代码之家  ›  专栏  ›  技术社区  ›  rotarydial

如何在Node/pg池中参数化Postgres数组值

  •  0
  • rotarydial  · 技术社区  · 5 年前

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

    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]);
    

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

    0 回复  |  直到 5 年前
        1
  •  2
  •   jjanes    5 年前
    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]]);
    
    推荐文章