# Buggy code
def get_sql_results(
    ctask,
    query_id,
    rendered_query,
    return_results=True,
    store_results=False,
    user_name=None,
    start_time=None,
    expand_data=False,
):
    """Executes the sql query returns the results."""
    with session_scope(not ctask.request.called_directly) as session:
        try:
            return execute_sql_statements(
                ctask,
                query_id,
                rendered_query,
                return_results,
                store_results,
                user_name,
                session=session,
                start_time=start_time,
                expand_data=expand_data,
            )
        except Exception as e:
            logging.exception(f"Query {query_id}: {e}")
            stats_logger.incr("error_sqllab_unhandled")
            query = get_query(query_id, session)
            return handle_query_error(str(e), query, session)


# Traceback (RuntimeError)
Task sql_lab.get_sql_results[051acb0d-30a5-4dbe-b30e-5b16bc9d8545] raised unexpected: RuntimeError('Working outside of application context.\n\nThis typically means that you attempted to use functionality that needed\nto interface with the current application object in some way. To solve\nthis, set up an application context with app.app_context().  See the\ndocumentation for more information.',)
Traceback (most recent call last):
File "/Users/rob/work/incubator-superset/venv/lib/python3.6/site-packages/celery/app/trace.py", line 385, in trace_task
R = retval = fun(*args, **kwargs)
File "/Users/rob/work/incubator-superset/venv/lib/python3.6/site-packages/celery/app/trace.py", line 648, in __protected_call__
return self.run(*args, **kwargs)
File "/Users/rob/work/incubator-superset/superset/sql_lab.py", line 154, in get_sql_results
with session_scope(not ctask.request.called_directly) as session:
File "/Users/rob/work/incubator-superset/venv/lib/python3.6/site-packages/contextlib2.py", line 79, in __enter__
return next(self.gen)
File "/Users/rob/work/incubator-superset/superset/sql_lab.py", line 117, in session_scope
app.config["SQLALCHEMY_DATABASE_URI"], poolclass=NullPool
File "/Users/rob/work/incubator-superset/venv/lib/python3.6/site-packages/werkzeug/local.py", line 348, in __getattr__
return getattr(self._get_current_object(), name)
File "/Users/rob/work/incubator-superset/venv/lib/python3.6/site-packages/werkzeug/local.py", line 307, in _get_current_object
return self.__local()
File "/Users/rob/work/incubator-superset/venv/lib/python3.6/site-packages/flask/globals.py", line 52, in _find_app
raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context().  See the
documentation for more information.

# Fixed code
def get_sql_results(
    ctask,
    query_id,
    rendered_query,
    return_results=True,
    store_results=False,
    user_name=None,
    start_time=None,
    expand_data=False,
):
    """Executes the sql query returns the results."""
    with session_scope(not ctask.request.called_directly) as session:
        try:
            return execute_sql_statements(
                ctask,
                query_id,
                rendered_query,
                return_results,
                store_results,
                user_name,
                session=session,
                start_time=start_time,
                expand_data=expand_data,
            )
        except Exception as e:
            logger.exception(f"Query {query_id}: {e}")
            stats_logger.incr("error_sqllab_unhandled")
            query = get_query(query_id, session)
            return handle_query_error(str(e), query, session)