kysely-org / kysely

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

Question about a generic getById #995

Closed Guid75 closed 1 month ago

Guid75 commented 1 month ago

Brand new user of this fantastic library, I'm searching a way to write a generic function to handle the getById classic usecase, here is my naive approach:

import { Kysely, Selectable } from "kysely";

export type FooTable = {
  id: string;
  name: string;
  fromFoo: boolean;
};

export type BarTable = {
  id: string;
  name: string;
  fromBar: string;
}

type Tables = {
  foo: FooTable;
  bar: BarTable;
};

export async function getById<TableName extends keyof Tables>(
  dataSource: Kysely<Tables>,
  tableName: TableName,
  id: string
) {
  const query = dataSource
    .selectFrom(tableName)
    .selectAll()
    .where("id", "=", id);

  return await query.execute();
}

Here is the playground link

I don't really get why I cannot pass the id parameter into the where clause :( What did I miss?

koskimas commented 1 month ago

Works if you simplify it.

But in general you shouldn't try to write generic code like this with Kysely. Kysely's types are extremely strict and it's hard to combine strict and generic. Your example was probably not a real use case, but you saved very little code by having that helper.

Guid75 commented 1 month ago

Ok, thank you very much, I can live with some little repetitions