Fix a subtle race condition when closing database handles