Trigger to update a table when data in other table is updated - triggers

I have a scenario where my table(Table_A) is getting the data replicated from another table(Table_B) which is on another server.
I want to write a trigger on Table A such that it inserts a value/row in a third table(Table_C) which is on the same server as Table_A.
I tried a trigger like this:
Function:
create or replace function drs_function1() returns trigger as $$
begin
if(TG_OP = 'INSERT') then
insert into Table_C values (NEW.loginname,'NEW');
return NEW;
elsif (TG_OP = 'DELETE') then
insert into Table_C values (OLD.loginname,'DELETED');
return OLD;
elsif(TG_OP = 'UPDATE') then
insert into Table_C values (NEW.loginname,'NEW');
return NEW;
end if;
end;
$$ language plpgsql;
Trigger:
create trigger trigger5 after insert or update or delete on Table_A for each row execute procedure drs_function1();
This works fine if I manually fire a insert/update/delete query on Table_A but the trigger does not fire when the data is fed through the replication from Table_B.
The system syncs Table_B with Table_A every 5min .
So, if we change data in Table_B the sync will put this data in Table_A and the trigger should fire at that point to insert data in Table_C.
Any help would be appreciated?
Thanks.

Related

Performance wise, is it better to create a separate triggers for INSERT, DELETE and UPDATE events or just one for all the events

In order to maintain audit log for the table test_table, I need to create triggers on the base table for INSERT, UPDATE and DELETE events and then insert these records in an audit table.
I can create trigger (and also associated procedure) in the following manner:
Create the procedure as:
CREATE OR REPLACE FUNCTION audit_test_table_function() RETURNS TRIGGER AS $body$
BEGIN
IF (TG_OP = 'DELETE') THEN
INSERT INTO audit_test_table VALUES (OLD.*, now(), user, pg_backend_pid(), 'D', DEFAULT);
RETURN OLD;
ELSIF (TG_OP = 'UPDATE') THEN
INSERT INTO audit_test_table VALUES (NEW.*, now(), user, pg_backend_pid(), 'U', DEFAULT);
RETURN NEW;
ELSIF (TG_OP = 'INSERT') THEN
INSERT INTO audit_test_table VALUES (NEW.*, now(), user, pg_backend_pid(), 'I', DEFAULT);
RETURN NEW;
END IF;
RETURN NULL;
END; $body$ LANGUAGE plpgsql;
And then create the trigger:
CREATE TRIGGER audit_test_table_trigger AFTER INSERT OR UPDATE OR DELETE ON test_table FOR EACH ROW EXECUTE PROCEDURE audit_test_table_function();
Other option would be to create the trigger/function for individual events ie separate one for DELETE event as following:
CREATE OR REPLACE FUNCTION audit_test_table_delete_function() RETURNS TRIGGER AS $body$
BEGIN
INSERT INTO audit_test_table VALUES (OLD.*, now(), user, pg_backend_pid(), 'D', DEFAULT);
RETURN OLD;
END;
$body$ LANGUAGE plpgsql;
CREATE TRIGGER audit_test_table_trigger AFTER DELETE ON test_table FOR EACH ROW EXECUTE PROCEDURE audit_test_table_delete_function();
And similarly for INSERT and UPDATE events.
My question is performance wise which one is recommended. And is there anything else that I should keep in mind?
I have already checked this but it doesn't answer my question.
You'll save a little execution time if you write three simpler functions, but I doubt that it is worth the effort.
If performance is paramount, you might consider writing the trigger functions in C.

Inserting Data in Postgres table when another table has been inserted with multiple rows

I am new to Postgres. My problem is that I want to insert some new rows in "target table" when these new rows are inserted in a "source table".
I wrote a trigger to do exactly that but whenever the source is inserted with say 7 new rows then the trigger inserts 7x7 = 49 rows in target. Next if I insert 3 more new rows in source then the target becomes 49+3x10 = 79.
What am I doing wrong..??
Trigger function:
CREATE OR REPLACE FUNCTION public.rec_insert()
RETURNS trigger AS
$BODY$
BEGIN
INSERT INTO target_table ("TIME","REGION","CITY","DISTRICT","Population")
SELECT NEW."TIME",NEW."REGION",NEW."CITY",NEW."DISTRICT",(100*(NEW."SAMPLES_MALE_Available")/(NULLIF((NEW."Total_AVAIL"-NEW."Female_AVAIL"),0)))
FROM source_table;
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql;
And my trigger is
CREATE TRIGGER ins_same_rec
AFTER UPDATE
ON source_table
FOR EACH ROW
EXECUTE PROCEDURE rec_insert();
You must omit the FROM. Thats the reason because many rows are inserted (one for each row in the previous state of the table)
CREATE OR REPLACE FUNCTION public.rec_insert()
RETURNS trigger AS
$BODY$
BEGIN
INSERT INTO target_table ("TIME","REGION","CITY","DISTRICT","Population")
SELECT NEW."TIME",NEW."REGION",NEW."CITY",NEW."DISTRICT",(100*(NEW."SAMPLES_MALE_Available")/(NULLIF((NEW."Total_AVAIL"-NEW."Female_AVAIL"),0)));
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql;

Postgresql Trigger to insert rows

I'm stuck for days with triggers on Postgresql (and Mysql as well). I just want to insert newly filled rows to another table. The original data comes from an external form (OpenDataKit) and goes to "intermediate" tables. I can't understand why the form cannot send the data anymore once the trigger is created... Note that all actions work without the trigger, when I do the insertions by hand. I would greatly appreciate some help to understand what I am doing wrong. I am now testing with Postgresql 9.5, but I got similar issue with MySQL 5.1.
-- CREATE procedure:
CREATE OR REPLACE FUNCTION proc_natobs() RETURNS TRIGGER AS
$BODY$
DECLARE
BEGIN
INSERT INTO lieu (id_lieu, wgs_lat, wgs_lon, date_obs, geom)
SELECT id_loc,"GPS_TEL_LAT", "GPS_TEL_LNG", "DATE_OBS", ST_SetSRID(ST_POINT("GPS_TEL_LNG","GPS_TEL_LAT"), 4326)
FROM "FORMULAIRE_NATOBS_REPEAT_LOC", "FORMULAIRE_NATOBS_CORE"
WHERE "FORMULAIRE_NATOBS_CORE"."_URI" = "FORMULAIRE_NATOBS_REPEAT_LOC"."_TOP_LEVEL_AURI"
AND "FORMULAIRE_NATOBS_REPEAT_LOC".id_loc IN (SELECT max(id_loc) FROM "FORMULAIRE_NATOBS_REPEAT_LOC");
INSERT INTO i_lieu_observateurs (id_lieu, id_auteur)
SELECT id_loc, CAST("AUTEUR" AS integer)
FROM "FORMULAIRE_NATOBS_CORE", "FORMULAIRE_NATOBS_REPEAT_LOC"
WHERE "FORMULAIRE_NATOBS_REPEAT_LOC"."_TOP_LEVEL_AURI" = "FORMULAIRE_NATOBS_CORE"."_URI"
AND id_loc IN (SELECT max(id_loc) FROM "FORMULAIRE_NATOBS_REPEAT_LOC")
UNION
SELECT id_loc, CAST("OBSERVATEURS" AS integer)
FROM "FORMULAIRE_NATOBS_REPEAT_LOC", "FORMULAIRE_NATOBS_REPEAT_OBSERVATEUR"
WHERE "FORMULAIRE_NATOBS_REPEAT_LOC"."_TOP_LEVEL_AURI" = "FORMULAIRE_NATOBS_REPEAT_OBSERVATEUR"."_TOP_LEVEL_AURI"
AND id_loc IN (SELECT max(id_loc) FROM "FORMULAIRE_NATOBS_REPEAT_LOC")
;
END;
$BODY$
LANGUAGE 'plpgsql';
-- CREATE the trigger:
CREATE TRIGGER trigger_natobs AFTER INSERT
ON "FORMULAIRE_NATOBS_REPEAT_LOC"
FOR EACH ROW
EXECUTE PROCEDURE proc_natobs();
So, when the ODK form inserts new rows in FORMULAIRE_NATOBS_REPEAT_LOC (for which I have created a serial ID to facilitate the SQL queries), I try to insert this row (combined with information from other intermediate tables) into table "lieu" for the first action of the trigger, and into table i_lieu_observation (composed by a double primary key) for the second action. I tested also with a trigger composed by the first action only, but it does not work either. The Android app that sends the form crashes until I remove the trigger.
Thanks in advance!
You need to use the special NEW variable in the trigger to access the newly inserted data. So you need something like:
CREATE OR REPLACE FUNCTION proc_natobs() RETURNS TRIGGER AS
$BODY$
DECLARE
BEGIN
INSERT INTO lieu (id_lieu, wgs_lat, wgs_lon, date_obs, geom)
SELECT new.id_loc,"GPS_TEL_LAT", "GPS_TEL_LNG", "DATE_OBS", ST_SetSRID(ST_POINT("GPS_TEL_LNG","GPS_TEL_LAT"), 4326)
FROM "FORMULAIRE_NATOBS_CORE"
WHERE "FORMULAIRE_NATOBS_CORE"."_URI" = new."_TOP_LEVEL_AURI";
INSERT INTO i_lieu_observateurs (id_lieu, id_auteur)
SELECT new.id_loc, CAST("AUTEUR" AS integer)
FROM "FORMULAIRE_NATOBS_CORE"
WHERE new."_TOP_LEVEL_AURI" = "FORMULAIRE_NATOBS_CORE"."_URI"
UNION
SELECT new.id_loc, CAST("OBSERVATEURS" AS integer)
FROM "FORMULAIRE_NATOBS_REPEAT_OBSERVATEUR"
WHERE new."_TOP_LEVEL_AURI" = "FORMULAIRE_NATOBS_REPEAT_OBSERVATEUR"."_TOP_LEVEL_AURI";
RETURN new;
END;
$BODY$
LANGUAGE 'plpgsql';
-- CREATE the trigger:
CREATE TRIGGER trigger_natobs AFTER INSERT
ON "FORMULAIRE_NATOBS_REPEAT_LOC"
FOR EACH ROW
EXECUTE PROCEDURE proc_natobs();
Because I don't know which fields come from which tables, I cannot make the above totally correct. In the same way as I have written new.id_loc, you will need to put new.field_name for all fields coming from the formulaire_natobs_repeat_loc table.
HTH
Try this
CREATE OR REPLACE FUNCTION proc_natobs() RETURNS TRIGGER AS
$BODY$
BEGIN
IF(TG_OP = 'INSERT') THEN
INSERT INTO lieu (id_lieu, wgs_lat, wgs_lon, date_obs, geom)
SELECT id_loc,"GPS_TEL_LAT", "GPS_TEL_LNG", "DATE_OBS", ST_SetSRID(ST_POINT("GPS_TEL_LNG","GPS_TEL_LAT"), 4326)
FROM "FORMULAIRE_NATOBS_REPEAT_LOC" loc, "FORMULAIRE_NATOBS_CORE" core
WHERE core."_URI" = loc."_TOP_LEVEL_AURI"
AND loc.id_loc =new.id_loc;
INSERT INTO i_lieu_observateurs (id_lieu, id_auteur)
SELECT id_loc as id,
CAST("AUTEUR" AS integer) as auteur
FROM "FORMULAIRE_NATOBS_CORE" core, "FORMULAIRE_NATOBS_REPEAT_LOC" loc
WHERE loc."_TOP_LEVEL_AURI" = core."_URI"
AND loc.id_loc =new.id_loc;
UNION
SELECT id_loc as id,
CAST("OBSERVATEURS" AS integer) as auteur
FROM "FORMULAIRE_NATOBS_REPEAT_LOC" loc, "FORMULAIRE_NATOBS_REPEAT_OBSERVATEUR" obs
WHERE loc."_TOP_LEVEL_AURI" = obs."_TOP_LEVEL_AURI"
AND loc.id_loc =new.id_loc;
END IF;
Return new;
END;
$BODY$
LANGUAGE 'plpgsql';
-- CREATE the trigger:
CREATE TRIGGER trigger_natobs AFTER INSERT
ON "FORMULAIRE_NATOBS_REPEAT_LOC"
FOR EACH ROW
EXECUTE PROCEDURE proc_natobs();
Hope it work for you.

PostgreSQL trigger not firing on update

I am using PostgreSQL 9.3.4
There are two linked tables updated remotely: table1 and table2
table2 uses foreign key dependance from table1.
Tables are updated in the following manner on remote server:
Insert into table1 returning id;
Insert into table2 using previous id
Query is sent ( 1 transaction with 2 insert statements)
I need to duplicate new rows to remote db using dblink so I created two 'before update' triggers for table1 and table2;
The problem is that only table2 trigger is firing; the first isn't ( from remote update;
doing test query from pgadmin under the same user, I get both triggers fired OK )
I assumed it is because the update is being processed in 1 transaction/query on remote server. So I tried to process both tables in second trigger, but still no luck - only table2 is processed.
What could be the reason ?
Thanks
P.S.
Trigger codes
Version 1
PROCEDURE fn_replicate_data:
DECLARE
BEGIN
PERFORM DBLINK_EXEC('myconn','INSERT INTO table1(dataid,sessionid,uid) VALUES('||new.dataid||','||new.sessionid||',
'||new.uid||') ');
RETURN new;
END;
PROCEDURE fn_replicate_data2:
DECLARE
BEGIN
PERFORM DBLINK_EXEC('myconn','INSERT INTO table2(dataid,data) VALUES('||new.dataid||','''||new.data||''') ');
RETURN new;
END;
CREATE TRIGGER tr_remote_insert_data
BEFORE INSERT OR UPDATE ON table1
FOR EACH ROW EXECUTE PROCEDURE fn_replicate_data();
CREATE TRIGGER tr_remote_insert_data2
BEFORE INSERT OR UPDATE ON table2
FOR EACH ROW EXECUTE PROCEDURE fn_replicate_data2();
VERSION2
PROCEDURE fn_replicate_data:
DECLARE
var table1%ROWTYPE;
BEGIN
select * from table1 into var where dataid = new.dataid;
PERFORM DBLINK_EXEC('myconn','INSERT INTO table1(dataid,sessionid,uid) VALUES('||var.dataid||','||var.sessionid||','||var.uid||') ');
PERFORM
DBLINK_EXEC('myconn','INSERT INTO table2(dataid,data) VALUES('||new.dataid||','''||new.data||''') ');
RETURN new;
END;
CREATE TRIGGER tr_remote_insert_data
BEFORE INSERT OR UPDATE ON table2
FOR EACH ROW EXECUTE PROCEDURE fn_replicate_data();
The reason was in NULL value if uid field. It had bigint type and had no default value in db, which causes the trigger to not work properly.
The fix is either
IF (NEW.uid IS NULL )
THEN
uid := 'DEFAULT';
else
uid := NEW.uid;
END IF;
before insert query; or (simpler) adding default value to db;

postgresql-using trigger to fire

I want to create a trigger so that whenever I make a change (Update or Delete) it should copy the old data to a new table (with same template).
I tried this code:
create table restrictions(ID int,name text);
insert into restrictions values(122,'suresh');
select * from restrictions;
create table restrictions_deleted(ID int,name text);// this is my duplicate table for keeping information of all updations.
CREATE OR REPLACE FUNCTION moveDeleted() RETURNS trigger AS $$
BEGIN
INSERT INTO restrictions_deleted VALUES(OLD.ID, OLD.name);
RETURN OLD;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE TRIGGER moveDeleted
BEFORE DELETE ON restrictions
FOR EACH ROW
EXECUTE PROCEDURE moveDeleted();
delete from restrictions where ID=122;
select * from restrictions_deleted;
This code is capable of recording all the deleted data into duplicate table. But I want to do same for updates also.
Any suggestion, any idea?
First - in a trigger function you need to RETURN NEW; instead of RETURN OLD;.
Second - change the trigger to BEFORE DELETE OR UPDATE.
Last - it is better to have AFTER DELETE OR UPDATE for a logging trigger. This way it wont do useless work, when the change is rolled back.
BTW here is a good example of logging/audit trigger.
UPDATE:
The function will look like:
CREATE OR REPLACE FUNCTION moveDeleted() RETURNS trigger AS $$
BEGIN
IF (TG_OP = 'UPDATE') THEN
INSERT INTO restrictions_deleted VALUES(OLD.ID, OLD.name);
RETURN NEW;
ELSIF (TG_OP = 'DELETE') THEN
INSERT INTO restrictions_deleted VALUES(OLD.ID, OLD.name);
RETURN OLD;
END IF;
END;
$$ LANGUAGE plpgsql;