I use PostgreSQL 12
I have the following two tables:
table_a:
table_a_id | version
1 | v1
2 | v1
3 | v1
4 | v2
5 | v2
6 | v2
table_b:
table_b_id | version | table_a_id
1 | v1 | 1
2 | v1 | 2
3 | v1 | 3
4 | v2 | 4
5 | v2 | 5
6 | v2 | 6
table_b must reference same version table_a_id i.e The below data is valid entry because table_a_id -> 1 belongs to version 'v1'
table_b_id | version | table_a_id
1 | v1 | 1
But the below data is invalid entry because table_a_id -> 4 belongs to version 'v2'
table_b_id | version | table_a_id
1 | v1 | 4
I am new to Postgres trigger functions
I have created the following trigger function to validate ON BEFORE INSERT OR UPDATE to table_b:
CREATE FUNCTION version_check()
RETURNS TRIGGER AS
$BODY$
BEGIN
IF NOT EXISTS (
SELECT
*
FROM
"table_a"
WHERE
"table_a"."table_a_id" = NEW."table_a_id"
AND
"table_a"."version" = NEW."version";
)
THEN
RAISE EXCEPTION 'table_a and table_b Version do not match';
END IF;
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql;
CREATE TRIGGER "version_check" BEFORE INSERT OR UPDATE ON "table_b"
FOR EACH ROW EXECUTE PROCEDURE version_check();
I am getting the following error on saving the Trigger function in pgAdmin 4
ERROR: syntax error at or near "BEGIN"
LINE 8: BEGIN
^
Am i doing any syntax error? Also will the above trigger function work fine for my requirement ?
Thanks in advance!