简体   繁体   中英

PostgreSQL Trigger After Insert to write on another table

Im trying to write a trigger for pgsql to keep a log of inserts, updates and deletes on an specific table.

I am getting an error on position 171 while creating teh trigger but i really dont know why.

log table

+----------+-----------+---------------------------+
|table_name|column_name|data_type                  |
+----------+-----------+---------------------------+
|logs      |id         |bigint                     |
|logs      |action     |smallint                   |
|logs      |table      |character varying          |
|logs      |primary    |bigint                     |
|logs      |log        |json                       |
|logs      |processed  |boolean                    |
|logs      |created_at |timestamp without time zone|
|logs      |updated_at |timestamp without time zone|
+----------+-----------+---------------------------+

function and trigger

CREATE OR REPLACE FUNCTION insert_log (INT, VARCHAR, INT, VARCHAR) RETURNS INT AS $$
    BEGIN
        INSERT INTO public.logs ("action", "table", "primary", "log")
            VALUES ($1, $2, $3, $4)
            RETURNING id;
    END
$$ LANGUAGE plpgsql;

CREATE TRIGGER trigger_clientes_insert
    AFTER INSERT ON xxx.legacy_clientes
    FOR EACH ROW
    EXECUTE FUNCTION insert_log (1, "clientes", id, row_to_json(NEW));

You should not be passing arguments to the trigger function: it automatically receives new , which is sufficient here. Also, the trigger function should return a TRIGGER .

Consider:

CREATE OR REPLACE FUNCTION insert_log () 
RETURNS TRIGGER AS $$
BEGIN
    INSERT INTO public.logs ("action", "table", "primary", "log")
        VALUES (1, NEW.clientes, NEW.id, row_to_json(NEW);
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trigger_clientes_insert
AFTER INSERT ON xxx.legacy_clientes
FOR EACH ROW
EXECUTE PROCEDURE insert_log();

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.

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