PostgreSQL查询长连接

apple=# select pid, backend_start, xact_start, query_start, waiting, state, backend_xid from pg_stat_activity where backend_xid is not null and now() - xact_start > interval '1 min';
-[ RECORD 1 ]-+------------------------------
pid           | 14604
backend_start | 2018-12-04 15:06:19.306234+08 -- 连接创建时间
xact_start    | 2018-12-04 16:08:25.528639+08 -- 事务begin时间
query_start   | 2018-12-04 16:09:03.921005+08 -- 事务中最近的查询开始时间,一个事务内有多个查询时,只记录最近的一个
waiting       | f                  -- 是否在等待,有锁时这里为t
state         | idle in transaction           -- 是否空闲,且仍然未提交
backend_xid   | 718176                        -- 当前事务的id,即xid。如果连接创建了,没有做任何操作,或者仅仅begin了,那么这里是空的;但是如果begin了,前面的xact_start就会记录事务开始时间。 另外,仅查询不会产生。

往往我们查看backend_xid不为空,的state为idle in transaction的连接,分析他的三个时间,来判断是不是长事务。

开两个连接,在一个连接中锁住表,另外一个连接查询表,可以看到查询的表waiting状态为t:

apple=# select pid, backend_start, xact_start, query_start, waiting, state, backend_xid from pg_stat_activity where backend_xid is null and now() - backend_start > interval '1 min';
-[ RECORD 1 ]-+------------------------------
pid           | 14604
backend_start | 2018-12-04 15:06:19.306234+08
xact_start    | 2018-12-04 16:23:23.420563+08
query_start   | 2018-12-04 16:23:23.420563+08
waiting       | t
state         | active
backend_xid   |
-[ RECORD 2 ]-+------------------------------
pid           | 15509
backend_start | 2018-12-04 15:47:22.826488+08
xact_start    | 2018-12-04 16:23:26.41356+08
query_start   | 2018-12-04 16:23:26.41356+08
waiting       | f
state         | active
backend_xid   |
-[ RECORD 3 ]-+------------------------------
pid           | 16235
backend_start | 2018-12-04 16:20:22.398526+08
xact_start    | 2018-12-04 16:23:04.552078+08
query_start   | 2018-12-04 16:23:18.629458+08
waiting       | f
state         | idle in transaction
backend_xid   |
原文地址:https://www.cnblogs.com/kuang17/p/10064926.html