Refactor to separate query generation logic.