Refactoring query generation