2016-01-25 9 views
8

una singola riga può essere inserito in questo modo:Come inserisco correttamente più file in PG con node-postgres?

client.query("insert into tableName (name, email) values ($1, $2) ", ['john', '[email protected]'], callBack) 

Questo approccio commenti automaticamente caratteri speciali.

Come si inseriscono più righe contemporaneamente?

ho bisogno di implementare questa:

"insert into tableName (name, email) values ('john', '[email protected]'), ('jane', '[email protected]')" 

posso solo usare gli operatori stringa js per compilare tali file manualmente, ma poi ho bisogno di aggiungere caratteri speciali fuggire in qualche modo.

+0

C'è un motivo non si può semplicemente eseguire INSERT due volte? –

+0

per quanto riguarda la documentazione di pg questo approccio è molto indesiderabile a causa della riduzione delle prestazioni – stkvtflw

+0

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. –

risposta

2

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.

2

Un altro modo utilizzando PostgreSQL funzioni JSON:

client.query('INSERT INTO table (columns) ' + 
     'SELECT m.* FROM json_populate_recordset(null::your_custom_type, $1) AS m', 
     [JSON.stringify(your_json_object_array)], function(err, result) { 
     if(err) { 
      console.log(err); 
     } else { 
      console.log(result); 
     } 
});