简体   繁体   中英

Get executed SQL statement from pgPromise query result

I'm writing an API that does queries over multiple postgres databases using node and pg-promise .

I'm interested in getting the executed SQL statement from query result. Something like pg-monitor outputs to console. I've set up pg-monitor and noticed there is a setLog method which I can use to get the data I need, but it would be perfect if I could get the same data from the place I'm executing the query from.

Point of this would be to enable the API to return both the query results and the metadata like the executed SQL. Is this possible? Thanks!

it would be perfect if I could get the same data from the place I'm executing the query from.

In this case you can format the query yourself, log it and then pass it into the query method:

const query = pgp.as.format('SELECT * FROM table WHERE id = $1', 123);
console.log('QUERY:', query);
db.any(query).then().catch()

All query methods use this formatting function underneath.

Note the difference however. When there is an issue with the query formatting, any query method reports it within its catch section, while use of as.format function directly will throw an error, if there is an issue, because formatting is synchronous.

UPDATE

With pg-promise version 8.2.0 and later you can even do the following:

const query = values => {
    const q = pgp.as.format('SELECT * FROM table WHERE id = $1', values);
    console.log('QUERY:', q);
    return q;
};
db.any(query, values).then().catch()

It is safer this way, as any error related to query formatting will be handled by the query method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM