kysely-org / kysely

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

Is there a way to deduplicate parameters in template strings? #1032

Closed daviduzumeri closed 3 weeks ago

daviduzumeri commented 3 weeks ago

I'm working on moving a legacy-ish codebase from Sequelize to Kysely, and we've got a bunch of very beefy queries using a bunch of Postgres-specific stuff that would be extremely impractical (and, for now, time-consuming -- I'm not ruling out doing it in the future but we really want to pnpm remove sequelize ASAP) to rewrite using the query builder. These all got done using Sequelize's parameterized query function (which is real similar to Knex's and pg's under the hood), where you pass it a string with some parameters and then an object with the parameters to replace. This allows you to basically set variables to do null checks etc within the Postgres query, and also makes it so that if you pass in a parameter and use it multiple times in the query, it only gets sent in once.

I can't seem to replicate this functionality with the SQL template string in Kysely. I don't want to hand-bomb this using sql.raw for obvious reasons, I just want to be able to use parameterized queries and bind values directly. I've been skimming the code and reading docs/issues and I can't see anyone bringing this up, but is there any way to replicate this using Kysely? I can sort of hack around this by doing null checks in TS and letting stuff dedupe but it'd be great to not have to risk screwing things up in the switchover, and even better to just be able to set the queries as string literals and use them in both Sequelize and Kysely.

Any ideas? I'm sure this is a low-priority thing for the team since the whole point of Kysely is to not hand-bomb your own SQL, but I imagine this would be a huge benefit for people doing migrations off of legacy projects.

(I also know we could just use pg directly but we want to run these queries within Kysely transactions)

daviduzumeri commented 3 weeks ago

(Sorry, realized this is probably for the Discord)