Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pg-promise number of updated rows

I am using the pg-promise NodeJS module. At some point, I am updating one of my database's table. I would like to know how many rows have been updated by the query, is it possible?

Below is part of my code:

var queryText = "UPDATE public.mytable SET whatever = $1 WHERE criteria1=$2 AND criteria2=$3;",
    queryParam = [
      value1,
      value2,
      value3
    ];

    postgres.none(queryText, queryParam)
    .then((value) => {
      // how can I know at this point how many rows have been updated
      resolve(result);

    })
    .catch(err => {
      // it doesn't go here when zero row has been updated
      reject(err);
    });

Thank you!

like image 664
nakurai Avatar asked Jun 26 '17 15:06

nakurai


1 Answers

I'm the author of pg-promise. In order to access the advanced query-result details, you need to execute the query via method result. And in your case you would access property rowCount:

db.result(query, values, r => r.rowCount)
    .then(count => {
       // count = number of rows affected (updated or deleted) by the query
    })
    .catch(error => {
    });

P.S. You do not need to use resolve(result) inside .then or reject(err) inside .catch, as all query methods of pg-promise already return promises.

UPDATE

Newer, ES7 syntax:

const {rowCount} = await db.result(query, values);
like image 136
vitaly-t Avatar answered Oct 22 '22 08:10

vitaly-t