Refactor query builder