Refactored database code (untested!)