node-postgres icon indicating copy to clipboard operation
node-postgres copied to clipboard

No batch insert and update query support

Open IshanCSE opened this issue 10 years ago • 5 comments

Want to pass multiple insert values in to single query. Is there any other way to do it?

IshanCSE avatar Mar 02 '16 05:03 IshanCSE

//yes you can simply do that using bluebird and pg var promise = require('bluebird'); var options = { promiseLib: promise }; var pgp = require('pg-promise')(options); var db = pgp(cn); //cn is your connection string

// array is you array of values and first argument to t.query is your query using individual values of array in u db.tx(function(t){ var queries=array.map(function(u){ return t.query('', u); }); return t.batch(queries);
}) .then(function(){ //res }) .catch(function(error){ //error response });

Dineshagrawal85 avatar Mar 03 '16 04:03 Dineshagrawal85

Want to pass multiple insert values in to single query. Is there any other way to do it?

You can concatenate inserts into a single insert query. For example, see here.

vitaly-t avatar Mar 06 '16 18:03 vitaly-t

I am not aware of a way to batch update into a single query. For batch insert, see #957.

rpedela avatar Mar 22 '16 20:03 rpedela

https://github.com/brianc/node-postgres/issues/957#issuecomment-295583050

charmander avatar Jul 27 '17 18:07 charmander

case this still helps: you can use temp tables to achieve this - like running those two statements:

create temp table coffeeTmp on commit drop as select 'Homer' as name, 'latte' as coffee union select 'Marge' as name, 'expresso' as coffee

update coffeeOrders c 
  set coffee=t.coffee
from coffeeTmp t
where c.name=t.name

when running via node-postgres, it would become sth like

c.query('begin')
c.query('create temp table coffeeTmp on commit drop as select $1 as name, $2 as coffee union select $3 as name, $4 as coffee', ['Homer', 'latte', 'Marge', 'expresso'])
c.query('update coffeeOrders c  set coffee=t.coffee from coffeeTmp t where c.name=t.name')
// (more here)
c.query('commit')

just BTW: insert would work as well - and so would upsert by running above update followed by an insert like

insert into coffeeOrders (name, coffee)
  select t.name, t.coffee from coffeeTmp t left join coffeeOrders c on t.name=c.name where c.name is null

sebastianrothbucher avatar Feb 20 '22 09:02 sebastianrothbucher