How to modify Trigger to update a single attribute in PostgreSQL - postgresql

Here is my sample table.
CREATE TABLE employee_test(
idTst SERIAL PRIMARY KEY,
monthDownload VARCHAR(6),
changeDate DATE);
I am trying to create a function and trigger that would update changeDate attribute with a current date when monthDownload attribute is updated.
The function I have it works with one problem. It updates all records instead of the one that was updated.
CREATE OR REPLACE FUNCTION downloadMonthChange()
RETURNS TRIGGER AS
$$
BEGIN
IF NEW.monthDownload <> OLD.monthDownload THEN
UPDATE employee_test
SET changeDate = current_date
where OLD.idTst = NEW.idTst;
END IF;
RETURN NEW;
END;
$$
Language plpgsql;
Trigger
Create TRIGGER dataTest
AFTER UPDATE
ON employee_test
FOR EACH ROW
EXECUTE PROCEDURE downloadMonthChange();
When I execute the following Update statement:
UPDATE employee_test SET monthDownload = 'oct12'
WHERE idTst = 1;
All changeDate rows get update with a current date.
Is there a way to have only a row with changed record to have a current date updated.

If you use a before trigger you can write directly to NEW
CREATE OR REPLACE FUNCTION downloadMonthChange()
RETURNS TRIGGER AS
$$
BEGIN
IF NEW.monthDownload <> OLD.monthDownload THEN
NEW.changeDate = current_date;
END IF;
RETURN NEW;
END;
$$
Language plpgsql;
the other option when you must use an after trigger is to include the primary key in the where clause. It appears that you were trying to do this, but you had a spurious OLD in the query. beause of that the where clause was only looking at the record responsible for the trigger call, and not limiting which records were to be updated.
IF NEW.monthDownload <> OLD.monthDownload THEN
UPDATE employee_test
SET changeDate = current_date
where idTst = NEW.idTst;

Related

PostgreSQL trigger: first condition executes but not the second

A trigger works on the first part of a function but not the second.
I'm trying to set up a trigger that does two things:
Update a field - geom - whenever the fields lat or lon are updated, using those two fields.
Update a field - country - from the geom field by referencing another table.
I've tried different syntaxes of using NEW, OLD, BEFORE and AFTER conditions, but whatever I do, I can only get the first part to work.
Here's the code:
CREATE OR REPLACE FUNCTION update_geometries()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
update schema.table a set geom = st_setsrid(st_point(a.lon, a.lat), 4326);
update schema.table a set country = b.name
from reference.admin_layers_0 b where st_intersects(a.geom,b.geom)
and a.pk = new.pk;
RETURN NEW;
END;
$$;
CREATE TRIGGER
geom_update
AFTER INSERT OR UPDATE of lat,lon on
schema.table
FOR EACH STATEMENT EXECUTE PROCEDURE update_geometries();
There is no new on a statement level trigger. (well, there is, but it is always Null)
You can either keep the statement level and update the entire a table, i.e. remove the and a.pk = new.pk, or, if only part of the rows are updated, change the trigger for a row-level trigger and only update the affected rows
CREATE OR REPLACE FUNCTION update_geometries()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
NEW.geom = st_setsrid(st_point(NEW.lon, NEW.lat), 4326);
SELECT b.name
INTO NEW.country
FROM reference.admin_layers_0 b
WHERE st_intersects(NEW.geom,b.geom);
RETURN NEW;
END;
$$;
CREATE TRIGGER
geom_update
BEFORE INSERT OR UPDATE of lat,lon on
schema.table
FOR EACH ROW EXECUTE PROCEDURE update_geometries();

sql trigger - update/insert

one thing I´m struggling with is the definition of triggers in SQL. I need to implement a code for a given table such that:
-for any new row inserted in the table, the trigger is activated and the table stores current date on the attribute date. the issue I have with the code included below is that updates all rows in the table, and onle want the inserted table to be updated with the current date.
CREATE FUNCTION func()
RETURNS trigger AS $$
DECLARE
value DATE;
BEGIN
SELECT CURRENT_DATE INTO fecha;
UPDATE tabla SET date = value;
RETURN NULL;
END;
$$LANGUAGE plpgsql;
CREATE TRIGGER date
AFTER INSERT ON table
FOR EACH ROW EXECUTE PROCEDURE func();
for any update on any row of the table, the trigger is activated and again, stores the current date on the attribute date.
CREATE FUNCTION func2()
RETURNS trigger AS $$
DECLARE
value DATE;
BEGIN
SELECT CURRENT_DATE INTO value;
SET NEW.date=value;
RETURN NULL;
END;
$$LANGUAGE plpgsql;
CREATE TRIGGER date
AFTER UPDATE ON table
FOR EACH ROW
EXECUTE PROCEDURE func2();
Use a BEFORE trigger instead that manipulates the row that is getting inserted/updated:
CREATE FUNCTION func()
RETURNS trigger AS $$
BEGIN
NEW.date = CURRENT_DATE ;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER date
BEFORE INSERT OR UPDATE ON table
FOR EACH ROW EXECUTE PROCEDURE func();

Interpreting TG_TABLE_NAME as a value to update row in other table

I want to update a row in the master_table_info table with the latest timestamp whenever certain other tables are updated. Each row in the table corresponds to another table. I've created this function, but I cannot get TG_TABLE_NAME to be interpreted as a variable value and not a new column. I thus get the error column some_table does not exist. How do I interpret it as a value?
CREATE OR REPLACE FUNCTION master_table_timestamp()
RETURNS TRIGGER AS
$$
BEGIN
EXECUTE format('
UPDATE master_table_info
SET updated_at = NOW()
WHERE table_name = %I', TG_TABLE_NAME);
RETURN NULL;
END;
$$
language plpgsql;
CREATE TRIGGER master_table_timestamp
BEFORE UPDATE ON some_table
EXECUTE PROCEDURE master_table_timestamp();
EDIT
Based on the answer/comments so far and reading up the trigger documentation, I realized that I should use TG_TABLE_NAME and change to an AFTER trigger. However, modifying the table with the trigger produces no changes on master_table_info. What could be wrong?
CREATE OR REPLACE FUNCTION master_table_timestamp()
RETURNS TRIGGER AS
$$
BEGIN
UPDATE master_table_info
SET updated_at = NOW()
WHERE table_name = TG_TABLE_NAME;
RETURN new;
END;
$$
language plpgsql;
CREATE TRIGGER master_table_timestamp
AFTER UPDATE ON some_table
EXECUTE PROCEDURE master_table_timestamp();
2nd Edit
This code in my edit above (based on assistance from the answers) is correct. I just needed to force a manual refresh of the table for it to correctly show.
%I replaces the placeholder as an identifier. So the generated SQL would be
UPDATE master_table_info
SET updated_at = NOW()
WHERE table_name = some_table;
To replace a literal value you would need %L as a placeholder in the String. The %L placeholder takes care of properly quoting values, so if you use that, the generated string would be:
UPDATE master_table_info
SET updated_at = NOW()
WHERE table_name = 'some_table';
which is what you expected.
However there is no need for dynamic SQL to begin with. As you use that function in a before trigger it is important that you return a non-null value from it, otherwise the UPDATE statement would be cancelled.
CREATE OR REPLACE FUNCTION master_table_timestamp()
RETURNS TRIGGER AS
$$
BEGIN
UPDATE master_table_info
SET updated_at = NOW()
WHERE table_name = TG_TABLE_NAME;
RETURN new; --<< return a NON-NULL value here!
END;
$$
language plpgsql;

PSQL Add value from row to another value in the same row using triggers

I have a test table with three columns (file, qty, qty_total). I will input multiple rows like this for example, insert into test_table (file,qty) VALUS (A,5);. What i want is for on commit is for a trigger to take the value from qty and add it to qty_total. As what will happen is that this value will get updated as this example demonstrates. Update test_table set qty = 10 where file = A; So the qty_total is now 15. Thanks
Managed to solve this myself. I created a trigger function `CREATE FUNCTION public.qty_total()
RETURNS trigger
LANGUAGE 'plpgsql'
COST 100.0
VOLATILE NOT LEAKPROOF
AS $BODY$
BEGIN
IF TG_OP = 'UPDATE' THEN
NEW."total" := (OLD.total + NEW.col2);
RETURN NEW;
ELSE
NEW."total" := NEW.col2;
RETURN NEW;
END IF;
END;
$BODY$;
ALTER FUNCTION public.qty_total()
OWNER TO postgres; This was called by a trigger CREATE TRIGGER qty_trigger
BEFORE INSERT OR UPDATE
ON public.test
FOR EACH ROW
EXECUTE PROCEDURE qty_total(); now when i insert a new code and value, the value is copied to the total, when it is updated, the value is added to the total and i have my new qty_total. This may not have the best error catching in it, but since i am passing the data from php, i am happy to make sure the errors are caught and removed.

How to apply a update after an inser or update POSTGRESQL Trigger

How to apply an update after an insert or update in POSTGRESQL; I have got a table which has a field lastupdate; I want that field to be set up whenever the row is updated or when it was inserted.
I tried this trigger, but It is not working! HELP!!
CREATE OR REPLACE FUNCTION fn_update_profile()
RETURNS TRIGGER AS $update_profile$
BEGIN
IF (TG_OP = 'INSERT' OR TG_OP = 'UPDATE' ) THEN
UPDATE profile SET lastupdate=now() where oid=OLD.oid;
RETURN NULL;
ELSEIF (TG_OP = 'DELETE') THEN
RETURN NULL;
END IF;
RETURN NULL; -- result is ignored since this is an AFTER trigger
END;
$update_profile$ LANGUAGE plpgsql;
Your trigger function can be a lot easier than you had. Keep in mind that PG will do the update or the insert on the original table, you only have to deal with keeping the profile table up-to-date:
CREATE OR REPLACE FUNCTION fn_update_profile()
RETURNS TRIGGER AS $update_profile$
BEGIN
UPDATE profile SET lastupdate = now() WHERE oid = NEW.oid;
RETURN NEW;
END;
$update_profile$ LANGUAGE plpgsql;
The INSERT and UPDATE trigger functions both use the NEW parameter; the INSERT trigger function does not have the OLD parameter. You should always return NEW from the trigger function if successful (or OLD from a DELETE trigger), even if it is an AFTER INSERT OR UPDATE trigger; the whole operation will be rolled back if NULL is returned. If you then define the actual trigger to fire after the insert or update, you should be good:
CREATE TRIGGER tr_update_profile
AFTER INSERT OR UPDATE ON my_table
FOR EACH ROW EXECUTE PROCEDURE fn_update_profile();