我在我的应用程序中创建了一个表,并添加了审计列:
我想在db中有一个机制来自动填充这些列,在搜索时我找到了这个链接https://dailypostgres.wordpress.com/2013/10/24/keep-track-of-table-data-changes-by-putting-auditing-columns-and-populate-it-automatically-using-trigger/并使用以下代码创建了一个函数:
CREATE OR REPLACE FUNCTION update_audit_columns
(IN p_table_name TEXT) RETURNS VOID AS
$body$
DECLARE
x_function_name TEXT;
str_build TEXT;
BEGIN
IF LENGTH(p_table_name) = 0
THEN
RAISE EXCEPTION 'P_TABLE_NAME IS REQUIRED TO GENERATE TRIGGER';
END IF;
-- trigger function name based on table name passed as param
x_function_name := 'trg_audit_' || p_table_name || '()';
-- build string to create trigger function
str_build := 'CREATE OR REPLACE FUNCTION ' || x_function_name || '
RETURNS TRIGGER
AS $TRIGGER$
BEGIN
IF TG_OP = ''INSERT''
THEN
NEW.last_updated := CURRENT_TIMESTAMP;
NEW.last_updated_by := SESSION_USER;
NEW.created_by := SESSION_USER;
NEW.created_on := CURRENT_TIMESTAMP;
RETURN NEW;
ELSIF TG_OP = ''UPDATE''
THEN
NEW.last_updated := SESSION_USER;
NEW.last_updated_by := CURRENT_TIMESTAMP;
RETURN NEW;
END IF;
END;
$TRIGGER$
LANGUAGE ''plpgsql'' EXTERNAL SECURITY DEFINER;';
EXECUTE str_build;
EXECUTE 'DROP TRIGGER IF EXISTS audit_trigger ON '|| p_table_name ||';';
-- create trigger which actually calls above function
str_build := 'CREATE TRIGGER audit_trigger BEFORE INSERT OR UPDATE '
|| ' ON '|| p_table_name
|| ' FOR EACH ROW EXECUTE PROCEDURE '|| x_function_name ||';';
EXECUTE str_build;
RETURN;
END;
$body$
LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY DEFINER;
但即使是现在,当我尝试插入/更新行时,列也不会自动填充。 虽然我可以在pgAdmin ui中看到该函数已创建。
我有什么遗失的东西吗?另外,由于我对此很陌生,请您解释一下这个脚本试图完成的内容?