Interpolation of query variable
I'm not sure if this is a bug as the way I used it here isn't shown in any of the examples. But it was an unexpected issue that I came across and I figured I'll make note of it here in case someone else has this issue as well.
It looks like saving a query in a variable and then interpolating that in the back-ticks of the client resolves into a syntax error Error: syntax error at or near "$1".
For example, this resolves into that error:
const sqlQuery = `
SELECT * FROM table
`
const res = await sql`${sqlQuery}`
But this doesn't:
const res = await sql`SELECT * FROM table`
I guess it's important for the client to process whatever is in the backticks directly instead of processing the result of processed backticks. I'm not familiar enough with the mechanism of how backticks work so not sure what's happening.
Hi @johnEthicalTechnology .
Thanks for the good explanation.
Postgres.js doesn't allow using entire queries or query parts inside the tagged template as arguments.
Not yet at least, but you can follow progress in this issue - https://github.com/porsager/postgres/issues/12
For your use case where you have a full query, the solution is simply to make it a function if you wish to reuse it. That also allows you to pass any important variables should you need to.
So something like this:
const sqlQuery = () => sql`
SELECT * FROM table
`
// somewhere else
const res = await sqlQuery()
And if you need to pass specific arguments just use js functions as usual.
const sqlQuery = (id) => sql`
SELECT * FROM table where id = ${ id }
`
// somewhere else
const res = await sqlQuery(req.params.id)
I hope that clears things up for you 🙂
Yes it did. Thanks for the explanation! 😄
@porsager what if argument is the table name ? example : select MIN(DT) from ${symbol} this will not also work;
Hi @alzalabany
You'll need to wrap identifiers in sql(), so your example should work like this:
sql`select MIN(DT) from ${ sql(symbol) }`