VastbaseG100

基于openGauss内核开发的企业级关系型数据库。

Menu

自治事务

功能描述

该功能支持在定义PL/pgSQL定义函数/存储过程中,在声明部分增加指令:PRAGMA AUTONOMOUS_TRANSACTION,用来控制对当前存储过程中的内部事务可以进行独立提交,而不影响其他的事务。 该执行方式与普通方式执行函数/存储过程相同。 此外,自治事务还支持如下功能:

  • 支持PL/pgSQL块内的SQL语句使用函数/存储过程参数和定义的变量。

  • 允许在匿名块内声明自治事务。

  • 支持自治事务的嵌套使用。

注意事项

声明为自治事务的函数/存储过程对返回值以及参数有如下限制:

  • 不支持集合作为返回值。

  • 不支持组合类型作为返回类型。

  • 不支持游标类型。

  • 不支持out参数。

语法格式

PRAGMA AUTONOMOUS_TRANSACTION;

示例

1、创建测试表。

create table at_tb2(id int, val varchar(64));

2、创建声明为自治事务的存储过程。

create or replace procedure at_test3(i int)
AS
DECLARE
  PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
  insert into at_tb2 values(1, 'before s1');
  insert into at_tb2 values(2, 'after s1');
  if i > 10 then
  rollback;
  else
  commit;
  end if;
end;
/
commit;  -- 如果数据库未开启默认自动提交,则需要手动提交

3、调用存储过程。

call at_test3(6);

4、查询表中的数据。

select * from at_tb2;

返回结果为:

 id |    val
----+-----------
  1 | before s1
  2 | after s1
(2 rows)

5、支持PL/pgSQL块内的SQL语句使用函数/存储过程参数和定义的变量。

create or replace procedure at_proc(i int)
as
declare
strval varchar;
pragma autonomous_transaction;
begin
strval:= 'begin:insert by autonomous transaction procedure<at_proc>';
insert into at_tb2 values(i,strval);
commit;
end;
/

commit; -- 如果数据库未开启默认自动提交,则需要手动提交

6、调用存储过程。

call at_proc(1);

7、查询表中的数据。

select * from at_tb2;

返回结果为:

 id |                            val
----+-----------------------------------------------------------
  1 | before s1
  2 | after s1
  1 | begin:insert by autonomous transaction procedure<at_proc>
(3 rows)

8、支持在匿名块内声明自治事务。

declare
pragma autonomous_transaction;
strval varchar;
begin strval:='insert by autonomous transaction by anonymous block';
insert into at_tb2 values(1,strval);
commit;
end;
/

9、查询表中数据。

select * from at_tb2;

返回结果为:

 id |                            val
----+-----------------------------------------------------------
  1 | before s1
  2 | after s1
  1 | begin:insert by autonomous transaction procedure<at_proc>
  1 | insert by autonomous transaction by anonymous block
(4 rows)

10、支持自治事务嵌套使用-创建嵌套自治事务的存储过程。

create or replace procedure at_proc_inner(i int)
as
declare
pragma autonomous_transaction;
begin
insert into at_tb2 values(1,'insert by autonomous transaction procedure<at_proc_inner>');
if i>5 then
rollback;
else
commit;
end if;
end;
/

create or replace procedure at_proc_outer(i int)
as
declare
pragma autonomous_transaction;
begin
insert into at_tb2 values(1,'insert by autonomous transaction procedure<at_proc_outer>');
at_proc_inner(i);
if i>10 then rollback;
else
commit;
end if;
end;
/

11、调用存储过程并查询结果。

truncate at_tb2;
call at_proc_outer(8);
select * from at_tb2;

返回结果为:

id |                                 val
---------------------------------------------------------------
  1 | insert by autonomous transaction procedure<at_proc_outer>
(1 row)