Skip to content

Commit

Permalink
fix $if inside with is any.
Browse files Browse the repository at this point in the history
  • Loading branch information
igalklebanov authored and koskimas committed Dec 29, 2023
1 parent 87d1041 commit 10e282b
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/query-builder/select-query-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1416,7 +1416,7 @@ export interface SelectQueryBuilder<DB, TB extends keyof DB, O>
$if<O2>(
condition: boolean,
func: (qb: this) => SelectQueryBuilder<any, any, O & O2>
): SelectQueryBuilder<DB, TB, O & Partial<O2>>
): SelectQueryBuilder<DB, TB, O & Partial<Omit<O2, keyof O>>>

/**
* Change the output type of the query.
Expand Down Expand Up @@ -2051,14 +2051,14 @@ class SelectQueryBuilderImpl<DB, TB extends keyof DB, O>
$if<O2>(
condition: boolean,
func: (qb: this) => SelectQueryBuilder<any, any, O & O2>
): SelectQueryBuilder<DB, TB, O & Partial<O2>> {
): SelectQueryBuilder<DB, TB, O & Partial<Omit<O2, keyof O>>> {
if (condition) {
return func(this)
}

return new SelectQueryBuilderImpl<DB, TB, O & Partial<O2>>({
return new SelectQueryBuilderImpl({
...this.#props,
})
}) as any
}

$castTo<T>(): SelectQueryBuilder<DB, TB, T> {
Expand Down
41 changes: 41 additions & 0 deletions test/typings/test-d/with.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,47 @@ async function testWith(db: Kysely<Database>) {
}[]
>(r4)

// https://github.com/kysely-org/kysely/issues/785
const r5 = await db
.with('person_projection', (qb) =>
qb
.selectFrom('person')
.select(['first_name', 'last_name'])
.$if(true, (qb) => qb.where('first_name', 'is not', null))
)
.selectFrom('person_projection')
.selectAll()
.$if(true, (qb) => qb.where('first_name', 'is not', null))
.execute()

expectType<
{
first_name: string
last_name: string | null
}[]
>(r5)

// testing fix of https://github.com/kysely-org/kysely/issues/785 didn't break $if that adds columns to the projection.
const r6 = await db
.with('person_projection', (qb) =>
qb
.selectFrom('person')
.select(['first_name', 'last_name'])
.$if(true, (qb) => qb.select('age'))
)
.selectFrom('person_projection')
.selectAll()
.$if(true, (qb) => qb.where('first_name', 'is not', null))
.execute()

expectType<
{
first_name: string
last_name: string | null
age: number | undefined
}[]
>(r6)

// Different columns in expression and CTE name.
expectError(
db
Expand Down

0 comments on commit 10e282b

Please sign in to comment.