将 VALUES 子句作为查询参数传递

Passing VALUES clause as query parameter

我正在尝试重构使用 postgresql pg 模块的现有代码片段,看起来像这样:

let sql = `INSERT INTO jobs (title, type, label) VALUES ${stringValues}`;
        let { rows } = await pg.query(sql, []);

这里他们有 VALUES 子句作为计算的 stringValues 字符串,如下所示:

"('title1', 'type1', 'label1'),('title2', 'type2', 'label2')"

我试图让这个片段更加注入安全和优雅,通过 $1 传递参数。我已经尝试 VALUES array[][stringValues.split(',')] 作为 $1 传递 - 没有运气。 还尝试了 VALUES array[::record](SELECT array[::record])、各种 jsonb_ 转换等 - 仍然没有成功。

任何人都可以建议任何传递此类参数以插入 VALUES 的好方法吗?

对于相对少量的数据,最干净的方法是使用 pg-format 库。请参阅 from a similar question and this github issue 以供参考。

import format from "pg-format";

const values = [['title1', 'type1', 'label1'],['title2', 'type2', 'label2']]
const sql = `INSERT INTO jobs (title, type, label) VALUES %L`
const {rows} = await pg.query(format(sql,values))

如果您要批量加载大量数据。可能值得考虑使用性能更高的 COPY FROM command functionality implemented in pg-copy-streams