rollback的功能在数据库中都一样,未提交的操作都会回滚,在psql中默认配置下AUTOCOMMIT是打开的,这一点和oracle不同,
如果测试需要先把autocommit设置为off,
\set AUTOCOMMIT off
在postgresql中有个savepoint可以回滚到某个点
1. 做几个测试,创建多个savepoint点,并可以多次rollback到同一个savepoint,rollback至savepoint后可以继续操作
postgres=# \set AUTOCOMMIT off
insert into tt values(1);
insert into tt values(2);
savepoint savepoint1;
insert into tt values(3);
insert into tt values(4);
savepoint savepoint2;
insert into tt values(5);
insert into tt values(6);postgres=# INSERT 0 1
postgres=# INSERT 0 1
postgres=# SAVEPOINT
postgres=# INSERT 0 1
postgres=# INSERT 0 1
postgres=# SAVEPOINT
postgres=# INSERT 0 1
postgres=#
INSERT 0 1
postgres=#
postgres=# select * from tt;
t1
----
1
2
3
4
5
6
(6 rows)
postgres=# rollback to savepoint savepoint2;
ROLLBACK
postgres=# select * from tt;
t1
----
1
2
3
4
(4 rows)
postgres=# insert into tt values(5);
INSERT 0 1
postgres=# select * from tt;
t1
----
1
2
3
4
5
(5 rows)
postgres=# rollback to savepoint savepoint2;
ROLLBACK
postgres=# select * from tt;
t1
----
1
2
3
4
(4 rows)
postgres=# commit;
COMMIT
postgres=#
postgres=# select * from tt;
t1
----
1
2
3
4
(4 rows)
2.在rollback至savepoint后操作如果出错,后续的所有操作会报
ERROR: current transaction is aborted, commands ignored until end of transaction block
这时候需要再次rollback to savepoint2可以回滚至savepoint2。
\set AUTOCOMMIT off
insert into tt values(1);
insert into tt values(2);
savepoint savepoint1;
insert into tt values(3);
insert into tt values(4);
savepoint savepoint2;
insert into tt values(5);
insert into tt values(6);
回滚
postgres=# rollback to savepoint savepoint2;
ROLLBACK
postgres=# select * from tt;
t1
----
1
2
3
4
(4 rows)
postgres=# insert into tt values('dfsdfdsf','sdf');
ERROR: INSERT has more expressions than target columns
LINE 1: insert into tt values('dfsdfdsf','sdf');
^
postgres=# select * from tt;
ERROR: current transaction is aborted, commands ignored until end of transaction block
postgres=# \d tt
ERROR: current transaction is aborted, commands ignored until end of transaction block
postgres=# ;
postgres=# select * from tt;
ERROR: current transaction is aborted, commands ignored until end of transaction block
postgres=# rollback to savepoint savepoint2;
ROLLBACK
postgres=# select * from tt;
t1
----
1
2
3
4
(4 rows)
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/582521/viewspace-1969290/
,如需转载,请注明出处,否则将追究法律责任。