带有json数组的Postgresql中的参数化查询
我想调用array_prepend到一个json []使用参数化查询。 我正在使用pg-promise npm包,但是它使用正常的node-postgres适配器。
我的查询是:
db.query(`update ${schema}.chats set messages = array_prepend('{"sender":"${sender}","tstamp":${lib.ustamp()},"body":$1}',messages) where chat_id = ${chat_id}` , message));
与“$ 1”相同。
它适用于非参数化查询。
以上代码产生:
{[错误:在“hiya”或附近的语法错误]
主要原因是为了避免sql注入(文档说,使用参数化查询时,他们充分逃脱)。
在你的查询中有2个问题。
第一个是你正在使用ES6模板string,同时也使用${propName}
语法的sql格式。
从图书馆的文件 :
命名参数是使用语法$ * propName *定义的,其中*是以下任何一个打开 – closures对:{},(),[],<>,//,所以您可以使用一个自己喜欢的,但请记住{}也用于ES6模板string中的expression式。
所以你要么从ES6模板string改变为标准string,要么简单地切换到其他variables语法,比如$/propName/
或者$[propName]
,这样你就可以避免冲突。
第二个问题正如我在前面的评论中指出的那样,当生成正确的SQL名称时,使用logging为SQL名称的内容 。
下面是查询格式更清晰的方法:
db.query('update ${schema~}.chats set messages = array_prepend(${message}, messages) where chat_id = ${chatId}', { schema: 'your schema name', chatId: 'your chat id', message: { sender: 'set the sender here', tstamp: 'set the time you need', body: 'set the body as needed' } } );
如果您怀疑要执行什么样的查询,最快速的方法是通过pgp.as.format(query, values)
来查看,这将为您提供确切的查询string。
如果你仍然想使用ES6模板string,那么你可以将string更改为:
`update $/schema~/.chats set messages = array_prepend($/message/, messages) where chat_id = $/chatId/`
这只是一个例子,语法是灵活的。 只记得不要使用ES6模板string格式化将值注入到查询中,因为ES6模板不知道如何正确地格式化JavaScripttypes以符合PostgreSQL,只有库知道它。