【发布时间】:2017-03-02 11:28:28
【问题描述】:
我有一个 plpgsql 函数,它接受 jsonb 输入,并使用它首先检查某些内容,然后再次在查询中获取结果。比如:
CREATE OR REPLACE FUNCTION public.my_func(
a jsonb,
OUT inserted integer)
RETURNS integer
LANGUAGE 'plpgsql'
COST 100.0
VOLATILE NOT LEAKPROOF
AS $function$
BEGIN
-- fail if there's something already there
IF EXISTS(
select t.x from jsonb_populate_recordset(null::my_type, a) f inner join some_table t
on f.x = t.x and
f.y = t.y
) THEN
RAISE EXCEPTION 'concurrency violation... already present.';
END IF;
-- straight insert, and collect number of inserted
WITH inserted_rows AS (
INSERT INTO some_table (x, y, z)
SELECT f.x, f.y, f.z
FROM jsonb_populate_recordset(null::my_type, a) f
RETURNING 1
)
SELECT count(*) from inserted_rows INTO inserted
;
END
在这里,我在IF 检查和实际插入中都使用了jsonb_populate_recordset(null::my_type, a)。有没有办法进行一次解析 - 也许通过某种变量?或者查询优化器是否会启动并确保解析操作只发生一次?
【问题讨论】:
-
服务器版本是多少?..
-
服务器版本为9.6。
-
是否需要引发异常?
-
是的,我确实需要例外(示例已简化)。
标签: postgresql exception insert plpgsql