软件下载吧文章资讯

分类分类

PostgreSQL长事务概念解析

2024-02-28 13:28作者:下载吧

我们在很多地方应该都听到过长事务的危害,比方说长事务会导致表膨胀之类的。那么在PostgreSQL中什么才算是长事务呢?

首先,在PostgreSQL的官方文档中并没有所谓“长事务”这一定义,似乎大家约定俗称的把一个执行了很长却没有提交的事务认为是“长事务”了,而在不同的数据库中关于长事务的定义往往也不尽相同,那么在PostgreSQL中什么是长事务呢?

打个比方,如下所示,我在一个会话中通过begin开启一个事务,然后执行了个简单的查询语句后迟迟不提交,这算不算长事务呢?

bill=# begin;
BEGIN
bill=*# select 1;
 ?column?
———-
        1
(1 row)

bill=*#

为了搞清楚这个问题,我们不妨想想,为什么我们会提到长事务呢。这是因为pg中的长事务会影响表中垃圾回收,会导致表的年龄增长无法freeze。而我们上面这个会话开启的事务会有影响吗?实际上并不会,我们可以通过pg_stat_activity视图观察:

bill=# select * from pg_stat_activity where pid = 26192;
-[ RECORD 1 ]—-+——————————
datid            | 16385
datname          | bill
pid              | 26192
leader_pid       |
usesysid         | 16384
usename          | bill
application_name | psql
client_addr      |
client_hostname  |
client_port      | -1
backend_start    | 2022-03-02 11:49:49.433165+08
xact_start       | 2022-03-02 14:34:04.494416+08
query_start      | 2022-03-02 14:34:06.946754+08
state_change     | 2022-03-02 14:34:06.947207+08
wait_event_type  | Client
wait_event       | ClientRead
state            | idle in transaction
backend_xid      |
backend_xmin     |
query            | select 1;
backend_type     | client backend

之所以会导致表膨胀之类的问题,主要是在于backend_xid和backend_xmin两个字段,而上面的事务这两个字段均是空的。

/* ———-
* LocalPgBackendStatus
*
* When we build the backend status array, we use LocalPgBackendStatus to be
* able to add new values to the struct when needed without adding new fields
* to the shared memory. It contains the backend status as a first member.
* ———-
*/
typedef struct LocalPgBackendStatus
{
/*
* Local version of the backend status entry.
*/
PgBackendStatus backendStatus;
/*
* The xid of the current transaction if available, InvalidTransactionId
* if not.
*/
TransactionId backend_xid;
/*
* The xmin of the current session if available, InvalidTransactionId if
* not.
*/
TransactionId backend_xmin;
} LocalPgBackendStatus;
展开全部

相关文章

说两句网友评论
    我要跟贴
    取消