kysely-org / kysely

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

Question: Can the database schema be modelled with generics? #495

Closed f0rr0 closed 1 year ago

f0rr0 commented 1 year ago

Example:

export type GenericDB<T extends Record<string, string>> = {
  sessions: T
}

export const createPostgresClient = <T extends Record<string, string>>(config: PoolConfig) =>
  new Kysely<GenericDB<T>>({
    dialect: new PostgresJSDialect(config),
  })

const test= async <T extends Record<string, string>>(session: T) => {
  const client = createPostgresClient<T>({})
  // does not work
  return await client.insertInto('sessions').values(session).returningAll().executeTakeFirstOrThrow()
}
f0rr0 commented 1 year ago

A possible use case I have is that I am authoring a library in which the consumer can provide the type for a particular column in a table for example.

f0rr0 commented 1 year ago

The example works if generic is removed:


const test = async () => {
  // removed generic
  const client = createPostgresClient<{ name: string }>({})
  // works now
  return await client.insertInto('sessions').values({ name: 'something' }).returningAll().executeTakeFirstOrThrow()
}
koskimas commented 1 year ago

That's not possible I'm afraid.