Refactored the query_generation code