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...
推荐阅读
- Swift中willSet和didSet的简述
- js|js 事件循环
- 用c#转换word或excel文档为html文件|用c#转换word或excel文档为html文件,C#实现DataSet内数据转化为Excel和Word文件的通用类完整实例...
- cmd设置代理命令
- 8.|8. PostgreSQL逻辑结构(2)——表
- 认识PostgreSQL|认识PostgreSQL WAL(1)
- [python]字典中的方法get和setdefault方法
- JD、QQ12
- Kubernetes|Kubernetes stateful set讲解以及一个基于postgreSQL的具体例子
- Web|Web API --元素偏移量 offset 系列