Skip to content

Commit

Permalink
improve conditional selects recipe
Browse files Browse the repository at this point in the history
  • Loading branch information
koskimas committed Aug 3, 2023
1 parent 143b18f commit 2a75720
Showing 1 changed file with 4 additions and 1 deletion.
5 changes: 4 additions & 1 deletion site/docs/recipes/conditional-selects.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ async function getPerson(id: number, withLastName: boolean) {
let query = db.selectFrom('person').select('first_name').where('id', '=', id)

if (withLastName) {
// ❌ The type of `query` doesn't change here
query = query.select('last_name')
}

Expand All @@ -32,10 +33,12 @@ with `last_name` selection is `B` which extends `A` but also contains informatio
about the new selection. When you assign an object of type `B` to `query` inside
the `if` statement, the type gets downcast to `A`.

You can write code like this to add conditional `where`, `groupBy`, `orderBy` etc.
:::info
You _can_ write code like this to add conditional `where`, `groupBy`, `orderBy` etc.
statements that don't change the type of the query builder, but it doesn't work
with `select`, `returning`, `innerJoin` etc. that _do_ change the type of the
query builder.
:::

In this simple case you could implement the method like this:

Expand Down

1 comment on commit 2a75720

@vercel
Copy link

@vercel vercel bot commented on 2a75720 Aug 3, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

kysely – ./

kysely.dev
www.kysely.dev
kysely-git-master-kysely-team.vercel.app
kysely-kysely-team.vercel.app

Please sign in to comment.