Executes the sql query returns the results.
( # pylint: disable=too-many-arguments, too-many-locals, too-many-statements, too-many-branches
query_id: int,
rendered_query: str,
return_results: bool,
store_results: bool,
user_name: Optional[str],
session: Session,
start_time: Optional[float],
expand_data: bool,
log_params: Optional[Dict[str, Any]],
)
| 340 | |
| 341 | |
| 342 | def execute_sql_statements( # pylint: disable=too-many-arguments, too-many-locals, too-many-statements, too-many-branches |
| 343 | query_id: int, |
| 344 | rendered_query: str, |
| 345 | return_results: bool, |
| 346 | store_results: bool, |
| 347 | user_name: Optional[str], |
| 348 | session: Session, |
| 349 | start_time: Optional[float], |
| 350 | expand_data: bool, |
| 351 | log_params: Optional[Dict[str, Any]], |
| 352 | ) -> Optional[Dict[str, Any]]: |
| 353 | """Executes the sql query returns the results.""" |
| 354 | if store_results and start_time: |
| 355 | # only asynchronous queries |
| 356 | stats_logger.timing("sqllab.query.time_pending", now_as_float() - start_time) |
| 357 | |
| 358 | query = get_query(query_id, session) |
| 359 | payload: Dict[str, Any] = dict(query_id=query_id) |
| 360 | database = query.database |
| 361 | db_engine_spec = database.db_engine_spec |
| 362 | db_engine_spec.patch() |
| 363 | |
| 364 | if database.allow_run_async and not results_backend: |
| 365 | raise SupersetErrorException( |
| 366 | SupersetError( |
| 367 | message=__("Results backend is not configured."), |
| 368 | error_type=SupersetErrorType.RESULTS_BACKEND_NOT_CONFIGURED_ERROR, |
| 369 | level=ErrorLevel.ERROR, |
| 370 | ) |
| 371 | ) |
| 372 | |
| 373 | # Breaking down into multiple statements |
| 374 | parsed_query = ParsedQuery(rendered_query, strip_comments=True) |
| 375 | if not db_engine_spec.run_multiple_statements_as_one: |
| 376 | statements = parsed_query.get_statements() |
| 377 | logger.info( |
| 378 | "Query %s: Executing %i statement(s)", str(query_id), len(statements) |
| 379 | ) |
| 380 | else: |
| 381 | statements = [rendered_query] |
| 382 | logger.info("Query %s: Executing query as a single statement", str(query_id)) |
| 383 | |
| 384 | logger.info("Query %s: Set query to 'running'", str(query_id)) |
| 385 | query.status = QueryStatus.RUNNING |
| 386 | query.start_running_time = now_as_float() |
| 387 | session.commit() |
| 388 | |
| 389 | # Should we create a table or view from the select? |
| 390 | if ( |
| 391 | query.select_as_cta |
| 392 | and query.ctas_method == CtasMethod.TABLE |
| 393 | and not parsed_query.is_valid_ctas() |
| 394 | ): |
| 395 | raise SupersetErrorException( |
| 396 | SupersetError( |
| 397 | message=__( |
| 398 | "CTAS (create table as select) can only be run with a query where " |
| 399 | "the last statement is a SELECT. Please make sure your query has " |