问题
I am using https://node-postgres.com/ to write a fairly simple application, but I do have a complex constraint that has caused me issues. Namely, I need my SQL statement to select a schema based on user input
SELECT * FROM {some user value}.tableName
but when I attempt to parametrize this normally, I get a syntax error
{"errorType":"error","errorMessage":"syntax error at or near \"$1\""
Which seems to indicate that the value wasnt replaced as expected.
Is there a way to sanitize the incoming value without executing it in a query? or is there a proper way to parametrize this value in the query in a way that will execute properly?
(I would like to avoid a big library change to something like sequilize just to meet my basic needs)
回答1:
Turns out there is a great way to do this using the guts of the library! it digs into the prototype, so if this becomes a more regular thing looking into something like pg-format might be a good call. But for now this works.
const sanitizedKey = db.Client.prototype.escapeIdentifier(incomingData.orgKey)
const result = await db.query(builder(`
WITH policies_threatened_by_incident AS (
select p.alert_id, p.tiv, p.distance
from ${sanitizedKey}.wf_alert_policies_active p
...
shout out to the helpful contributors -> https://github.com/brianc/node-postgres/issues/2295#issuecomment-664767339
来源:https://stackoverflow.com/questions/62907228/sanitizing-user-inputs-when-the-user-input-is-a-schema-name-in-node-postgres