PostgreSQL事务特性之嵌套事务

嵌套事务的实现是基于SAVEPOINTROLLBACK TO SAVEPOINTRELEASE SAVEPOINT的,也就是设置一个保存点,可以回滚到保存点和释放保存点。

测试表的初始状态如下:

postgres=# \d test 
     Table "public.test"
 Column |  Type   | Modifiers 
--------+---------+-----------
 id     | integer | 
 name   | text    | 

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

开始测试

postgres=# begin ;
BEGIN
postgres=# insert into test values (1, 'a');
INSERT 0 1
postgres=# savepoint insert_a;
SAVEPOINT
postgres=# select * from test ;
 id | name 
----+------
  1 | a
(1 row)

postgres=# insert into test values (2, 'b');
INSERT 0 1
postgres=# savepoint insert_b;
SAVEPOINT
postgres=# select * from test ;
 id | name 
----+------
  1 | a
  2 | b
(2 rows)

postgres=# insert into test values (3, 'c');
INSERT 0 1
postgres=# select * from test ;
 id | name 
----+------
  1 | a
  2 | b
  3 | c
(3 rows)

现在定义了两个SAVEPOINT,并且插入了3条数据,现在测试ROLLBACK TO SAVEPOINT

postgres=# rollback to insert_b;
ROLLBACK
postgres=# select * from test ;
 id | name 
----+------
  1 | a
  2 | b
(2 rows)

postgres=# rollback to insert_a;
ROLLBACK
postgres=# select * from test ;
 id | name 
----+------
  1 | a
(1 row)

可见回滚到前面定义的保存点成功了。

如果回滚到前面的保存点,后面的更改就丢失了,包括保存点,比如回滚到insert_a,那么在insert_a之后的数据就没有了,insert_b这个保存点也不存在了。

postgres=# rollback to insert_a;
ROLLBACK
postgres=# select * from test ;
 id | name 
----+------
  1 | a
(1 row)

postgres=# rollback to insert_b;
ERROR:  no such savepoint

测试RELEASE SAVEPOINT

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

postgres=# begin ;             
BEGIN
postgres=# insert into test values (1, 'a');
INSERT 0 1
postgres=# savepoint insert_a;              
SAVEPOINT
postgres=# select * from test ; 
 id | name 
----+------
  1 | a
(1 row)

postgres=# insert into test values (2, 'b');
INSERT 0 1
postgres=# savepoint insert_b;              
SAVEPOINT
postgres=# select * from test ;             
 id | name 
----+------
  1 | a
  2 | b
(2 rows)

postgres=# release insert_a;
RELEASE
postgres=# select * from test ;
 id | name 
----+------
  1 | a
  2 | b
(2 rows)

postgres=# rollback to insert_a;
ERROR:  no such savepoint

保存点被释放后就不能再回滚到该保存点了。

转载于:https://my.oschina.net/aven92/blog/497704

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值