K
Kysely6mo ago
Robin

Arbitrary insert statement

I have a bit of an edge case where I want to build a query that is dynamic based on user input (it's part of an interactive tutorial). Is there a way to build an insert statement where the object name is an arbitrary string? Alternatively, is there some way to do this with sql framemgents, but still make the value a parameter? I'm imagining a sql.parameter function, but I don't see anything like that in the docs.
Solution:
Everything is a parameter by default when you use the sql tag.
sql`insert into foo (id) values (${id})`.execute(db)
sql`insert into foo (id) values (${id})`.execute(db)
...
Jump to solution
3 Replies
Solution
koskimas
koskimas6mo ago
Everything is a parameter by default when you use the sql tag.
sql`insert into foo (id) values (${id})`.execute(db)
sql`insert into foo (id) values (${id})`.execute(db)
id in that example is sent as a parameter. It's not interpolated to the SQL.
koskimas
koskimas6mo ago
Alternatively you can use Kysely<any> to build any insert query https://kyse.link/?p=s&i=DCFGKru80WvqqZ9KXBMd
Robin
Robin6mo ago
Oh great! I don't know why I thought directly interpolating like that wouldn't work.