kysely-org / kysely

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

[Feature]: Allow executing raw queries with a more idiomatic way #455

Open kasvith opened 1 year ago

kasvith commented 1 year ago

Currently executing raw queries has the following structure

sql`SELECT 1 AS result`.execute(kysely)

It would be nice to have it the other way around as well as people naturally tend to think with the current instance first.

kysely.execute(sql`SELECT 1 AS result`)

or

kysely.raw(sql`SELECT 1 AS result`).execute()
igalklebanov commented 1 year ago

Hey 👋

I think this might fit

const { rows } = await db.executeQuery(sql<{ result: number }>`select 1 as result`)

rows[0].result
kasvith commented 1 year ago

its also good

capaj commented 9 months ago

does this still work? I am trying to do

          await trx.executeQuery(
            sql<any>`ALTER SCHEMA ${current.subdomain} RENAME TO ${subdomain};`
          )

and I keep getting this query cannot be compiled to SQL

capaj commented 9 months ago

ok this works ok

await sql`ALTER SCHEMA "test" RENAME TO "test23"`.execute(trx)

but when I try to use variables in the template it throws

capaj commented 9 months ago

sorry for spamming. This is most likely a problem in pgPool as it has the same problem with the parameter for this query. TIL you cannot rename a schema in a stored procedure

capaj commented 9 months ago

BTW on this note, is there a way to do raw query with plain old string literal in kysely?

igalklebanov commented 9 months ago

@capaj

ok this works ok

await sql`ALTER SCHEMA "test" RENAME TO "test23"`.execute(trx)

but when I try to use variables in the template it throws

Some engines don't support any parameters in DDL, or in some queries. Try using sql.ref or sql.raw in those interpolated positions.

BTW on this note, is there a way to do raw query with plain old string literal in kysely?

Check sql's methods. e.g. sql.raw.