关于postgresql:postgresql-set-transaction-snapshot

6次阅读

共计 1573 个字符,预计需要花费 4 分钟才能阅读完成。

用法
SET TRANSACTION SNAPSHOT snapshot_id

能够在一个新的事务中应用曾经存在的事务的 snapshot。这个 snapshot 必须首先进行 export(pg_export_snapshot)。SET TRANSACTION SNAPSHOT 必须在新事务开始执行。事务隔离级别必须为 SERIALIZABLE or REPEATABLE READ。新事务隔离级别如果为 SERIALIZABLE,则老事务的也必须是 SERIALIZABLE。如果老事务时 read-only,新事务也须要为 read-only。

应用场景,session 1 export snapshot,session 2 通过 SET TRANSACTION SNAPSHOT 与 session 1 的 snapshot 同步。这样不论 session 1 export snapshot 后有没有别的 session 提交事务,都不影响 session 2。

session 1 export snapshot
此时 t1 中没有 id=897 的 tuple

[postgres@hgcndn ~]$ psql -p 5432 -U postgres -h 127.0.0.1
psql (12.4)
Type "help" for help.

postgres=# BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;
BEGIN
postgres=# SELECT pg_export_snapshot();
 pg_export_snapshot
---------------------
 00000003-0000000F-1
(1 row)

postgres=# select * from t1 where id=897;
 id | name
----+------
(0 rows)

session 2 进行 commit
在 t1 中 insert 了 id=897 的 tuple

[postgres@hgcndn ~]$ psql -p 5432 -U postgres -h 127.0.0.1
psql (12.4)
Type "help" for help.

postgres=#
postgres=# select * from t1 where id=897;
 id | name
----+------
(0 rows)

postgres=# insert into t1 values(897, 'test');
INSERT 0 1
postgres=# select * from t1 where id=897;
 id  | name
-----+------
 897 | test
(1 row)

session 3
默认的 read committed 的隔离级别下,能看到 session 2 提交的批改
然而在新事务中,通过 SET TRANSACTION SNAPSHOT 与 session 1 中 export snapshot 的事务对齐后,看不到 session 2 中 insert 的 tuple

[postgres@hgcndn ~]$ psql -p 5432 -U postgres -h 127.0.0.1
psql (12.4)
Type "help" for help.

postgres=#
postgres=# select * from t1 where id=897;
 id  | name
-----+------
 897 | test
(1 row)

postgres=#  BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;
BEGIN
postgres=# SET TRANSACTION SNAPSHOT '00000003-0000000F-1';
SET
postgres=# select * from t1 where id=897;
 id | name
----+------
(0 rows)

参考文献
https://www.postgresql.org/do…
https://www.postgresql.org/do…

正文完
 0