node-mysql2
node-mysql2 copied to clipboard
[Question] Automatic unescaping for column names and tables
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
);
fromis a reserved SQL keyword. If you try to insert a row into that table using named columns, thefromcolumn 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
queryfunction 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?
Can't you use
connection.query(
"INSERT INTO example (`?`) VALUES (?)",
["from", "2020-01-01"]
);
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')