【问题标题】:Measure XID use on failed queries in PostgreSQL测量 PostgreSQL 中失败查询的 XID 使用情况
【发布时间】:2016-07-10 00:55:45
【问题描述】:

我正在调查对 Postgres 数据库执行的常见查询,以帮助减少 XID 的使用。我可以使用pg_stat_statements 获取执行的查询列表和调用次数,但是它不包括由于违反唯一约束等原因而失败的查询。有没有一种方法可以记录并统计这些失败的查询?

例子:

test_xid=# \d test
     Table "public.test"
 Column |  Type   | Modifiers 
--------+---------+-----------
 id     | integer | not null
Indexes:
    "test_pkey" PRIMARY KEY, btree (id)

test_xid=# truncate test;
TRUNCATE TABLE
test_xid=# select pg_stat_statements_reset();
 pg_stat_statements_reset 
--------------------------

(1 row)

test_xid=# select txid_current();
 txid_current 
--------------
       224547
(1 row)

test_xid=# insert into test(id) values (1);
INSERT 0 1
test_xid=# insert into test(id) values (1);
ERROR:  duplicate key value violates unique constraint "test_pkey"
DETAIL:  Key (id)=(1) already exists.
test_xid=# insert into test(id) values (1);
ERROR:  duplicate key value violates unique constraint "test_pkey"
DETAIL:  Key (id)=(1) already exists.
test_xid=# insert into test(id) values (1);
ERROR:  duplicate key value violates unique constraint "test_pkey"
DETAIL:  Key (id)=(1) already exists.
test_xid=# select txid_current();
 txid_current 
--------------
       224552
(1 row)

test_xid=# select query, calls from pg_stat_statements;
               query                | calls 
------------------------------------+-------
 insert into test(id) values (?);   |     1
 select pg_stat_statements_reset(); |     1
 select txid_current();             |     2
(3 rows)

test_xid=# select pg_stat_statements_reset();
 pg_stat_statements_reset 
--------------------------

(1 row)

test_xid=# insert into test(id) values (1);
ERROR:  duplicate key value violates unique constraint "test_pkey"
DETAIL:  Key (id)=(1) already exists.
test_xid=# select query, calls from pg_stat_statements;
               query                | calls 
------------------------------------+-------
 select pg_stat_statements_reset(); |     1
(1 row)

可以看出,如果 INSERT 查询始终失败,并且如果成功执行后查询已经存在,则 INSERT 查询将不会出现在 pg_stat_statments 中,则调用计数不会因后续失败的查询而增加,即使查询失败会导致当前 XID 增加。

【问题讨论】:

    标签: postgresql pg-stat-statements


    【解决方案1】:

    对于一般统计数据,您可以查看 pg_stat_database.xact_rollback。如果您想了解回滚的语句,我能想到的唯一不涉及 C 代码的就是记录所有语句,然后查看日志。

    如果您想深入研究 C 代码(或花钱请人),我认为向 pg_stat_statements 添加回滚支持不会非常困难,我怀疑社区会欢迎这样做。

    【讨论】:

      猜你喜欢
      • 2013-11-20
      • 2010-09-30
      • 1970-01-01
      • 2021-04-05
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多