kysely icon indicating copy to clipboard operation
kysely copied to clipboard

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

Open kasvith opened this issue 2 years ago • 7 comments

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()

kasvith avatar Apr 30 '23 20:04 kasvith

Hey 👋

I think this might fit

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

rows[0].result

igalklebanov avatar May 01 '23 06:05 igalklebanov

its also good

kasvith avatar May 01 '23 07:05 kasvith

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 avatar Nov 24 '23 09:11 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

capaj avatar Nov 24 '23 09:11 capaj

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 avatar Nov 24 '23 09:11 capaj

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

capaj avatar Nov 24 '23 09:11 capaj

@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.

igalklebanov avatar Nov 24 '23 09:11 igalklebanov