Query generation refactor.