使用 pg-promise 记录特定的 postgresql 查询

Log specific postgresql query using pg-promise

我正在使用 pg-promise 包和 Nodejs 来执行 PostgreSQL 查询。我想查看执行的查询。仅特定查询,例如,我想调试的一个查询。

我可以看到一种推荐的方法是使用 pg-monitor to catch the events and log them as mentioned here in the examples documentation

在不使用 pg-monitor 的情况下,是否有一种简单的方法可以只打印已执行的准备好的查询。我在文档中看不到它。

示例:

db.query("SELECT * FROM table WHERE id = $/id/", {id: 2})

如何打印此查询以产生?

SELECT * FROM table WHERE id = 2

is there a simple way to just print the prepared query that is executed...

一般查询 - 是的,请参见下文。 A Prepared Query - 不,根据定义,它们是在服务器端格式化的。

const query = pgp.as.format('SELECT * FROM table WHERE id = $/id/', {id: 2});
console.log(query);
await db.any(query);

并且如果您想打印模块执行的所有查询,而不在初始化库时使用 pg-monitor, simply add event query 处理程序:

const initOptions = {
  query(e) {
    console.log(e.query);
  }
};
const pgp = require('pg-promise')(initOptions);