Skip to content

chore/trigger tests #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions trigger_tests/trigger_depth.sql
Original file line number Diff line number Diff line change
@@ -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();
30 changes: 30 additions & 0 deletions trigger_tests/triggers.sql
Original file line number Diff line number Diff line change
@@ -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();