我有一个postgresql表。用户可以使用界面或使用查询手动更新记录或删除记录。我需要跟踪已更新的记录数,删除到日志表中。我尝试过以下更新操作计数可以成功跟踪。但删除操作计数不会记录到日志表。
CREATE OR REPLACE FUNCTION edmonton.count_func() RETURNS TRIGGER AS $body$
DECLARE
v_old_data TEXT;
v_new_data TEXT;
log_count INTEGER;
BEGIN
IF (TG_OP = 'UPDATE') THEN
v_old_data := ROW(OLD.*);
v_new_data := ROW(NEW.*);
log_count = count(row(new));
RAISE NOTICE 'update operations';
INSERT INTO edmonton.log ("timestamp",message,type,project_area,count)
VALUES (CURRENT_TIMESTAMP,'records updated in Builder
table','Information','edmonton',log_count);
RETURN NEW;
ELSIF (TG_OP = 'DELETE') THEN
v_old_data := ROW(OLD.*);
log_count = count(row(old));
RAISE NOTICE 'delete operations';
INSERT INTO edmonton.log ("timestamp",message,type,project_area,count)
VALUES (CURRENT_TIMESTAMP,'records deleted in Builder
table','Information','edmonton',log_count);
RETURN OLD;
ELSIF (TG_OP = 'INSERT') THEN
v_new_data := ROW(NEW.*);
log_count = count(row(new));
RAISE NOTICE 'insert operations';
INSERT INTO edmonton.log ("timestamp",message,type,project_area,count)
VALUES (CURRENT_TIMESTAMP,'records inserted in Builder
table','Information','edmonton',log_count);
RETURN NEW;
ELSE
RAISE WARNING '[EDMONTON.COUNT_FUNC] - Other action occurred: %, at
%',TG_OP,now();
RETURN NULL;
END IF;
EXCEPTION
WHEN data_exception THEN
RAISE WARNING '[EDMONTON.COUNT_FUNC] - UDF ERROR [DATA EXCEPTION] -
SQLSTATE: %, SQLERRM: %',SQLSTATE,SQLERRM;
RETURN NULL;
WHEN unique_violation THEN
RAISE WARNING '[EDMONTON.COUNT_FUNC] - UDF ERROR [UNIQUE] - SQLSTATE: %,
SQLERRM: %',SQLSTATE,SQLERRM;
RETURN NULL;
WHEN OTHERS THEN
RAISE WARNING '[EDMONTON.COUNT_FUNC] - UDF ERROR [OTHER] - SQLSTATE: %,
SQLERRM: %',SQLSTATE,SQLERRM;
RETURN NULL;
END;
$body$
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = pg_catalog, edmonton;
这是我的触发器
CREATE TRIGGER count_audit
AFTER INSERT OR UPDATE OR DELETE
ON edmonton.builder
FOR EACH STATEMENT
EXECUTE PROCEDURE edmonton.count_func();
我在更新记录时收到警告消息,并且消息未记录到日志表中。
WARNING: [EDMONTON.COUNT_FUNC] - UDF ERROR [OTHER] - SQLSTATE: 55000, SQLERRM: record "old" is not assigned yet
CONTEXT: PL/pgSQL function count_func() line 49 at RAISE
答案 0 :(得分:1)
https://www.postgresql.org/docs/current/static/plpgsql-trigger.html
NEW
数据类型记录;保存新数据库行的变量 行级触发器中的INSERT / UPDATE操作。这个变量是 在语句级触发器中取消分配和DELETE操作。
OLD
数据类型记录;保存旧数据库行的变量 行级触发器中的UPDATE / DELETE操作。这个变量是 在语句级触发器中取消分配和INSERT操作。
所以真正的问题是
更新/插入如何工作?..
答案 1 :(得分:1)
首先,您无法以这种方式计算插入/更新/删除的行数。表达式
count(row(new))
始终返回1,因为row(new)
是一行。
其次,记录new
和old
未在每个语句的触发器中设置。每the documentation:
NEW
数据类型记录;变量为行级触发器中的INSERT / UPDATE操作保存新数据库行。此变量在语句级触发器和DELETE操作中未分配。