mysqljs / named-placeholders

PDO-style named to unnamed placeholders compiler
MIT License
22 stars 13 forks source link

?? before a named placeholder makes the named placeholder undefined #20

Closed ST3AMMACH1N3 closed 1 year ago

ST3AMMACH1N3 commented 1 year ago

NOTE: This is using mysql2

let query = "SELECT ::column FROM ??";
let array = ["test_table"];
let params = { column: "id", ...array };
let [response] = await connection.query(query, params);

Correctly formats to

SELECT `id` FROM `test_table`

But when the '??' is first it seems to not now how to substitute named placeholders any more, leaving it undefined

let query= "SELECT ?? FROM ::table";
let array = ["id"];
let params = { table: "test_table", ...array };
let [response] = await connection.query(query, params);

Gives me this

SELECT `id` FROM `undefined`

And then crashes giving Error: Table 'test_db.undefined' doesn't exist

sidorares commented 1 year ago

I don't think we support mix of named and unnamed placeholders, just use named everywhere:

const np = require('named-placeholders')();
let query= "SELECT ::id FROM ::table";
let params = { table: "test_table", id: "id" };
let [q, p] = np(query, params);
console.log(q, p);

prints SELECT ?? FROM ?? [ 'id', 'test_table' ]

Also I'm not sure if you intend to do exactly what you do, but the result of spreading array to object is a new object with array indices as keys ( converted to string ):

let array = ["id"];
let params = { table: "test_table", ...array };
console.log(params);

prints { '0': 'id', table: 'test_table' }

ST3AMMACH1N3 commented 1 year ago

I DID intend to do what I did. And the first google result for "named placeholders mysql2" is a stack overflow from 2022 talking about them and giving examples of mixing named and unnamed placeholders as I did in my example. Stack Overflow. I understand that I can obviously use only named placeholders, just an odd issue I discovered.