kysely-org / kysely

A type-safe typescript SQL query builder
https://kysely.dev
MIT License
10.22k stars 259 forks source link

UNION expression select column type can still be interpereted null despite IS NOT NULL WHERE statement #915

Closed codygordon closed 5 months ago

codygordon commented 5 months ago

Take this expression builder example:

eb(
  'folderId',
  'in',
  eb
    .selectFrom('folder')
    .select(['id'])          
    .union(
      eb
        .selectFrom('contentPermission')
        .select(['folderId as id'])
        .where('contentPermission.folderId', 'is not', null)
    ),
)

The contentPermission table definition has folderId as a nullable column, so TS is throwing an error as the folderId type does not exactly match the "parent" query id column type (not nullable), however we know the union result would never result in any null values due to the where statement.

Screen Shot 2024-03-17 at 3 32 06 PM.

In lieu of a fix, is there a recommended workaround for this situation?

koskimas commented 5 months ago

This has been answered many times. It's impossible to fix this for anything other than trivial cases, and even that fix would complicate the types a lot and basically make the library unusable. The query builder type would be changed by where calls, making reassignment to the same variable often impossible. All that just to fix trivial one condition expressions. As soon as there's a more complex where statement, it wouldn't be possible anymore.

koskimas commented 5 months ago

I just added an example for dealing with these cases

https://kysely.dev/docs/examples/SELECT/not-null

codygordon commented 5 months ago

Thank you, appreciate the response!