【问题标题】:How do I parameterize a Postgres array value in Node / pg-pool如何在 Node / pg-pool 中参数化 Postgres 数组值
【发布时间】:2020-11-19 20:13:57
【问题描述】:

我正在使用包含运算符 @> 查询数组列 (style text[])。我的原始查询是:

SELECT * FROM songs WHERE style @> '{Acoustic}'

当我将它放入节点(使用pg-pool)并尝试对其进行参数化时,值引用周围的大括号似乎阻止它正常工作。请注意以下示例:

const style = 'Acoustic';

// this works, but I don't want to in-line like this:
const { rows } = await pool.query(`SELECT * FROM songs WHERE style @> '{` + style + `}'`);

// this fails with 'error: bind message supplies 1 parameters, but prepared statement "" requires 0'
const { rows } = await pool.query(`SELECT * FROM songs WHERE style @> '{$1}'`, [style]);

参数化的正确方法是什么?

【问题讨论】:

  • 请注意,我使用另一种查询:pool.query('SELECT * FROM songs WHERE $1 = ANY (style)', [style]);,但我想知道是否有办法使用上面的表单。

标签: node.js postgresql pgpool node-pg-pool


【解决方案1】:
const { rows } = await pool.query(`SELECT * FROM songs WHERE style @> '{$1}'`, [style]);

这里的$1,在引号中,只是被视为字符串的一部分,而不是可替代的变量。如果您希望传入一个标量并将其视为一个数组,您应该可以这样做:

const { rows } = await pool.query(`SELECT * FROM songs WHERE style @> ARRAY[$1]`, [style]);

另一种方法可能是让 node.js 直接绑定一个数组(未测试):

const { rows } = await pool.query(`SELECT * FROM songs WHERE style @> $1`, [[style]]);

【讨论】:

  • 您提供的两个选项都有效,让我更清楚如何使用数组列。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-20
  • 1970-01-01
  • 2017-05-18
  • 2021-12-16
  • 2021-07-13
  • 1970-01-01
相关资源
最近更新 更多