refactoring database code