kysely-org / kysely

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

Type-safe `having` with aliases #552

Closed MatanYadaev closed 1 year ago

MatanYadaev commented 1 year ago

When you add an alias to query, Kysely doesn't allow accessing this alias in the having statement.

db
  .selectFrom('person')
  .select(sql<string>`concat(first_name, ' ', last_name)`.as('full_name'))
  // Error: Argument of type '"full_name"' is not assignable to parameter of type 'ReferenceExpression<From<Database, "person">, "person">'.(2345)
  .having('full_name', 'like', 'example');

Playground: https://stackblitz.com/edit/react-ts-g6juwy?file=playground.ts

igalklebanov commented 1 year ago

Hey 👋

Thanks for the playground link! 💪 (we have our own playground by the way, https://kyse.link)

This was a conscious decision:

MySQL supports this and PostgreSQL doesn't. We went with psql here. https://discord.com/channels/890118421587578920/1090830198234173521/1090845170599219230

You can do the following:

.having(sql.ref<string>('full_name'), 'like', 'example')

You could also make that select more type-safe:

.select((eb) =>
  sql<string>`concat(${eb.ref("first_name")}, ' ', ${eb.ref(
    "last_name",
  )})`.as("full_name"),
)

// or

.select((eb) =>
  eb.fn<string>("concat", ["first_name", sql.lit(' '), "last_name"]).as("full_name"),
)
MatanYadaev commented 1 year ago

Thanks for the quick and detailed reply!