如何在事务中获取当前查询

How to get current query inside a transaction

我试图从 pg_stats_activity 获取当前查询,但没有按预期工作。

在交易之外一切正常:

pagetest=# select query from pg_stat_activity where pid = pg_backend_pid() and 1 is not null;
                                       query                                        
------------------------------------------------------------------------------------
 select query from pg_stat_activity where pid = pg_backend_pid() and 1 is not null;
(1 row)

pagetest=# select query from pg_stat_activity where pid = pg_backend_pid() and 2 is not null;
                                       query                                        
------------------------------------------------------------------------------------
 select query from pg_stat_activity where pid = pg_backend_pid() and 2 is not null;
(1 row)

pagetest=# select query from pg_stat_activity where pid = pg_backend_pid() and 3 is not null;
                                       query                                        
------------------------------------------------------------------------------------
 select query from pg_stat_activity where pid = pg_backend_pid() and 3 is not null;
(1 row)

但是在交易中我得到了错误的结果:

pagetest=# begin;
BEGIN
pagetest=# select query from pg_stat_activity where pid = pg_backend_pid() and 1 is not null;
                                       query                                        
------------------------------------------------------------------------------------
 select query from pg_stat_activity where pid = pg_backend_pid() and 1 is not null;
(1 row)

pagetest=# select query from pg_stat_activity where pid = pg_backend_pid() and 2 is not null;
                                       query                                        
------------------------------------------------------------------------------------
 select query from pg_stat_activity where pid = pg_backend_pid() and 1 is not null;
(1 row)

pagetest=# select query from pg_stat_activity where pid = pg_backend_pid() and 3 is not null;
                                       query                                        
------------------------------------------------------------------------------------
 select query from pg_stat_activity where pid = pg_backend_pid() and 1 is not null;
(1 row)

pagetest=# rollback
pagetest-# ;
ROLLBACK

似乎在统计收集器视图上有一些奇怪的可见性规则。有什么合理的解决方法吗?

试试这个:

  BEGIN;
    select 1,current_query();
    select 2,current_query();
   ROLLBACK;

通过开始交易,所有未来 activity 都是不可见的。 我使用第二个数据库连接来接收实际值。