Sanitizing user inputs when the user input is a schema name in node postgres

筅森魡賤 提交于 2020-08-10 18:52:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!