A seguito di questo articolo: Performance Boost da pg-promise biblioteca e il suo approccio suggerito:
// 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(',');
};
}
Un esempio di utilizzo, esattamente come nel tuo caso:
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
});
E che possa funzionare con un matrice di oggetti pure:
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
Per un approccio ad alte prestazioni tramite una singola query INSERT
, vedere Multi-row insert with pg-promise.
C'è un motivo non si può semplicemente eseguire INSERT due volte? –
per quanto riguarda la documentazione di pg questo approccio è molto indesiderabile a causa della riduzione delle prestazioni – stkvtflw
Se l'esecuzione di 2 inserti invece di 1 può mettere in pericolo le prestazioni dell'applicazione, quindi 'nodo-postgres', non è affatto per te. Ma credo che tu stia guardando nel modo sbagliato, cercando di ottimizzare dove non dovresti. Questa libreria può inserire facilmente 10.000 record in meno di 1 secondo. –