Refactor query generation