Refactor database access