Skip to content

Interpolation of query variable #214

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
johnEthicalTechnology opened this issue Aug 19, 2021 · 4 comments
Closed

Interpolation of query variable #214

johnEthicalTechnology opened this issue Aug 19, 2021 · 4 comments

Comments

@johnEthicalTechnology
Copy link

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.

@porsager
Copy link
Owner

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 - #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 🙂

@johnEthicalTechnology
Copy link
Author

johnEthicalTechnology commented Sep 14, 2021

Yes it did. Thanks for the explanation! 😄

@alzalabany
Copy link

@porsager what if argument is the table name ? example : select MIN(DT) from ${symbol} this will not also work;

@porsager
Copy link
Owner

porsager commented Oct 8, 2021

Hi @alzalabany

You'll need to wrap identifiers in sql(), so your example should work like this:

sql`select MIN(DT) from ${ sql(symbol) }`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants