1.创建logging模式,并且创建一个logging模式下的记录表:
CREATESCHEMAlogging;
CREATETABLElogging.user_history( idserial,tstamptimestampDEFAULTnow(),schemanametext,tabnametext,operationtext,whotextDEFAULTcurrent_user,new_valjson,old_valjson );
2.创建触发器函数:
CREATEFUNCTIONchange_user_trigger() RETURNStriggerAS$$ BEGIN IFTG_OP='INSERT'THEN INSERTINTOlogging.user_history(tabname,schemaname,operation,new_val)values(TG_RELNAME,TG_TABLE_SCHEMA,TG_OP,row_to_json(NEW)); RETURNNEW; ELSIFTG_OP='UPDATE'THEN INSERTINTOlogging.user_history(tabname,new_val,old_val)values(TG_RELNAME,row_to_json(NEW),row_to_json(OLD)); RETURNNEW; ELSIFTG_OP='DELETE'THEN INSERTINTOlogging.user_history(tabname,row_to_json(OLD)); RETURNOLD;--返回值要与ELSIF平齐,因为先插入后最好才执行返回 ENDIF; END; $$LANGUAGE'plpgsql'SECURITYDEFINER;--securitydefiner是指定创建该函数用户的权限执行,securityinvoker是指以调用该函数用户发权限执行
3.创建测试表users:
CREATETABLEusers ( idserialNOTNULL,usernamecharactervarying(40),emailcharactervarying(100) )
4.创建触发器:
CREATETRIGGER"logging_user_change" BEFOREINSERTORUPDATEORDELETE ONusers FOREACHROW EXECUTEPROCEDUREchange_user_trigger();
5.测试:
INSERTINTOusersVALUES('hans','hans@qq.com'); UPDATEuseRSSETid=1,username='paul';
这个函数的缺陷:
1,它不能监控select语句
2,它不能监控系统表
3,它不能监控DDL操作,例如alter table(如果需要监控可以配置postgresql.conf文件,修改log_statment参数:#log_statement = 'none' # none,ddl,mod,all)