Sql 在不重新设计架构的情况下,如何跟踪所有CRUD操作的历史?

Sql 在不重新设计架构的情况下,如何跟踪所有CRUD操作的历史?,sql,postgresql,Sql,Postgresql,我希望捕获某些表中随时间变化的数据值修改,以便进行审计。有许多客户机可以对数据库进行查询,因此在SQL前面放置一个层是不可行的 在更新、删除和插入时创建触发器或规则,将操作细节写入postgresql日志文件和/或日志记录表 这是我之前准备的 此示例记录到表和日志中 CREATE TABLE debuglog(sql text, ts timestamptz,tbl name,usr text); CREATE or REPLACE function log_changes() RETURNS

我希望捕获某些表中随时间变化的数据值修改,以便进行审计。有许多客户机可以对数据库进行查询,因此在SQL前面放置一个层是不可行的

在更新、删除和插入时创建触发器或规则,将操作细节写入postgresql日志文件和/或日志记录表

这是我之前准备的 此示例记录到表和日志中

CREATE TABLE debuglog(sql text, ts timestamptz,tbl name,usr text);

CREATE or REPLACE function log_changes() RETURNS trigger as $TLC$
declare
    sql text := current_query();
begin

    --( not shown: code here that blanks out password fileds in sql )

    if tg_op= 'INSERT'  then 
        insert into debuglog values (sql || e'\n -- NEW=' || NEW::text,now(),TG_RELNAME,current_user || coalesce( ' '||inet_client_addr(),'local'));
        raise log 'insert to % by % NEW=%',TG_RELNAME, current_user || coalesce( ' '||inet_client_addr(),'local'),NEW::text;
    elsif tg_op = 'DELETE'  then 
        insert into debuglog values (sql || e'\n -- OLD=' || OLD::text,now(),TG_RELNAME,current_user || coalesce( ' '||inet_client_addr(),'local'));
        raise log 'delete from % by % OLD=%',TG_RELNAME, current_user || coalesce( ' '||inet_client_addr(),'local'),OLD::text;
        return old;
    else
        raise log 'update to % by % OLD=% NEW=%',TG_RELNAME, current_user || coalesce( ' '||inet_client_addr(),'local'),OLD::text,NEW::text;
        insert into debuglog values ( sql || e'\n -- OLD=' || OLD::text || e'\n -- NEW=' || NEW::text,now(),TG_RELNAME,current_user || coalesce( ' '||inet_client_addr(),'local'));
    end if;
    return new;
end $TLC$
language plpgsql;

create trigger after update or insert or delete on logged_table for each row do also log_changes();
我发现向作用于表的DML中添加SQL注释有助于查找有问题的代码。

请参阅或