I have 4 entities :
User(id*, ...)
Permission(user_id*, resource_id*, resource_type, role)
Resource1(id*, ...)
Resource2(id*, ...)
Resource1
and Resource2
share no semantic relation and are completely independant.
How can I force my database to ensure that Permission.resource_id
exists in one and exactly one of Resource1
and Resource2
?
I know I can use an intermediate table Resource(id*)
and add a procedure to add the record into that table upon an INSERT statement on Resource1/2 and set a foreign key constraint on Permission.resource_id
to Resource.id
.
Is there any solution to implement that logic without the Resource
table ? I would prefer to use SQLite or PostgreSQL, otherwise I’m happy with a solution in another SQL database engine.
2
Answers
In
PostgreSQL
, you can utilize check constraints along with a deferrable foreign key constraint to enforce the constraint.View
Permission table:
Trigger
Modify your
Permission
table to include bothresource1_id
andresource2_id
. Then add a check constraint to make sure exactly 1 of them is null. You can also cross checkresource_type
vs. the non-null resource id.Permission(user_id*, resource1_id*, resource2_id* resource_type, role);
Sample table DDL with constraints.
This does not require any triggers.