Extra checking on database creation and closing

This fixes some problems when running multiple tests, where the first
fail corrupts the database.