我正在创建一个表来跟踪更改,但是它返回以下错误:
“(psycopg2.InternalError)控件已到达触发过程的结尾 没有返回上下文:PL / pgSQL函数change_trigger()“
只要我执行以下任何操作:insert
,change
或update
请参见下表和触发功能
创建用于记录更改的表
Create schema logging;
Create table logging.history(
id serial,
tstamp timestamp default now (),
schemaname text,
tabname text,
operation text,
who text default current_user,
new_val json,
old_val json);
创建功能
CREATE function
change_trigger()
RETURNS trigger as $$
BEGIN
IF TG_OP = 'Insert'
THEN
Insert into logging.history (tabname, schemaname, operation, new_val)
Values (TG_TABLE_NAME,TG_TABLE_SCHEMA, TG_OP, row_to_json(NEW));
RETURN NEW;
ELSIF TG_OP = 'Update'
THEN
Insert into logging.history (tabname, schemaname, operation, new_val, old_val)
Values (TG_TABLE_NAME,TG_TABLE_SCHEMA, TG_OP, row_to_json(NEW), row_to_json(OLD));
RETURN NEW;
ELSIF TG_OP = 'Delete'
THEN
Insert into logging.history (tabname, schemaname, operation, old_val)
Values (TG_TABLE_NAME,TG_TABLE_SCHEMA, TG_OP, row_to_json(OLD));
RETURN OLD;
END IF;
END;
$$ LANGUAGE 'plpgsql';
将触发器函数链接到表:
CREATE TRIGGER t AFTER INSERT OR UPDATE OR DELETE ON mytemp
FOR EACH ROW EXECUTE PROCEDURE change_trigger();
例如,当我执行以下操作时:
INSERT into mytemp(column1)
VALUES ('id2323900')
错误返回为:
控制已到达触发过程的结尾而没有返回上下文: PL / pgSQL函数change_trigger()
答案 0 :(得分:1)
tg_op的名称为({'INSERT', 'UPDATE', 'DELETE'
)不('Insert', 'Update', 'Delete'
)-区分大小写,或将TG_OP = 'Insert'
更改为TG_OP ilike('insert')
。我将在结尾处添加“ else”语句,并发出以下通知:
ELSE
NOTICE RAISE 'Unknown tg_op';
RETURN OLD;
END IF;