Suppose I have the following tables
CREATE TABLE plugins (
id int primary key,
type text);
insert into plugins values (1,'matrix');
insert into plugins values (2,'matrix');
insert into plugins values (3,'function');
insert into plugins values (4,'function');
CREATE TABLE matrix_params (
id int primary key,
pluginid int references plugins (id)
);
This all works as expected but I would like to add an additional constraint that a matrix_param can only refer to the pluginid that has type ‘matrix’. So
insert into matrix_params values (1,1);
Should succeed but
insert into matrix_params values (2,3);
Should fail.
A simple constraint for matrix_params does not work as it has no way of knowing what the corresponding type is in the plugins table.
You can use a CHECK constraint for this. You can’t put a query in a CHECK constraint but you can call a function; so, we build a simple function that tells us if a
pluginidis a matrix:and wrap that in a CHECK constraint:
Then:
And the FK takes care of referential integrity and cascades.