Postgres Foreign Keys on a generalizing link table

96 views Asked by At

I'm doing some work with a system that has many types of entities that may or may not have access to many types of resources. Setting up these tables I have a structure where I set up an Entity_Sequence and a Resource Sequence, and then create a link table for each different entity and each different Resource to associate them with their respective sequence.

For example, I have a Users_Entities_Link table with the columns user_id referencing User, and entity_id, which is a bigint default nextval(Entity_Sequence).

To top this structure off is an Entities_Resources_Access of (entity_id, resource_id) to denote whether the entity has access to the resource. However, given that each of these entities could be related to any one of the entity link tables and the same for resources and each of the resource tables, I'm trying to figure out what the best way to handle the relationship is. This seems like a fairly rare problem, so I couldn't find help elsewhere on it.

The best that I could determine myself was to run an after deletion trigger on each of the Entity or Resource link tables that would check if the entity or resource exists in the access table, but that's a lot of debt to handle when adding in new potential entities or resources.

Is there a better solution to either the structural problem of how to deal with this many entities accessing many resources issue, or how to handle the sequence relationship better? Do I need to add in a dummy entity table and a dummy resource table that each only have an ID for the link and access tables to link foreign keys to? That seems like a lot of wasted space if I have a large quantity of any given entity or resource, and also something that I would have to manually unlink if it floated without anything referencing it on deletion of a row in an associated table (like a user)

Here's how the setup is currently designed:

Table some_entity_entity_link
    some_entity_id FK refs some_entity(id)
    entity_id not null default nextval(entity_sequence)
Table another_entity_entity_link
    another_entity_id FK refs another_entity(id)
    entity_id not null default nextval(entity_sequence)


Table some_resource_resource_link
    some_resource_id FK refs some_resource(id)
    resource_id not null default nextval(resource_sequence)
Table another_resource_resource_link
    another_resource_id FK refs another_resource(id)
    resource_id not null default nextval(resource_sequence)

Table entities_resources_access
    entity_id
    resource_id
0

There are 0 answers