PostgreSQL事務特性之嵌套事務

嵌套事務的實現是基於SAVEPOINTROLLBACK TO SAVEPOINTRELEASE SAVEPOINT的,也就是設置一個保存點,能夠回滾到保存點和釋放保存點。 html

測試表的初始狀態以下: sql

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

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

開始測試 post

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)

可見回滾到前面定義的保存點成功了。 postgresql

若是回滾到前面的保存點,後面的更改就丟失了,包括保存點,好比回滾到insert_a,那麼在insert_a以後的數據就沒有了,insert_b這個保存點也不存在了。 code

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
htm

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

保存點被釋放後就不能再回滾到該保存點了。
事務

相關文章
相關標籤/搜索