dpgaspar commented on code in PR #22809: URL: https://github.com/apache/superset/pull/22809#discussion_r1088814172
########## superset/sqllab/api.py: ########## @@ -0,0 +1,258 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +import logging +from typing import Any, cast, Dict, Optional + +import simplejson as json +from flask import request +from flask_appbuilder.api import expose, protect, rison +from flask_appbuilder.models.sqla.interface import SQLAInterface +from marshmallow import ValidationError + +from superset import app, is_feature_enabled +from superset.constants import MODEL_API_RW_METHOD_PERMISSION_MAP +from superset.databases.dao import DatabaseDAO +from superset.extensions import event_logger +from superset.jinja_context import get_template_processor +from superset.models.sql_lab import Query +from superset.queries.dao import QueryDAO +from superset.sql_lab import get_sql_results +from superset.sqllab.command_status import SqlJsonExecutionStatus +from superset.sqllab.commands.execute import CommandResult, ExecuteSqlCommand +from superset.sqllab.commands.results import SqlExecutionResultsCommand +from superset.sqllab.exceptions import ( + QueryIsForbiddenToAccessException, + SqlLabException, +) +from superset.sqllab.execution_context_convertor import ExecutionContextConvertor +from superset.sqllab.query_render import SqlQueryRenderImpl +from superset.sqllab.schemas import ( + ExecutePayloadSchema, + QueryExecutionResponseSchema, + sql_lab_get_results_schema, +) +from superset.sqllab.sql_json_executer import ( + ASynchronousSqlJsonExecutor, + SqlJsonExecutor, + SynchronousSqlJsonExecutor, +) +from superset.sqllab.sqllab_execution_context import SqlJsonExecutionContext +from superset.sqllab.validators import CanAccessQueryValidatorImpl +from superset.superset_typing import FlaskResponse +from superset.utils import core as utils +from superset.views.base import json_success +from superset.views.base_api import ( + BaseSupersetModelRestApi, + requires_json, + statsd_metrics, +) + +config = app.config +logger = logging.getLogger(__name__) + + +class SqlLabRestApi(BaseSupersetModelRestApi): Review Comment: we can just inherit from `BaseApi`. `BaseSupersetModelRestApi` is when we want to get free CRUD REST API endpoints out of a SQLAlchemy model. note: we loose superset custom responses, we prob need to create a `BaseSupersetApi` we this override ########## superset/sqllab/api.py: ########## @@ -0,0 +1,258 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +import logging +from typing import Any, cast, Dict, Optional + +import simplejson as json +from flask import request +from flask_appbuilder.api import expose, protect, rison +from flask_appbuilder.models.sqla.interface import SQLAInterface +from marshmallow import ValidationError + +from superset import app, is_feature_enabled +from superset.constants import MODEL_API_RW_METHOD_PERMISSION_MAP +from superset.databases.dao import DatabaseDAO +from superset.extensions import event_logger +from superset.jinja_context import get_template_processor +from superset.models.sql_lab import Query +from superset.queries.dao import QueryDAO +from superset.sql_lab import get_sql_results +from superset.sqllab.command_status import SqlJsonExecutionStatus +from superset.sqllab.commands.execute import CommandResult, ExecuteSqlCommand +from superset.sqllab.commands.results import SqlExecutionResultsCommand +from superset.sqllab.exceptions import ( + QueryIsForbiddenToAccessException, + SqlLabException, +) +from superset.sqllab.execution_context_convertor import ExecutionContextConvertor +from superset.sqllab.query_render import SqlQueryRenderImpl +from superset.sqllab.schemas import ( + ExecutePayloadSchema, + QueryExecutionResponseSchema, + sql_lab_get_results_schema, +) +from superset.sqllab.sql_json_executer import ( + ASynchronousSqlJsonExecutor, + SqlJsonExecutor, + SynchronousSqlJsonExecutor, +) +from superset.sqllab.sqllab_execution_context import SqlJsonExecutionContext +from superset.sqllab.validators import CanAccessQueryValidatorImpl +from superset.superset_typing import FlaskResponse +from superset.utils import core as utils +from superset.views.base import json_success +from superset.views.base_api import ( + BaseSupersetModelRestApi, + requires_json, + statsd_metrics, +) + +config = app.config +logger = logging.getLogger(__name__) + + +class SqlLabRestApi(BaseSupersetModelRestApi): + datamodel = SQLAInterface(Query) + + include_route_methods = { Review Comment: if inheriting from `BaseApi` we don't need this anymore ########## superset/sqllab/schemas.py: ########## @@ -0,0 +1,83 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from marshmallow import fields, Schema + +sql_lab_get_results_schema = { + "type": "object", + "properties": { + "key": {"type": "string"}, + }, + "required": ["key"], +} + + +class ExecutePayloadSchema(Schema): + database_id = fields.Integer(required=True) + sql = fields.String(required=True) + client_id = fields.String(allow_none=True) + queryLimit = fields.Integer(allow_none=True) + sql_editor_id = fields.String(allow_none=True) + schema = fields.String(allow_none=True) + tab = fields.String(allow_none=True) + ctas_method = fields.String(allow_none=True) + templateParams = fields.String(allow_none=True) + tmp_table_name = fields.String(allow_none=True) Review Comment: mixed camel and snake, can we fix this? ########## superset/sqllab/commands/results.py: ########## @@ -0,0 +1,131 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# pylint: disable=too-few-public-methods, too-many-arguments +from __future__ import annotations + +import logging +from typing import Any, cast, Dict, Optional + +from flask_babel import gettext as __, lazy_gettext as _ + +from superset import app, db, results_backend, results_backend_use_msgpack +from superset.commands.base import BaseCommand +from superset.errors import ErrorLevel, SupersetError, SupersetErrorType +from superset.exceptions import SerializationError, SupersetErrorException +from superset.models.sql_lab import Query +from superset.sqllab.utils import apply_display_max_row_configuration_if_require +from superset.utils import core as utils +from superset.utils.dates import now_as_float +from superset.views.utils import _deserialize_results_payload + +config = app.config +SQLLAB_QUERY_COST_ESTIMATE_TIMEOUT = config["SQLLAB_QUERY_COST_ESTIMATE_TIMEOUT"] +stats_logger = config["STATS_LOGGER"] + +logger = logging.getLogger(__name__) + + +class SqlExecutionResultsCommand(BaseCommand): + _key: str + _rows: Optional[int] + _blob: Any + _query: Query + + def __init__( + self, + key: str, + rows: Optional[int] = None, + ) -> None: + self._key = key + self._rows = rows + + def validate(self) -> None: + if not results_backend: + raise SupersetErrorException( + SupersetError( + message=__("Results backend is not configured."), + error_type=SupersetErrorType.RESULTS_BACKEND_NOT_CONFIGURED_ERROR, + level=ErrorLevel.ERROR, + ) + ) + + read_from_results_backend_start = now_as_float() + self._blob = results_backend.get(self._key) + stats_logger.timing( + "sqllab.query.results_backend_read", + now_as_float() - read_from_results_backend_start, + ) + + if not self._blob: + raise SupersetErrorException( + SupersetError( + message=__( + "Data could not be retrieved from the results backend. You " + "need to re-run the original query." + ), + error_type=SupersetErrorType.RESULTS_BACKEND_ERROR, + level=ErrorLevel.ERROR, + ), + status=410, + ) + + self._query = ( + db.session.query(Query).filter_by(results_key=self._key).one_or_none() + ) + if self._query is None: + raise SupersetErrorException( + SupersetError( + message=__( + "The query associated with these results could not be find. " Review Comment: "The query associated with these results could not be found. " ########## superset/sqllab/api.py: ########## @@ -0,0 +1,258 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +import logging +from typing import Any, cast, Dict, Optional + +import simplejson as json +from flask import request +from flask_appbuilder.api import expose, protect, rison +from flask_appbuilder.models.sqla.interface import SQLAInterface +from marshmallow import ValidationError + +from superset import app, is_feature_enabled +from superset.constants import MODEL_API_RW_METHOD_PERMISSION_MAP +from superset.databases.dao import DatabaseDAO +from superset.extensions import event_logger +from superset.jinja_context import get_template_processor +from superset.models.sql_lab import Query +from superset.queries.dao import QueryDAO +from superset.sql_lab import get_sql_results +from superset.sqllab.command_status import SqlJsonExecutionStatus +from superset.sqllab.commands.execute import CommandResult, ExecuteSqlCommand +from superset.sqllab.commands.results import SqlExecutionResultsCommand +from superset.sqllab.exceptions import ( + QueryIsForbiddenToAccessException, + SqlLabException, +) +from superset.sqllab.execution_context_convertor import ExecutionContextConvertor +from superset.sqllab.query_render import SqlQueryRenderImpl +from superset.sqllab.schemas import ( + ExecutePayloadSchema, + QueryExecutionResponseSchema, + sql_lab_get_results_schema, +) +from superset.sqllab.sql_json_executer import ( + ASynchronousSqlJsonExecutor, + SqlJsonExecutor, + SynchronousSqlJsonExecutor, +) +from superset.sqllab.sqllab_execution_context import SqlJsonExecutionContext +from superset.sqllab.validators import CanAccessQueryValidatorImpl +from superset.superset_typing import FlaskResponse +from superset.utils import core as utils +from superset.views.base import json_success +from superset.views.base_api import ( + BaseSupersetModelRestApi, + requires_json, + statsd_metrics, +) + +config = app.config +logger = logging.getLogger(__name__) + + +class SqlLabRestApi(BaseSupersetModelRestApi): + datamodel = SQLAInterface(Query) + + include_route_methods = { + "get_results", + "execute_sql_query", + } + resource_name = "sqllab" + allow_browser_login = True + + class_permission_name = "Query" + method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP Review Comment: if inheriting from BaseApi we don't need this anymore ########## superset/sqllab/schemas.py: ########## @@ -0,0 +1,83 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from marshmallow import fields, Schema + +sql_lab_get_results_schema = { + "type": "object", + "properties": { + "key": {"type": "string"}, + }, + "required": ["key"], +} + + +class ExecutePayloadSchema(Schema): + database_id = fields.Integer(required=True) + sql = fields.String(required=True) + client_id = fields.String(allow_none=True) + queryLimit = fields.Integer(allow_none=True) + sql_editor_id = fields.String(allow_none=True) + schema = fields.String(allow_none=True) + tab = fields.String(allow_none=True) + ctas_method = fields.String(allow_none=True) + templateParams = fields.String(allow_none=True) + tmp_table_name = fields.String(allow_none=True) + select_as_cta = fields.Boolean(allow_none=True) + json = fields.Boolean(allow_none=True) + runAsync = fields.Boolean(allow_none=True) + expand_data = fields.Boolean(allow_none=True) + + +class QueryResultSchema(Schema): Review Comment: these mixed snake_case and camelCase names... how hard on the frontend to just get everything to snake_case? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
