I need to traverse and update the graph in SQL.
To put this into prospective, I’ll give an example:
- Every company can represent other company on a given subject.
- Companies can represent each other, but not for the same subject
This assumes tables like:
companies(id), representations(source_id, destination_id, subject).
But the rule is that when my company is no longer representing yours on a given subject, then no companies down the chain from mine can represent my company on the same subject.
I hope you understand what I mean.
So with the simple data like:
C1:
--sell--> C2
--pay--> C3
C2:
--sell--> C3
--pay--> C1
C3:
--mail--> C1
--sell--> C4
C4:
--deliver-->C1
Now, we remove the representation (I should have called it relation) C2--sell-->C3 we should end up the following structure ([X] – removed):
C1:
--sell--> C2
--pay--> C3
C2:
[X]--sell--> C3
--pay--> C1
C3:
--mail--> C1
[X]--sell--> C4
C4:
--deliver-->C1
So the question is how is it possible to select all the companies, that are down the chain from mine for a given subject?
I suppose recursive CTE expression is the only way to do it.
NOTES:
- The structure is not a tree, it is an ordered cyclic graph.
- Graph database isn’t an option for now (this is only a small part of the system)
- The updates don’t need to be immediate and it’s ok for them to be eventually consistent (talking about few seconds to minutes).
Sounds like you need to maintain a transitive closure of the graph for each subject. Look at a paper about how to implement an incremental evaluation system (IES) with SQL, seems to be able to do the trick. The paper has extensive SQL examples for directed acyclic, undirected and arbitrary directed graphs.
It appears that for each of your subject the graph is acyclic, which is fortunately the simplest case.