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

时间:2016-07-06 10:29:08

标签: postgresql postgresql-9.3

我尝试从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

看起来统计信息收集器视图上有一些奇怪的可见性规则。有没有合理的方法呢?

2 个答案:

答案 0 :(得分:2)

试试这个:

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

答案 1 :(得分:0)

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