2

For example I have a query like:

      const rows = await db.query(
        "SELECT * FROM $1 WHERE email = $2 AND password = $3",
        [tableName, email, password]
      );

It gives me a syntax error.

FluffyBeing
  • 448
  • 1
  • 11
  • 27

1 Answers1

3

This is not possible, parameterised queries only work for values (instead of literals) but not for identifiers. You will need to build the SQL string:

const rows = await db.query(
  `SELECT * FROM ${db.escapeIdentifier(tableName)} WHERE email = $1 AND password = $2`,
  [email, password]
);

(Assuming the db is a PgClient)

If you know the possible values of the tableName variable beforehand, you might get away without escaping; if you don't, you better also specify the schema explicitly.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375