New Postgres user, exploring trigger functions comparing to Oracle. Trying to write a general trigger that takes table name (and schema name if possible) as input and insert audit data into a corresponding audit table. However running into errors. Below is one of the sample code I tried... tried format as well but still got the error when try to pass additional parameters in audit tables Any help/input appreciated.
CREATE OR REPLACE FUNCTION audit_function_tr()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
declare
input_table_name text;
my_action char(1);
begin
input_table_name := 'employee.'||TG_ARGV\[0\]; -- audit table in different schema
IF TG_OP = 'INSERT' THEN
my_action := 'I';
elseif TG_OP = 'DELETE' THEN
my_action := 'D';
else
my_action := 'U';
END IF;
end if;
EXECUTE 'INSERT INTO '|| input_table_name ||
'VALUES ' || (my_action,current_user, now(), row_to_json(old));
IF TG_OP = 'DELETE' then
RETURN OLD;
ELSE
RETURN NEW;
end if;
END;
$function$
;
get below error when trigger is called:
SQL Error \[42601\]: ERROR: syntax error at end of input
Where: PL/pgSQL function audit_function_tr() line 16 at EXECUTE
ERROR: syntax error at end of input
Where: PL/pgSQL function audit_function_tr() line 16 at EXECUTE
ERROR: syntax error at end of input
Where: PL/pgSQL function audit_function_tr() line 16 at EXECUTE
You are falling prey to plain SQL injection. You have to escape your JSON values properly:
EXECUTE format(
'INSERT INTO employee.%I VALUES (%L, %L, %L, %L)',
TG_ARGV[0],
my_action,
current_user,
now(),
row_to_json(old)
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.