Generic function to be called from multiple triggers - postgresql

I have created a function and trigger to make use that the userId is uCased. The code is as followsL
CREATE OR REPLACE FUNCTION stdUserId ()
RETURNS trigger AS $stdUserId$
BEGIN
NEW.login_id = UPPER (TRIM (NEW.login_id));
RETURN NEW;
END;
$stdUserId$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS usersStdUserId ON users;
CREATE TRIGGER usersStdUserId BEFORE INSERT OR UPDATE ON users
FOR EACH ROW EXECUTE PROCEDURE stdUserId (login_id);
Now I would like to alter the function to be usable with other triggers as in:
DROP TRIGGER IF EXISTS user_rolesStdUserId ON user_roles;
CREATE TRIGGER user_rolesStdUserId BEFORE INSERT OR UPDATE ON users
FOR EACH ROW EXECUTE PROCEDURE stdUserId (user_id);
I would like a generic approach as I have a number of tables to apply this function to. I would prefer to stay away from "IF table01 .. . ELSEIF table02 .. ."
Your assistance is appreciated.

Related

Pass the query result to the function

I created a function that takes as a parameter a string by which i am looking for the desired element in the Bus table. After that i create a trigger that will fire after inserting into the Maintenance table. Here i have a problem: i specify that when changing the table, call the function and pass the last added element there, but the trigger is not created.
I looked for similar questions and saw that you need to take the query in brackets, but it did not help.
Ask for your help!
Function:
create function set_status(model_ varchar(50)) returns void as $$
update Bus set technical_condition = 'don`t work' where model = model_;
$$ LANGUAGE sql;
Trigger:
create trigger check_insert
after insert on Maintenance
for each row
execute procedure set_status((select model from Maintenance order by id_m desc limit 1));
First off your trigger function must be of the form:
create or replace function <function_name>()
returns trigger
language plpgsql
as $$
begin
...
end;
$$;
The language specification may come either before the code or after it. Moreover it must be defined returning trigger and as taking no parameters. See documentation.
You can achieve what you want by moving the select status ... query into the trigger function itself.
create or replace function set_status()
returns trigger
language plpgsql
as $$
begin
update bus
set technical_condition =
(select model
from maintenance
order by id_m desc
limit 1
) ;
return null;
end;
$$;
create trigger check_insert
after insert on maintenance
for each row
execute procedure set_status();
NOTE: Not Tested.

Syntax error while creating a trigger in PostgreSQL

I created a table name Student in PostgreSQL and then I tried defining a trigger on that table but it's showing an error message in doing so.
Trigger Syntax:
CREATE TRIGGER bi_Student BEFORE INSERT ON Student as $$
FOR EACH ROW
BEGIN
raise notice 'Successfully inserted into table(%)', user;
end $$;
Table Creation Command:
create table Student(Stu_id int, Stu_Name text, Stu_Age int, Stu_address char(30));
Actually I tried to declare the execution statements directly inside the trigger only rather than calling any procedure/ function from the trigger which is working fine but I want to do in this way in PostgreSQL.
PostgreSQL doesn't support it. You need trigger function always.
As documented in the manual you need a trigger function
create function my_trigger_function()
returns trigger
as
$$
begin
raise notice 'Successfully inserted into table(%)', user;
return new; --<< important (see the manual for details)
end
$$
language plpgsql;
Not sure what you intend with the user parameter there, as that is not the table name, but the current database user. If you want to display the actual table name, you need to use TG_RELNAME instead - which is an implicit variable available in the trigger function.
And a trigger definition
CREATE TRIGGER bi_Student
BEFORE INSERT ON Student
FOR EACH ROW
execute function my_trigger_function();

Postgres Function Trigger Sequence Dependency Error

I have the following functions and trigger with sequence setup:
I want to create a function and trigger that anytime I add a new row to STRATEGY_SITES table, the 'SITE_NUM' field will have the new sequential number from SITENUM_SEQ. Schema name is gismgr.
I am getting the following error:Underlying DBMS error[Error:control reached end of trigger procedure without return Context: PL/pgSQL function process_sites_edit()(gismgr.strategy_sites)::SQLSTATE=2F005][gismgr.startegy_sites]
CREATE OR REPLACE FUNCTION process_sites_edit() RETURNS TRIGGER AS $SITE_EDIT_TRIGGER$
begin
new.SITE_NUM := nextval('gismgr.SITENUM_SEQ');
end;
$SITE_EDIT_TRIGGER$ LANGUAGE 'plpgsql';
create TRIGGER SITE_EDIT_TRIGGER
before insert or update on STRATEGY_SITES for each row
EXECUTE PROCEDURE process_strategy_sites_edit();
CREATE SEQUENCE gismgr."SITENUM_SEQ" owned by gismgr.strategy_Sites.site_num
INCREMENT 1
START 19080
MINVALUE 19080
MAXVALUE 9999999999999999
CACHE 20;
This seems to be an ORACLEism which is unnecessary in Postgres. Assuming your table already exsists then just
alter table *table_name* alter column site_num default nextval('gismgr.SITENUM_SEQ')
Also make sure the insert does not mention the site_num column. If you feel you must continue with the trigger approach the your trigger function needs to specify the return value.
CREATE OR REPLACE FUNCTION process_sites_edit()
RETURNS TRIGGER AS $SITE_EDIT_TRIGGER$
begin
new.SITE_NUM := nextval('gismgr.SITENUM_SEQ');
return new;
end;
$SITE_EDIT_TRIGGER$ LANGUAGE 'plpgsql';
I would also suggest you do not want to fire the trigger on updates. That will change the site number on any/every update of a given row Are there FK referencing it - they will not be updated the update would fail. Further the procedure executed must match the function name:
create TRIGGER SITE_EDIT_TRIGGER
before insert on STRATEGY_SITES for each row
EXECUTE PROCEDURE process_sites_edit();

postgresSQL How to apply trigger only on updated row?

I'm trying to create a function + trigger that will update my "modif" attribut to current date when there is an update or insert on my table called "nada".
the code work well but all the rows are affected.I only want the current date on the rows that were updated.
Any idea ?
This is my code so far:
CREATE OR REPLACE FUNCTION public.maj_modif()
RETURNS "trigger" AS
$BODY$
BEGIN
NEW.modif:= (SELECT current_date);
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS maj_modif ON public.nada;
CREATE TRIGGER maj_modif BEFORE INSERT OR UPDATE ON public.nada
FOR EACH ROW
EXECUTE PROCEDURE public.maj_modif();
If I try the same code without "FOR EACH ROW" in the trigger I get this erreur: « new » is not affected yet (...) The structure of the registration line is not yet determined.
I assume that you only want the trigger to fire if any columns were actually changed.
That can be done with
CREATE TRIGGER maj_modif BEFORE UPDATE ON public.nada
FOR EACH ROW
WHEN OLD <> NEW
EXECUTE PROCEDURE public.maj_modif();
That only works for UPDATE, because on INSERT OLD is not defined. Define the INSERT trigger without the WHEN clause.

How do I trigger or call a function on INSERT to one table based on result of another table?

I know how to do this using SQL Server or Sybase, but can't seem to get it right using Postgres 9.4. I have a FUNCTION that is working as intended:
CREATE OR REPLACE FUNCTION "public"."welcome"(u_id INT DEFAULT 1234)
RETURNS "void"
AS $$
INSERT INTO my_table_1 (title,body,category,user_id,created_at)
VALUES ('Welcome!', '<some text>','general',u_id,now())
$$ LANGUAGE sql
This FUNCTION works as expected when called as SELECT welcome(1234);
However, what I'm trying to do is call or trigger this FUNCTION based on the condition AFTER a new user gets inserted into another table and that user is the first and only user:
INSERT INTO my_table_2 (user_id,name,...) VALUES (5678,'John Doe',...);
and the following condition is met:
SELECT COUNT(*) from my_table_2 WHERE <my conditions are met>;
returns exactly and only 1
So, symantically, I'm trying to accomplish:
call TRIGGER welcome(1234) AFTER INSERT into my_table_2 where my conditions are met
I've seen some examples, and don't quite understand the CREATE FUNCTION x() AS TRIGGER syntax, and it seems that Postgres is steering me in this direction, but examples are lacking in my case. Help! (and thanks in advance!)
In the SQL standard, you define a trigger that fires a trigger function when a certain action is taking place. In your case you want to create an AFTER INSERT trigger whose trigger function calls your "welcome" function.
First the trigger function:
CREATE FUNCTION call_welcome() RETURNS trigger AS $$
DECLARE
cnt integer;
BEGIN
SELECT count(*) INTO cnt FROM my_table_2 WHERE ...;
IF cnt = 1 THEN
PERFORM welcome(NEW.user_id);
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
And the trigger:
CREATE TRIGGER tr_call_welcome
AFTER INSERT ON my_table_2
FOR EACH ROW EXECUTE PROCEDURE call_welcome();