我在 postgresql 中有一个触发器函数,它将在 INSERT、UPDATE 和 DELETE 操作的审计表中插入行。在我的表中,有一个名为audit_id的列,我需要在此字段中写入插入的审计行的 ID。这是我的功能
CREATE OR REPLACE FUNCTION my_audit_trigger()
RETURNS trigger LANGUAGE plpgsql
AS $function$
declare
audit_pk bigint;
begin
IF TG_OP = 'INSERT'
THEN
INSERT INTO audit.table_audit (rel_id, table_name, operation, after)
VALUES (TG_RELID, TG_TABLE_NAME, TG_OP, to_jsonb(NEW)) returning id into audit_pk;
NEW.audit_id := audit_pk;
RETURN NEW;
ELSIF TG_OP = 'UPDATE'
THEN
IF NEW != OLD THEN
INSERT INTO audit.table_audit (rel_id, table_name, operation, before, after)
VALUES (TG_RELID, TG_TABLE_NAME, TG_OP, to_jsonb(OLD), to_jsonb(NEW)) returning id into audit_pk;
END IF;
NEW.audit_id := audit_pk;
RETURN NEW;
ELSIF TG_OP = 'DELETE'
THEN
INSERT INTO audit.table_audit (rel_id, table_name, operation, before)
VALUES (TG_RELID, TG_TABLE_NAME, TG_OP, to_jsonb(OLD)) returning id into audit_pk;
OLD.audit_id := audit_pk;
RETURN OLD;
END IF;
end;
$function$;
结果,当插入或更新我的表行时,我得到了相应操作的审计 ID,但是当我运行 DELETE 命令时,我得到了前一个操作的审计 ID,而不是 DELETE 本身的审计 ID。所以我想问题出在OLD.audit_id := audit_pk;
更具体地说,例如,我运行INSERT INTO table VALUES (this, that) RETURNING audit_id
并返回 INSERT 操作的 audit_id。
之后,在运行时,DELETE FROM table WHERE id = sth RETURNING audit_id
我得到了 INSERT 操作的 audit_id,而不是 DELETE。
任何帮助表示赞赏,谢谢。
PS这就是我创建触发器的方式
CREATE TRIGGER table_trigger
BEFORE INSERT OR UPDATE OR DELETE
ON table
FOR EACH ROW
EXECUTE PROCEDURE my_audit_trigger();