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

prepared statements format error when filed is `JSON` type

Open serveryang opened this issue 8 months ago • 0 comments

let query='select  *  from ??  where (??=?) limit ?,? '
let params = ['certification', "cert->>'$.name'", 'myname', 0, 20];
let pool = mysql.createPool(poolOption);
let sql = pool.format(query, params);
//  the sql is not correct.
// correct query sql should be: select * from certification where cert->>'$.name' = ‘myname’ limit 0, 20

pool.format method will finally call escapeId(val, forbidQualified) in SqlString. the sqlstring module not update now. file: node_modules\sqlstring\lib\SqlString.js#18, code below:

SqlString.escapeId = function escapeId(val, forbidQualified) {
  if (Array.isArray(val)) {
    var sql = '';

    for (var i = 0; i < val.length; i++) {
      sql += (i === 0 ? '' : ', ') + SqlString.escapeId(val[i], forbidQualified);
    }

    return sql;
  } else if (forbidQualified) {
    return '`' + String(val).replace(ID_GLOBAL_REGEXP, '``') + '`';
  } else {
    return '`' + String(val).replace(ID_GLOBAL_REGEXP, '``').replace(QUAL_GLOBAL_REGEXP, '`.`') + '`';
  }
};

serveryang avatar Mar 13 '25 01:03 serveryang