Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return insert query result values using pg-promise helpers

I am using pgp.helpers.insert to save data into PostgreSQL which is working well. However, I need to return values to present in a response. I am using:

this.collection.one(this.collection.$config.pgp.helpers.insert(values, null, 'branch'))

which returns no data.

What I want to be able to do is return the branch id after a successful insert, such as:

INSERT into branch (columns) VALUES (values) RETURNING pk_branchID
like image 861
Faz Avatar asked Jan 31 '17 10:01

Faz


People also ask

How to return data from a promise in JavaScript?

Now you are able to return data from JavaScript promise. Return Data From Promise using ES6 Async/Await JavaScript ES6 provides a new feature called async/await which can used as an alternative to Promise.then. Using async/await you can write the above code in synchronous manner without any.then.

Is there a way to stream data from PG-query-stream?

See Data Imports with a complete example. You can use pg-query-stream - high-performance, read-only query streaming via cursor (doesn't work with pgNative option). Its code example can be re-implemented via pg-promise as follows:

How to wait for promise to be resolved after getpromise?

This happens because after making a call to getResult method, it in turns calls the getPromise method which gets resolved only after 2000 ms. getResult method doesn’t wait since it doesn’t returns a promise. So, if you return a promise from getResult method it can then be used to wait for the Promise to get resolved. Let’s try it.

Why does getpromise return a promise after 2000ms?

This happens because after making a call to getResult method, it in turns calls the getPromise method which gets resolved only after 2000 ms. getResult method doesn’t wait since it doesn’t returns a promise. So, if you return a promise from getResult method it can then be used to wait for the Promise to get resolved.


1 Answers

Simply append the RETURNING... clause to the generated query:

var h = this.collection.$config.pgp.helpers;
var query = h.insert(values, null, 'branch') + 'RETURNING pk_branchID';

return this.collection.one(query);

You must have a large object there if you want to automatically generate the insert. Namespace helpers is mostly valued when generating multi-row inserts/updates, in which case a ColumnSet is used as a static variable:

var h = this.collection.$config.pgp.helpers;
var cs = new h.ColumnSet(['col_a', 'col_b'], {table: 'branch'});
var data = [{col_a: 1, col_b: 2}, ...];

var query = h.insert(data, cs) + 'RETURNING pk_branchID';

return this.collection.many(query);

Note that in this case we do .many, as 1 or more rows/results are expected back. This can even be transformed into just an array of id-s:

return this.collection.map(query, [], a => a.pk_branchID);

see: Database.map

like image 143
vitaly-t Avatar answered Sep 29 '22 07:09

vitaly-t