postgresql: set transaction snapshot

用法
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)

【postgresql: set transaction snapshot】参考文献
https://www.postgresql.org/do...
https://www.postgresql.org/do...

    推荐阅读