Ответ 1
Следующая статья: Повышение производительности из библиотеки 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
});
ОБНОВЛЕНИЕ-1
Для высокопроизводительного подхода с помощью одного запроса INSERT
см. Многострочная вставка с pg-обещанием.
ОБНОВЛЕНИЕ 2-
Информация здесь довольно старая, см. последний синтаксис для пользовательского форматирования типов. То, что раньше было _rawDBType
, теперь является rawType
, а formatDBType
было переименовано в toPostgres
.