pg-promise number of updated rows
Asked Answered
B

1

10

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!

Bentz answered 26/6, 2017 at 15:18 Comment(0)
M
27

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);
Monteiro answered 26/6, 2017 at 15:30 Comment(6)
If you're in an async function, you can also do e.g. let result = await db.result('DELETE FROM mytable WHERE criteria1 = $1', ['foo'])Sayres
@DaveGray That is self-evident when one moves from ES6 to ES7 syntax. At least you could have used the example correctly, with the transformation r => r.rowCount argument, or the example won't work otherwise.Monteiro
You're right, it's not an exact drop-in replacement without doing let result = await db.result('DELETE FROM mytable WHERE criteria1 = $1', ['foo'], r => r.rowCount) - apologies to OP; in my use case I wanted to see the entire result object. Thanks for the library, it has saved me lots of time!Sayres
Added ES7 example.Monteiro
when used with insert on conflict do update, how do I find out how many rows it inserted vs updated?Phosphocreatine
@Phosphocreatine You can't. Postgres can only report how many rows have been affected/modified, without any specifics.Monteiro

© 2022 - 2024 — McMap. All rights reserved.