Refactor database code