插入冲突时回滚触发器

时间:2016-02-03 13:15:22

标签: sql postgresql plpgsql postgresql-9.5

我有这个:

CREATE FUNCTION upsert_user(u_name text, u_fullname text, u_email text, u_suffix text) RETURNS integer
    LANGUAGE plpgsql
    AS $$
DECLARE
    userid users.id_user%TYPE;
BEGIN
    LOOP
        -- first try to update
        UPDATE users SET "fullname" = u_fullname, "email" = u_email, "suffix" = u_suffix WHERE "name" = u_name RETURNING "id_user" INTO userid;
        -- check if the row is found
        IF FOUND THEN
            RETURN userid;
        END IF;
        -- not found so insert the row
        BEGIN
            INSERT INTO users ("name", "fullname", "email", "suffix") VALUES (u_name, u_fullname, u_email, u_suffix) RETURNING "id_user" INTO userid;
            RETURN userid;
            EXCEPTION WHEN unique_violation THEN
                -- do nothing and loop
        END;
    END LOOP;
END;
$$;

CREATE TRIGGER link_entity
  BEFORE INSERT
  ON public.users
  FOR EACH ROW
  EXECUTE PROCEDURE public.link_entity();

CREATE FUNCTION link_entity() RETURNS trigger
    LANGUAGE plpgsql
    AS $$    DECLARE
        entityid integer;
    BEGIN
        INSERT INTO privileges_entities (name) VALUES (NEW.name) RETURNING privileges_entities.id_entity INTO entityid;
        IF NOT FOUND THEN
            RETURN NULL;
        END IF;
        NEW.ref_entity := entityid;
        RETURN NEW;
    END;
$$;

将postgresql更新到9.5版后,我修改了函数upsert_user以使用新指令ON CONFLICT:

CREATE FUNCTION upsert_user(u_name text, u_fullname text, u_email text, u_suffix text) RETURNS integer
    LANGUAGE sql
    AS $$
  INSERT INTO users (name, fullname, email, suffix)
  VALUES (u_name, u_fullname, u_email, u_suffix)
  ON CONFLICT (name) DO UPDATE SET name=EXCLUDED.name, fullname=EXCLUDED.fullname, email=EXCLUDED.email, suffix=EXCLUDED.suffix
  RETURNING id_user;
$$;

现在的问题是,即使插入users表失败,现在也会在privileges_entities表中插入新行。 如果插入用户导致冲突,是否可以回滚触发器?

1 个答案:

答案 0 :(得分:1)

这确实是使用新的ON CONFLICT子句的副作用。

我的解决方案是在link_entity()函数本身添加一个检查,如果用户已经存在则阻止它继续。像这样:

CREATE FUNCTION link_entity() RETURNS trigger
    LANGUAGE plpgsql
    AS $$    DECLARE
        entityid integer;
        nameExists boolean;
    BEGIN
        EXECUTE format('SELECT EXISTS(SELECT 1 FROM %I.%I WHERE name = NEW.name)', TG_TABLE_SCHEMA, TG_TABLE_NAME) INTO nameExists;
        IF nameExists THEN
            RETURN NEW; -- just return, entity already linked
        END IF;

        INSERT INTO privileges_entities (name) VALUES (NEW.name) RETURNING privileges_entities.id_entity INTO entityid;
        IF NOT FOUND THEN
            RETURN NULL;
        END IF;
        NEW.ref_entity := entityid;
        RETURN NEW;
    END;
$$;