Следуя этой статье: Performance Boost из pg-promise библиотеки и ее Предложенный подход:
// Concatenates an array of objects or arrays of values, according to the template,
// to use with insert queries. Can be used either as a class type or as a function.
//
// template = formatting template string
// data = array of either objects or arrays of values
function Inserts(template, data) {
if (!(this instanceof Inserts)) {
return new Inserts(template, data);
}
this._rawDBType = true;
this.formatDBType = function() {
return data.map(d=>'(' + pgp.as.format(template, d) + ')').join(',');
};
}
Пример использования его, точно так, как в вашем случае:
var users = [['John', 23], ['Mike', 30], ['David', 18]];
db.none('INSERT INTO Users(name, age) VALUES $1', Inserts('$1, $2', users))
.then(data=> {
// OK, all records have been inserted
})
.catch(error=> {
// Error, no records inserted
});
И он будет работать с массив объектов:
var users = [{name: 'John', age: 23}, {name: 'Mike', age: 30}, {name: 'David', age: 18}];
db.none('INSERT INTO Users(name, age) VALUES $1', Inserts('${name}, ${age}', users))
.then(data=> {
// OK, all records have been inserted
})
.catch(error=> {
// Error, no records inserted
});
UPDATE
Для высокопроизводительного подхода с помощью одного запроса INSERT
см. Multi-row insert with pg-promise.
есть причина, вы не можете просто выполнить INSERT дважды? –
относительно документации pg этот подход очень нежелателен из-за снижения производительности. – stkvtflw
Если выполнение 2 вставок вместо 1 будет угрожать производительности вашего приложения, тогда 'node-postgres' не для вас вообще. Но я считаю, что вы смотрите на это неправильно, пытаясь оптимизировать, где вы не должны. Эта библиотека может легко вставить 10 000 записей менее чем за 1 секунду. –