我是《pg-promise》的作者.
在旧版本的库中,Performance Boost篇文章中的简化示例介绍了这一点,在编写高性能数据库应用程序时,这仍然是一本不错的读物.
较新的方法是依靠helpers namespace,这最终是灵活的,并优化了性能.
const pgp = require('pg-promise')({
/* initialization options */
capSQL: true // capitalize all generated SQL
});
const db = pgp(/*connection*/);
// our set of columns, to be created only once (statically), and then reused,
// to let it cache up its formatting templates for high performance:
const cs = new pgp.helpers.ColumnSet(['col_a', 'col_b'], {table: 'tmp'});
// data input values:
const values = [{col_a: 'a1', col_b: 'b1'}, {col_a: 'a2', col_b: 'b2'}];
// generating a multi-row insert query:
const query = pgp.helpers.insert(values, cs);
//=> INSERT INTO "tmp"("col_a","col_b") VALUES('a1','b1'),('a2','b2')
// executing the query:
await db.none(query);
见API:ColumnSetinsert.
这样的插入甚至不需要事务,因为如果一组值插入失败,则不会插入任何值.
您可以使用相同的方法生成以下任何查询:
- 单列
INSERT
- 多排
INSERT
- 单列
UPDATE
- 多排
UPDATE
使用${}符号的插入是否受到sql注入的保护?
是的,但不是独自一人.如果您要动态插入模式/表/列名,那么使用SQL Names非常重要,这将保护您的代码不受SQL注入的影响.
相关问题:PostgreSQL multi-row updates in Node.js
Q: How to get 100 of each new record at the same time?
A:只需将RETURNING id
添加到查询中,并使用方法many执行即可:
const query = pgp.helpers.insert(values, cs) + ' RETURNING id';
const res = await db.many(query);
//=> [{id: 1}, {id: 2}, ...]
或者更好的方法是,获取id-s,并使用方法map将结果转换为整数数组:
const res = await db.map(query, undefined, a => +a.id);
//=> [1, 2, ...]
要了解我们为什么在那里使用+
,请参见:pg-promise returns integers as strings.
UPDATE-1
有关插入大量记录的信息,请参见Data Imports.
UPDATE-2
使用v8.2.1及更高版本,您可以将静态查询生成包装到一个函数中,这样就可以在查询方法中生成,以便在查询生成失败时拒绝:
// generating a multi-row insert query inside a function:
const query = () => pgp.helpers.insert(values, cs);
//=> INSERT INTO "tmp"("col_a","col_b") VALUES('a1','b1'),('a2','b2')
// executing the query as a function that generates the query:
await db.none(query);