我正在寻求澄清如何确保 plpgsql 函数中的原子事务,以及为数据库的这种特定更改设置隔离级别的位置。
在下面显示的 plpgsql 函数中,我想确保删除和插入都成功。当我尝试将它们包装在单个事务中时出现错误:
ERROR: cannot begin/end transactions in PL/pgSQL
如果另一个用户在此函数删除自定义行之后但在有机会插入自定义行之前添加了针对环境的默认行为('RAIN'、'NIGHT'、'45MPH'),则在执行下面的函数期间会发生什么排?是否存在包装插入和删除的隐式事务,以便如果另一个用户更改了此函数引用的任一行,两者都会回滚?我可以为此功能设置隔离级别吗?
create function foo(v_weather varchar(10), v_timeofday varchar(10), v_speed varchar(10),
v_behavior varchar(10))
returns setof CUSTOMBEHAVIOR
as $body$
begin
-- run-time error if either of these lines is un-commented
-- start transaction ISOLATION LEVEL READ COMMITTED;
-- or, alternatively, set transaction ISOLATION LEVEL READ COMMITTED;
delete from CUSTOMBEHAVIOR
where weather = 'RAIN' and timeofday = 'NIGHT' and speed= '45MPH' ;
-- if there is no default behavior insert a custom behavior
if not exists
(select id from DEFAULTBEHAVIOR where a = 'RAIN' and b = 'NIGHT' and c= '45MPH') then
insert into CUSTOMBEHAVIOR
(weather, timeofday, speed, behavior)
values
(v_weather, v_timeofday, v_speed, v_behavior);
end if;
return QUERY
select * from CUSTOMBEHAVIOR where ... ;
-- commit;
end
$body$ LANGUAGE plpgsql;