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(); 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();