代码之家  ›  专栏  ›  技术社区  ›  Null Salad

如何使用postgresql和nodejs将变量安全地插入数组?

  •  0
  • Null Salad  · 技术社区  · 5 月前

    我可以像这样不安全地修改数组:

    await pool.query(`UPDATE profiles SET friends = friends || '{"${newFriend}"}'`);
    

    然而,这会让你对SQL注入等持开放态度。理想的做法是将其放入末尾的数组中,如下所示

    await pool.query(`UPDATE profiles SET friends = friends || $1`, [newFriend]);
    

    但这并不完全正确,是吗?我需要添加字符串 "{' '}" 不知何故。做这件事的正确方法是什么?

    1 回复  |  直到 5 月前
        1
  •  1
  •   Ry-    5 月前

    pg支持开箱即用序列化数组参数:

    await pool.query(`UPDATE profiles SET friends = friends || $1`, [[newFriend]]);
    

    您还可以在查询端使用 array constructor :

    await pool.query(`UPDATE profiles SET friends = friends || ARRAY[$1]`, [newFriend]);
    

    无论哪种方式,您都可以避免手动使用数组的文本表示,这是理想的。

    数组连接运算符也可以直接处理单个元素,但我觉得这有点不舒服。

    // substitute `text` with the underlying type of the array, if not `text`
    await pool.query(`UPDATE profiles SET friends = friends || $1::text`, [newFriend]);