Ensures that database sessions are cleaned up.

This commit introduces some code to ensure that all database
sessions have been cleaned up when it is no longer needed.