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