Passing a procedure arguments to a trigger - postgresql

I have a table say:
CREATE TABLE comment (
comment_id SERIAL PRIMARY KEY,
content varchar
);
and another:
CREATE TABLE comment_tree (
ancestor integer NOT NULL,
descendant integer NOT NULL,
PRIMARY KEY (ancestor, descendant),
FOREIGN KEY (ancestor) REFERENCES comment (comment_id),
FOREIGN KEY (descendant) REFERENCES comment (comment_id)
);
Now I have a procedure which insert a new comment as a child of another comment:
CREATE OR REPLACE PROCEDURE add_comment(content varchar, parent_id integer) AS $$
DECLARE
cid integer;
BEGIN
INSERT INTO comment (content) VALUES (content)
RETURNING comment_id INTO cid;
INSERT INTO comment_tree (ancestor, descendant)
VALUES (parent_id, cid);
END;
$$ LANGUAGE plpgsql;
But I want to know if it is possible to pass the parent_id to a trigger when I call the procedure instead of inserting into comment_tree inside the procedure?

You cannot pass an arbitrary variable directly to a trigger. You can use a temporary table that simulate a kind of pipe. Create a temporary table with the value you want to pass in the procedure:
CREATE OR REPLACE PROCEDURE add_comment(content varchar, parent_id integer) AS $$
DECLARE
pid integer;
BEGIN
CREATE TEMP TABLE my_temp_table AS SELECT parent_id;
INSERT INTO comment (content) VALUES (content)
RETURNING comment_id INTO pid;
DROP TABLE my_temp_table;
END;
$$ LANGUAGE plpgsql;
Then you can use it in the trigger fired after insertion:
CREATE OR REPLACE FUNCTION after_insert_on_comment()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO comment_tree (ancestor, descendant)
SELECT parent_id, new.comment_id
FROM my_temp_table;
RETURN null;
END $$;
Test it in db<>fiddle.

Related

How do I update a summary table with a trigger?

I am working with the sample DVD_Rental database. I have to create a trigger on my category_performance_details table that will create a summary table every time data is added to the detail table.
These are the queries I am using to setup my tables:
DROP TABLE IF EXISTS category_performance_summary;
CREATE TABLE category_performance_summary (
genre VARCHAR(25),
total_sales numeric
);
DROP TABLE IF EXISTS category_performance_details;
CREATE TABLE if not exists category_performance_details (
category_id Int,
category_name VARCHAR(25),
film_id Int,
film_title VARCHAR(255),
film_rental_rate numeric(4,2),
inventory_id Int,
payment_id Int,
payment_amount numeric(4,2),
rental_id Int,
rental_date Timestamp
);
I want to update the summary table after every insert statement with a trigger so that it provides a summary of the total sales per category. Basically, the summary table should be the same result as:
SELECT category_name, SUM(payment_amount) FROM category_performance_details
GROUP BY category_name;
This is my procedure and trigger. For some reason, I am getting a syntax error at or near "CREATE TRIGGER". Am I approaching this trigger correctly? What is wrong with my syntax?
CREATE OR REPLACE FUNCTION update_summary_table()
RETURNS TRIGGER
LANGUAGE PLPGSQL
AS
$$
BEGIN
TRUNCATE TABLE category_performance_summary;
INSERT INTO category_performance_summary (genre, total_sales)
SELECT category_name, SUM(payment_amount)
FROM category_performance_details
GROUP BY category_name;
RETURN NEW;
END;
$$
CREATE TRIGGER update_summary
AFTER INSERT
ON category_performance_summary
FOR EACH STATEMENT
EXECUTE PROCEDURE update_summary_table();
You can also simply increment or decrement the total_sales in the trigger function.
In any case you have to use the NEW (resp. OLD) key word in order to refer to the values that are inserted/updated (resp. deleted) in table category_performance_summary :
CREATE OR REPLACE FUNCTION increment_summary_table()
RETURNS TRIGGER
LANGUAGE PLPGSQL
AS
$$
BEGIN
INSERT INTO category_performance_summary (genre, total_sales)
VALUES (NEW.category_name, 1)
ON CONFLICT (genre) DO UPDATE
SET total_sales= total_sales + 1
WHERE genre= NEW.category_name ;
RETURN NEW;
END;
$$ ;
CREATE TRIGGER increment_summary
AFTER INSERT
ON category_performance_summary
FOR EACH STATEMENT
EXECUTE PROCEDURE increment_summary_table();
CREATE OR REPLACE FUNCTION decrement_summary_table()
RETURNS TRIGGER
LANGUAGE PLPGSQL
AS
$$
BEGIN
UPDATE category_performance_summary
SET total_sales= total_sales - 1
WHERE genre= OLD.category_name ;
RETURN OLD;
END;
$$ ;
CREATE TRIGGER decrement_summary
AFTER DELETE
ON category_performance_summary
FOR EACH STATEMENT
EXECUTE PROCEDURE decrement_summary_table();

How to upsert with serial primary key

I have a stored procedure to perform an upsert. However the conflict condition never runs, passing an existing ID always causes it to create a new record.
create or replace function upsert_email(v_id bigint, v_subject character varying)
returns bigint
language plpgsql
as $$
declare
v_id bigint;
begin
insert into emails
(id, subject)
values (coalesce(v_id, (select nextval('serial'))), v_subject)
on conflict(id)
do update set (subject) = (v_subject) where emails.id = v_id
returning id into v_id;
return v_id;
end;
$$;
When running select upsert_email(6958500, 'subject'); which is a record that exists, it always creates a new record instead.
I have already looked at: Upsert/on conflict with serial primary key which is the most similar question and is what my SQL is modeled on, however I haven't been able to get it to work.
Wow, idiot of the year award goes to me.
I'm taking a parameter called v_id, then immediately overwrite it in the declare with a v_id; They should be named 2 different things:
create or replace function upsert_email(v_id bigint, v_subject character varying)
returns bigint
language plpgsql
as $$
declare
v_return_id bigint;
begin
insert into emails
(id, subject)
values (coalesce(v_id, (select nextval('serial'))), v_subject)
on conflict(id)
do update set (subject) = (v_subject) where emails.id = v_id
returning id into v_return_id;
return v_return_id;
end;
$$;

create child table function using cursor in postgresql

CREATE FUNCTION create_child1()
RETURNS TABLE(sys_user_id integer,
sys_service_id integer
)
LANGUAGE 'plpgsql'
COST 100
VOLATILE
ROWS 1000
AS $BODY$
DECLARE
curr_id CURSOR IS
SELECT id FROM users WHERE id in (3089,3090,3091,3092);
v_id bigint;
BEGIN
OPEN curr_id;
LOOP
FETCH curr_id INTO v_id;
EXIT WHEN not found ;
EXECUTE format('
CREATE TABLE IF NOT EXISTS %I (
sys_user_id integer,
sys_service_id integer
id bigint NOT NULL primary key
)
INHERITS (telemetry_master)
WITH (
OIDS=FALSE
)', 'telemetry_' || v_id);
end loop;
close curr_id;
fetch next from curr_id into v_id;
END
$BODY$ LANGUAGE plpgsql;
You do not need an explicit cursor in your function. You can use a simple FOR ... IN ... LOOP.
It is unclear what you want to return from the function. For example, it can return a readable text about each created table.
CREATE OR REPLACE FUNCTION create_child1()
RETURNS SETOF text LANGUAGE plpgsql
AS $BODY$
DECLARE
v_id int;
BEGIN
FOR v_id IN 3089..3092 LOOP
EXECUTE format('
CREATE TABLE IF NOT EXISTS telemetry_%s (
sys_user_id integer,
sys_service_id integer,
id bigint NOT NULL primary key
)
INHERITS (telemetry_master)', v_id);
RETURN NEXT format('telemetry_%s created.', v_id);
END LOOP;
END $BODY$;
Use:
SELECT create_child1();
create_child1
-------------------------
telemetry_3089 created.
telemetry_3090 created.
telemetry_3091 created.
telemetry_3092 created.
(4 rows)
If the ids are not consecutive you can use unnest(), e.g.:
FOR v_id IN SELECT id FROM unnest(array[3000,3001,3020,3021]) AS id LOOP

Insert within function fails with "query has no destination for result data"

Here is the complete example code:
CREATE TABLE testtbl (
id integer NOT NULL,
intval integer,
strval varchar(64)
);
CREATE SEQUENCE testtbl_id_seq
START WITH 1 INCREMENT BY 1
NO MINVALUE NO MAXVALUE CACHE 1;
ALTER SEQUENCE testtbl_id_seq OWNED BY testtbl.id;
ALTER TABLE ONLY testtbl ALTER COLUMN id SET DEFAULT
nextval('testtbl_id_seq'::regclass);
ALTER TABLE ONLY testtbl ADD CONSTRAINT testtbl_pkey PRIMARY KEY (id);
CREATE FUNCTION insert_testtbl (p_intval integer, p_strval varchar(64))
RETURNS integer AS $$
DECLARE
v_new_id integer;
BEGIN
INSERT INTO testtbl (intval, strval) VALUES (p_intval, p_strval)
RETURNING v_new_id;
RETURN v_new_id;
END;
$$ LANGUAGE plpgsql;
SELECT insert_testtbl(1, 'One');
When I run this (PostgreSQL version is 9.6.1), I get:
ERROR: query has no destination for result data
CONTEXT: PL/pgSQL function insert_testtbl(integer,character varying) line 5 at SQL statement
This doesn't make sense; I AM specifying a destination for the result!
What am I doing wrong here? Thanks!!!
I am specifying a destination for the result!
No you are not.
RETURNING v_new_id; simply means:
"return the current value of the variable v_new_id from this insert statement"
(which is null as the variable was never assigned a value)
You are not storing the generated value anywhere.
You either need to use an into clause:
CREATE FUNCTION insert_testtbl (p_intval integer, p_strval varchar(64))
RETURNS integer AS $$
DECLARE
v_new_id integer;
BEGIN
INSERT INTO testtbl (intval, strval) VALUES (p_intval, p_strval)
RETURNING id
INTO v_new_id; --<<< HERE
RETURN v_new_id;
END;
$$ LANGUAGE plpgsql;
Or convert everything it simple SQL function:
CREATE FUNCTION insert_testtbl (p_intval integer, p_strval varchar(64))
RETURNS integer AS
$$
INSERT INTO testtbl (intval, strval) VALUES (p_intval, p_strval)
RETURNING id;
$$ LANGUAGE sql;

Trigger insert into another table only if unique value

I have a trigger function that copy row of unique values to another table on update or insert that ALMOST work.
The trigger should only insert a new row to the sample table if the number don't exist in it before. Atm. it insert a new row to the sample table with the value NULL if the number already exist in the table. I dont want it to do anything if maintbl.number = sample.nb_main
EDIT: sample table and sample data
CREATE TABLE schema.main(
sid SERIAL NOT NULL,
number INTEGER,
CONSTRAINT sid_pk PRIMARY KEY (sid)
)
CREATE TABLE schema.sample(
gid SERIAL NOT NULL,
nb_main INTEGER,
CONSTRAINT gid_pk PRIMARY KEY (gid)
Example and desired result
schema.main schema.sample
number nb_main
234233 234233
234234 555555
234234
555555
555555
CREATE OR REPLACE FUNCTION schema.update_number()
RETURNS trigger AS
$BODY$
BEGIN
INSERT INTO schema.sample(
nb_main)
SELECT DISTINCT(maintbl.number)
FROM schema.maintbl
WHERE NOT EXISTS (
SELECT nb_main FROM schema.sample WHERE maintbl.number = sample.nb_main);
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION schema.update_number()
OWNER TO postgres;
CREATE TRIGGER update_number
AFTER INSERT OR UPDATE
ON schema.maintbl
FOR EACH ROW
EXECUTE PROCEDURE schema.update_number();
I just found out that my select query is probably wrong, if I run SELECT query by itself it return one row 'NULL' but i should not?
SELECT DISTINCT(maintbl.number)
FROM schema.maintbl
WHERE NOT EXISTS (
SELECT nb_main FROM schema.sample WHERE maintbl.number = sample.nb_main);
Any good advice?
Best
If I understood correctly, you wish to append to schema.sample a number that has been inserted or updated in schema.maintbl, right?
CREATE OR REPLACE FUNCTION schema.update_number()
RETURNS trigger AS
$BODY$
BEGIN
IF (SELECT COUNT(*) FROM schema.sample WHERE number = NEW.number) = 0 THEN
INSERT INTO schema.sample(nb_main) VALUES (NEW.number);
END IF;
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql VOLATILE;