I have a table of users eg:
create table "user" (
id serial primary key,
name text not null,
superuser boolean not null default false
);
and a table with jobs:
create table job (
id serial primary key,
description text
);
the jobs can be assigned to users, but only for superusers. other users cannot have jobs assigned.
So I have a table whereby I see which job was assigned to which user:
create table user_has_job (
user_id integer references "user"(id),
job_id integer references job(id),
constraint user_has_job_pk PRIMARY KEY (user_id, job_id)
);
But I want to create a check constraint that the user_id
references a user that has user.superuser = True
.
Is that possible? Or is there another solution?
Create a separate
superuser
table that inherits from theuser
table:The
user_has_job
table can then reference thesuperuser
table:Move users around between the tables as needed by inserting and deleting:
This would work for INSERTS:
And then a check contraint on the user_has_job table:
Works for inserts:
However this is possible:
So if you allow updating users you need to create an update trigger on the users table to prevent that if the user has jobs.
The only way I can think of is to add a unique constraint on
(id, superuser)
to theusers
table and reference that from theuser_has_job
table by "duplicating" thesuperuser
flag there:Due to the
default
value, you don't have to specify thesuperuser
column when inserting into theuser_has_job
table. So the following insert works:But trying to insert arthur into the table fails:
This also prevents turning ford into a non-superuser. The following update:
fails with the error
I don't know if this is a good way to do it but it seems to work