refactor connection and controller's generate_query method