Is it possible to create a partial foreign key (similar to partial indexes) in general sql / postgresql? I have not found a way to force referential integrity in the following case:
Table A is soft-deletable (it has a column deleted_at, which is set to a value when a row is to be marked as such), while Table B is hard-deletable (meaning we actually delete the rows)
table A:
- id
- deleted_at
- some other stuff
- partial unique index for id where deleted_at is null
table B:
- id
- deleted_at
- some other stuff
- partial unique index for id where deleted_at is null
table C:
- referred type
- referred id
- some other stuff
The rows in tables A,B,C represent objects of a certain class. The relation between them that every C needs to reference either an A or a B, marked by the value of the "type" column, and the "id" will mark which instance of the object is referred to.
What I would like to achieve is to force the integrity, so that for all rows in table C where referred type is 'MyData::A', the referred_id must match a row in table A's partial index (where deleted_at is null), similarly for B
Something like
ADD CONSTRAINT name FOREIGN KEY table_C(referred_id)
REFERENCES table_A(id where deleted_at is not null)
where referred_type = 'MyData::A'
ADD CONSTRAINT name FOREIGN KEY table_C(referred_id)
REFERENCES table_B(id where deleted_at is not null)
where referred_type = 'MyData::B'
Which obviously is bogus syntax.
If this is not possible, would it be possible to do, without messing around with the possibility to have two types of referred objects in different tables, like so:
CREATE VIEW A_B_ids AS SELECT id, deleted_at From table_A
UNION SELECT id, deleted_at FROM table_B
ADD CONSTRAINT name FOREIGN KEY table_C(referred_id)
REFERENCES A_B_ids(id where deleted_at is not null)
TRIGGER
– Hap