0

Hi came across this syntax in a node.js application, in which we are making a SELECT query to our postgres database.

app.get("/monsters/:id", (req, res, next) => {
    let id = req.params.id;
    pool.query(`SELECT * FROM monsters WHERE id = $1`, [id], (err, response) => {
        if (err) return next(err);
        console.log(response.rows);
        res.send(response.rows);
    })
});

I don't understand the follow the line: pool.query(SELECT * FROM monsters WHERE id = $1, [id], (err, response) => {

how does this kind of string literal work, where we have used $1 and passing an array?

Thank you

pi2018
  • 347
  • 2
  • 11
  • That's a [template literal](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals) – CertainPerformance Apr 21 '20 at 07:59
  • Also `$1` is not connected to the string literal - it's just a normal part of the text inside. It's used by the SQL engine to be replaced with an appropriate parameter. – VLAZ Apr 21 '20 at 08:00
  • it is adding the first element of the [id] array. So what does $1 represent? – pi2018 Apr 21 '20 at 08:02
  • It's the parameter in the array. It's just a parametarised query. – VLAZ Apr 21 '20 at 08:04
  • Thank you, so again this has to do with SQL syntax and not JS ? – pi2018 Apr 21 '20 at 08:06
  • @CertainPerformance While the string is stored as a template string there are no interpolation done here. The template string is a red-herring and this code would work the same way if you replace it with a regular string – slebetman Apr 21 '20 at 08:09

1 Answers1

3

This has nothing to do with javascript or node.js syntax. The string

`SELECT * FROM monsters WHERE id = $1`

is the same as:

"SELECT * FROM monsters WHERE id = $1"

because there is no interpolation done within the string.

From the point of javascript, $1 literally represents $1 and nothing else.

I don't quite know the library you are using for accessing postgres but it looks fairly obvious to me that $1 is mapped to the first element of [id] (which is just the value of id). It looks like the postgres library used maps $1 to ? in SQL syntax and moves the values in the second argument to the appropriate part of the generated sql query.

I would look at the documentation for the library used to access postgres for more info on the API.

slebetman
  • 109,858
  • 19
  • 140
  • 171