From dede3c66deedee4db281cbe490f887328a918a77 Mon Sep 17 00:00:00 2001 From: Andy Atkinson Date: Tue, 26 Mar 2024 21:24:17 -0500 Subject: [PATCH 1/2] Start some triggers --- trigger_tests/triggers.sql | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 trigger_tests/triggers.sql diff --git a/trigger_tests/triggers.sql b/trigger_tests/triggers.sql new file mode 100644 index 0000000..6e4c281 --- /dev/null +++ b/trigger_tests/triggers.sql @@ -0,0 +1,30 @@ +-- https://www.postgresql.org/docs/current/plpgsql-trigger.html + +CREATE TABLE employees ( + id integer, + salary integer default 0, + updated_at timestamptz +); + +CREATE FUNCTION employee_calc() RETURNS trigger AS $employee_calc$ + BEGIN + -- Check that salary is not null + IF NEW.salary IS NULL THEN + RAISE EXCEPTION 'salary cannot be null'; + END IF; + IF NEW.salary IS NULL THEN + RAISE EXCEPTION '% cannot have null salary', NEW.id; + END IF; + + -- Who works for us when they must pay for it? + IF NEW.salary < 0 THEN + RAISE EXCEPTION '% cannot have a negative salary', NEW.id; + END IF; + + NEW.updated_at := current_timestamp; + RETURN NEW; + END; +$employee_calc$ LANGUAGE plpgsql; + +CREATE TRIGGER employee_calc BEFORE INSERT OR UPDATE ON employees + FOR EACH ROW EXECUTE FUNCTION employee_calc(); From 8dafdf0bbc7023d46843030216f9f0f50d799510 Mon Sep 17 00:00:00 2001 From: Andy Atkinson Date: Tue, 26 Mar 2024 22:02:15 -0500 Subject: [PATCH 2/2] Add trigger depth example --- trigger_tests/trigger_depth.sql | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 trigger_tests/trigger_depth.sql diff --git a/trigger_tests/trigger_depth.sql b/trigger_tests/trigger_depth.sql new file mode 100644 index 0000000..ec58776 --- /dev/null +++ b/trigger_tests/trigger_depth.sql @@ -0,0 +1,25 @@ + +-- https://pgpedia.info/p/pg_trigger_depth.html +CREATE TABLE foo (id INT, val TEXT); + +CREATE OR REPLACE FUNCTION trigger_depth() + RETURNS TRIGGER + LANGUAGE plpgsql +AS $$ + DECLARE + depth INT; + BEGIN + depth := pg_trigger_depth(); + RAISE NOTICE 'depth: %', depth; + IF depth = 1 THEN + INSERT INTO foo VALUES(-1, 'test'); + END IF; + RETURN NEW; + END; +$$; + +CREATE TRIGGER foo_ins_trigger + BEFORE INSERT + ON foo + FOR EACH ROW + EXECUTE FUNCTION trigger_depth();