fixed errors related to cascading deletions

@Wilduck this changes the postgres trigger to an initially deferred trigger. This will make it execute after a transaction is complete. I also updated the logic to check that entities exist before inserting an entity relationship deactivation event. This happens in the case of cascading deletions. I wrote a failing test that was fixed with this patch
Can you give me the logic for using a constraint trigger here? I know that this affects the timing of the trigger within a transaction, but I'm curious why it matters in this case.