简体   繁体   English

Postgresql 9.2触发器记录对另一个表中数据的更改

[英]Postgresql 9.2 trigger to log changes to data in another table

I have several tables and want to log when changes are made to them, what the change was and who made the change. 我有几个表,想要记录何时对它们进行更改,更改的内容以及更改者。 Postgresql 9.2 Postgresql 9.2

CREATE TABLE unitsref (
unitsrefid serial primary key,
units varchar,
unitname varchar,
inuse boolean,
systemuse varchar,
keynotes integer,
linkid integer
);

Is the best practise to use OLD.* IS DISTINCT FROM NEW.* ? 是使用OLD的最佳做法。*从新的* DISTINCT。

CREATE TRIGGER log_unitsref
    AFTER UPDATE ON unitsref
    FOR EACH ROW
    WHEN (OLD.* IS DISTINCT FROM NEW.*)
EXECUTE PROCEDURE log_unitsref();

I am only really interested in the three fields: 我只对这三个领域感兴趣:

units varchar,
unitname varchar,
inuse boolean,

I want to record these changes in a table eventlog with the fields: 我想在表事件日志中使用以下字段记录这些更改:

recordtype varchar,
recordkey varchar,
changetype varchar,
personid integer,
changedate date,
changetime time,
changefrom varchar,
changeto varchar,

What is the best syntax to write a function to do this? 编写函数来执行此操作的最佳语法是什么? In Progress Openedge I would write In Openedge我会写

create  EventLog.
assign  EventLog.PersonId    = glb-Personid
        EventLog.RecordType  = "UnitsRef"
        EventLog.RecordKey   = UnitsRef.Units
        EventLog.ChangeType  = "Create"
        EventLog.changeFrom  = ""
        EventLog.changeTo    = ""
        EventLog.changeDate  = today
        EventLog.changeTime  = time

but I don`t know the best method in Postgresql 但我不知道Postgresql中最好的方法

I am only really interested in the three fields 我只对三个领域感兴趣

Then it should be more efficient to only call the trigger after changes to these fields: 那么在更改这些字段后仅调用触发器应该更有效:


CREATE TRIGGER log_unitsref
AFTER UPDATE OF units, unitname, inuse
ON unitsref
FOR EACH ROW
WHEN (OLD.units, OLD.unitname, OLD.inuse) IS DISTINCT FROM (NEW.units, NEW.unitname, NEW.inuse)
EXECUTE PROCEDURE log_unitsref();

I quote the manual on CREATE TRIGGER : 我引用CREATE TRIGGER的手册

UPDATE OF ... UPDATE OF ......

The trigger will only fire if at least one of the listed columns is mentioned as a target of the UPDATE command. 只有在列出的列中至少有一列被提及为UPDATE命令的目标时,触发器才会触发。

WHEN ... WHEN ......

A Boolean expression that determines whether the trigger function will actually be executed. 一个布尔表达式,用于确定是否实际执行触发器功能。

Note that these two elements are closely related but neither mutually exclusive nor redundant. 请注意,这两个元素密切相关,但既不相互排斥也不冗余。

  • It is much cheaper not to fire the trigger at all, if no column of interest is involved. 如果不涉及任何感兴趣的列,那么根本不触发触发器要便宜得多。

  • It is much cheaper not to execute the trigger function if no column of interest was actually altered. 如果没有实际改变感兴趣的列,则执行触发器功能要便宜得多。

Related answers here or here ... 相关答案在这里这里 ......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM