node-mysql2 icon indicating copy to clipboard operation
node-mysql2 copied to clipboard

[Question] Automatic unescaping for column names and tables

Open KrofDrakula opened this issue 5 years ago • 2 comments

I've recently posted a bug in the base library for mysql, but I'm not sure if this library shares the same problem:

https://github.com/mysqljs/mysql/issues/2391

When using mysql2 as our library, column names are incorrectly unescaped and reserved keywords conflict with column names like from, to, default, etc.

Am I doing something wrong when attempting to unescape the names in the queries?

Pasting the content of the original issue here for convenience:


Consider the following table:

CREATE TABLE example (
  `from` DATE NOT NULL
);

from is a reserved SQL keyword. If you try to insert a row into that table using named columns, the from column is not escaped, which causes a syntax error. I haven't found a way to force the library to not remove escapes for this column name even after forcing it to insert a raw value:

// this query unescapes "`from`" into "from"
connection.query(
  "INSERT INTO example (`from`) VALUES (?)",
  ["2020-01-01"]
);

// this query does the same
connection.query(
  "INSERT INTO example (?) VALUES (?)",
  [mysql.raw('`from`'), "2020-01-01"]
);

This also affects exports from MySQL that contain backtick-escaped column names that are reserved keywords when being passed to the query function after reading from a file.

Is there something I'm missing? Is there a way to force identifiers to always be escaped in the final query?

KrofDrakula avatar Aug 27 '20 09:08 KrofDrakula

Can't you use

connection.query(
  "INSERT INTO example (`?`) VALUES (?)",
  ["from", "2020-01-01"]
);

testn avatar Oct 28 '21 14:10 testn

this query unescapes "`from`" into "from"

Are you sure this is true @KrofDrakula ?

const SqlString = require('sqlstring');
const inputSql = "INSERT INTO example (`from`) VALUES (?)";
const sql = SqlString.format(inputSql, ["2020-01-01"]);
console.log(sql);

this example prints

INSERT INTO example (`from`) VALUES ('2020-01-01')

sidorares avatar Oct 29 '21 01:10 sidorares