Return PL/pgSQL 函数中 ON CONFLICT DO NOTHING 的值

Return value for ON CONFLICT DO NOTHING in PL/pgSQL function

按照 this 评论的指示。

CREATE OR REPLACE FUNCTION test_upsert(
        _parent_id int, 
        _some_text text)
  RETURNS text
  LANGUAGE plpgsql AS
$func$
DECLARE
   a text;
BEGIN
   INSERT INTO parent_tree (parent_id, some_text)
   VALUES (_parent_id,_some_text)
   ON     CONFLICT DO NOTHING
   RETURNING 'ok' into a;
   return a;
   IF NOT FOUND THEN return 'JUZ ISTNIEJE';
   END IF;
END
$func$;
  1. 不确定这是什么意思:

    IF NOT FOUND THEN return 'JUZ ISTNIEJE';

  2. 如果不冲突则returnok,这才有意义。但是当冲突时它会产生空值。是否可以同时拥有 on conflict do nothing 和 return not ok 或者当发生冲突时,只有 raise notice parent_id should be unique?

我现在更新了 my referenced answer 以修复错误,这似乎是造成混乱的主要原因。

  1. NOT Sure what does IF NOT FOUND THEN return 'JUZ ISTNIEJE'; mean?

“JUZ ISTNIEJE”在波兰语中表示“已经存在”——这就是 OP 想要 return 那边的意思。唯一的一点是 return 一个有意义的文本而不是什么都没有 (NULL) - 这似乎解决了你的下一个问题:

  1. If no conflict then return ok, which makes sense. But when conflict it will yields null. Is it possible to BOTH have on conflict do nothing and also return not ok or when conflict happens, just raise notice parent_id should be unique.

是的,这就是我在那边的回答所做的,现在它已经修复了。您的函数变为:

CREATE OR REPLACE FUNCTION test_upsert(_parent_id int, _some_text text)
  RETURNS text
  LANGUAGE plpgsql AS
$func$
BEGIN
   INSERT INTO parent_tree (parent_id, some_text)
   VALUES (_parent_id,_some_text)
   ON     CONFLICT DO NOTHING;
   
   IF FOUND THEN
      RETURN 'ok';
   ELSE
      RAISE NOTICE 'parent_id already exists: %', _parent_id;  -- optional!
      RETURN 'not ok';  -- or whatever
   END IF;
END
$func$;