我使用postgres和plpgsql函数来实现Web应用程序的业务逻辑。
我的中间件调用plpgsql - functions。这些plpgsql函数调用其他plpgsql函数,这些函数执行更新,插入,删除等事务。
我添加了一些伪代码来说明逻辑。
我们假设,sub_function_1和sub_function_2执行时没有任何错误。 sub_function_3执行错误并进入异常。
由于sub_function_1和sub_function_2的事务只有在没有错误的情况下执行sub_function_3才有意义,如果sub_function_3遇到错误,我想对事务sub_function_1和sub_function_2进行回滚。
如果sub_function_3遇到错误,是否可以在sub_function_1和sub_function_2成功执行后撤消/回滚它们的事务?
create or replace function root_function()
begin
-- do some transactions through performing sub_function_1
perform sub_function_1();
-- do here some other transactions
-- do some transactions through performing sub_function_2
perform sub_function_2();
-- do some transactions through performing sub_function_3
perform sub_function_3();
return 'successful';
exception when others then
return 'failed';
end;
只需在root_function()的异常块中添加Rollback
即可。第三个子函数中的任何错误都将导致ROLLBACK
也撤消前两个子函数。
CREATE OR REPLACE FUNCTION root_function()
RETURNS VOID
LANGUAGE 'plpgsql'
AS $$
BEGIN
-- do some transactions through performing sub_function_1
PERFORM sub_function_1();
-- do here some other transactions
-- do some transactions through performing sub_function_2
PERFORM sub_function_2();
-- do some transactions through performing sub_function_3
PERFORM sub_function_3();
RAISE NOTICE 'successful';
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
END;$$;