简体   繁体   English

从pgPromise查询结果中获取执行的SQL语句

[英]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 . 我正在编写一个使用node和pg-promise对多个postgres数据库进行查询的API。

I'm interested in getting the executed SQL statement from query result. 我有兴趣从查询结果中获取执行的SQL语句。 Something like pg-monitor outputs to console. 类似于pg-monitor输出到控制台。 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. 我已经设置了pg-monitor,并且注意到有一个setLog方法可以用来获取所需的数据,但是如果我可以从执行查询的地方获取相同的数据,那将是完美的。

Point of this would be to enable the API to return both the query results and the metadata like the executed SQL. 这样做的目的是使API能够返回查询结果和元数据(如已执行的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. 当查询格式出现问题时,任何查询方法都会在其catch部分中报告该问题,而如果存在问题,则直接使用as.format函数会引发错误,因为格式是同步的。

UPDATE 更新

With pg-promise version 8.2.0 and later you can even do the following: 使用pg-promise版本8.2.0和更高版本,您甚至可以执行以下操作:

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. 这样更安全,因为任何与查询格式相关的错误都将由查询方法处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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