Refactored database code