kysely-org / kysely

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

Is it possible to configure Kysely to return `foo | undefined` instead of `foo | null`? #515

Closed yannxaver closed 1 year ago

yannxaver commented 1 year ago

Kysely returns nullable columns as foo | null. In my application code I prefer to use undefined instead of null. Hence I have to convert all foo | null fields into foo | undefined after retrieving data with Kysely. Is it possible to configure Kysely to return foo | undefined instead of foo | null?

igalklebanov commented 1 year ago

Hey 👋

This is not possible with Kysely.

There's no such thing as undefined in SQL.

All built-in dialects use drivers that, by default, transform sql nulls to js nulls. If you change foo | null to foo | undefined, you'd have to also align runtime results, otherwise it's not type-safe.

Supporting this requirement might hit compile-time performance and project maintainability (added type complexity).

You could wrap your queries like this (roughly):

import { InferResult } from 'kysely'

type Undefinedify<O> = { [K in keyof O]: null extends O[K] ? Exclude<O[K], null> | undefined : O[K] }

const query = db.selectFrom('person').selectAll()

type Result = InferResult<typeof query>

return await query.$castTo<Undefinedify<Result>>().execute()

This is half the solution, you still need to transform nulls to undefined, probably in underlying driver configuration (if not, than in a Kysely plugin).