I need to run some code for cleaning up after a database connection is gracefully closed or rudely interrupted/lost. This clean-up cannot be handled within the scope of a transaction inside the connection. So the clean-up (modifying some records, etc.) must be handled on the server-side in PL/pgSQL or Java etc. after the connection is gone. The clean-up is critical, so it must be done reliably every time.
Is there a hook for code to be called on every connection closure/loss in the Postgres server?