(node-postgres,pg)正确插入表名

H W*_*H W 8 sql postgresql node.js pg node-postgres

如果可以动态确定名称并且仍然阻止SQL注入攻击,那么如何正确提供表名?

例如:

以下作品,但我认为是不安全的:

dbclient.query("INSERT INTO " + table_name + " VALUES ($1, $2, $3)", [value_a, value_b, value_c])

我想等同于(但不起作用)的是:

dbclient.query("INSERT INTO $1 VALUES ($2, $3, $4)", [table_name, value_a, value_b, value_c])

编辑:我正在使用node-postgres:https://github.com/brianc/node-postgres.

Rob*_*kal 0

您可以使用正则表达式或其他验证逻辑手动检查表名的有效性。我可能会使用包含允许的表名的字典。

var tables = {users:'users', boats:'boats'};
table_name = tables[table_name];
if (! table_name) throw new Error();
dbclient.query("INSERT INTO " + table_name + " VALUES ($1, $2, $3)", [value_a, value_b, value_c])
Run Code Online (Sandbox Code Playgroud)

如果您计划生成大量动态 sql,请使用查询生成器,例如http://knexjs.org/