You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "diegomedina248 (via GitHub)" <gi...@apache.org> on 2023/01/20 19:52:14 UTC

[GitHub] [superset] diegomedina248 opened a new pull request, #22809: wip: chore: migrate /sql_json and /results to apiv1

diegomedina248 opened a new pull request, #22809:
URL: https://github.com/apache/superset/pull/22809

   <!---
   Please write the PR title following the conventions at https://www.conventionalcommits.org/en/v1.0.0/
   Example:
   fix(dashboard): load charts correctly
   -->
   
   ### SUMMARY
   <!--- Describe the change below, including rationale and design decisions -->
   
   ### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
   <!--- Skip this if not applicable -->
   
   ### TESTING INSTRUCTIONS
   <!--- Required! What steps can be taken to manually verify the changes? -->
   
   ### ADDITIONAL INFORMATION
   <!--- Check any relevant boxes with "x" -->
   <!--- HINT: Include "Fixes #nnn" if you are fixing an existing issue -->
   - [ ] Has associated issue:
   - [ ] Required feature flags:
   - [ ] Changes UI
   - [ ] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
     - [ ] Migration is atomic, supports rollback & is backwards-compatible
     - [ ] Confirm DB migration upgrade and downgrade tested
     - [ ] Runtime estimates and downtime expectations provided
   - [ ] Introduces new feature or API
   - [ ] Removes existing feature or API
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] diegomedina248 commented on a diff in pull request #22809: chore: migrate /sql_json and /results to apiv1

Posted by "diegomedina248 (via GitHub)" <gi...@apache.org>.
diegomedina248 commented on code in PR #22809:
URL: https://github.com/apache/superset/pull/22809#discussion_r1085654647


##########
superset/sqllab/api.py:
##########
@@ -0,0 +1,250 @@
+# 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
+
+from flask import request, Response
+from flask_appbuilder.api import expose, protect, rison, safe
+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.views.base import handle_api_exception
+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
+
+    execute_model_schema = ExecutePayloadSchema()
+
+    apispec_parameter_schemas = {
+        "sql_lab_get_results_schema": sql_lab_get_results_schema,
+    }
+    openapi_spec_tag = "SQL Lab"
+    openapi_spec_component_schemas = (
+        ExecutePayloadSchema,
+        QueryExecutionResponseSchema,
+    )
+
+    @expose("/results/")
+    @protect()
+    @safe
+    @statsd_metrics
+    @rison(sql_lab_get_results_schema)
+    @handle_api_exception

Review Comment:
   safe wraps only `BadRequest` error to 400 and a global `Exception` to 500.
   handle_api_exception wraps a set of Superset exceptions which are more specific



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] villebro commented on pull request #22809: chore: migrate /sql_json and /results to apiv1

Posted by "villebro (via GitHub)" <gi...@apache.org>.
villebro commented on PR #22809:
URL: https://github.com/apache/superset/pull/22809#issuecomment-1400669015

   @EugeneTorap I have limited bandhwidth right now, but I agree, these PRs are 💥! I'm prioritizing reviewing + testing #22496 as that is IMO really important, but after that I'll try to find time for this one unless someone else beats me to it.


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] diegomedina248 merged pull request #22809: chore: migrate /sql_json and /results to apiv1

Posted by "diegomedina248 (via GitHub)" <gi...@apache.org>.
diegomedina248 merged PR #22809:
URL: https://github.com/apache/superset/pull/22809


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] dpgaspar commented on a diff in pull request #22809: chore: migrate /sql_json and /results to apiv1

Posted by "dpgaspar (via GitHub)" <gi...@apache.org>.
dpgaspar commented on code in PR #22809:
URL: https://github.com/apache/superset/pull/22809#discussion_r1085516617


##########
superset/sqllab/api.py:
##########
@@ -0,0 +1,250 @@
+# 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
+
+from flask import request, Response
+from flask_appbuilder.api import expose, protect, rison, safe
+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.views.base import handle_api_exception
+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
+
+    execute_model_schema = ExecutePayloadSchema()
+
+    apispec_parameter_schemas = {
+        "sql_lab_get_results_schema": sql_lab_get_results_schema,
+    }
+    openapi_spec_tag = "SQL Lab"
+    openapi_spec_component_schemas = (
+        ExecutePayloadSchema,
+        QueryExecutionResponseSchema,
+    )
+
+    @expose("/results/")
+    @protect()
+    @safe
+    @statsd_metrics
+    @rison(sql_lab_get_results_schema)
+    @handle_api_exception
+    @event_logger.log_this_with_context(
+        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}"
+        f".get_results",
+        log_to_statsd=False,
+    )
+    def get_results(self, **kwargs: Any) -> Response:
+        """Gets the result of a SQL query execution
+        ---
+        get:
+          summary: >-
+            Gets the result of a SQL query execution
+          parameters:
+          - in: query
+            name: q
+            content:
+              application/json:
+                schema:
+                  $ref: '#/components/schemas/sql_lab_get_results_schema'
+          responses:
+            200:
+              description: SQL query execution result
+              content:
+                application/json:
+                  schema:
+                    $ref: '#/components/schemas/QueryExecutionResponseSchema'
+            400:
+              $ref: '#/components/responses/400'
+            401:
+              $ref: '#/components/responses/401'
+            404:
+              $ref: '#/components/responses/404'
+            422:
+              $ref: '#/components/responses/422'

Review Comment:
   don't think this one is possible



##########
superset/sqllab/api.py:
##########
@@ -0,0 +1,250 @@
+# 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
+
+from flask import request, Response
+from flask_appbuilder.api import expose, protect, rison, safe
+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.views.base import handle_api_exception
+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
+
+    execute_model_schema = ExecutePayloadSchema()
+
+    apispec_parameter_schemas = {
+        "sql_lab_get_results_schema": sql_lab_get_results_schema,
+    }
+    openapi_spec_tag = "SQL Lab"
+    openapi_spec_component_schemas = (
+        ExecutePayloadSchema,
+        QueryExecutionResponseSchema,
+    )
+
+    @expose("/results/")
+    @protect()
+    @safe
+    @statsd_metrics
+    @rison(sql_lab_get_results_schema)
+    @handle_api_exception

Review Comment:
   do we need this one? isn't safe enough?



##########
superset/sqllab/api.py:
##########
@@ -0,0 +1,250 @@
+# 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
+
+from flask import request, Response
+from flask_appbuilder.api import expose, protect, rison, safe
+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.views.base import handle_api_exception
+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
+
+    execute_model_schema = ExecutePayloadSchema()
+
+    apispec_parameter_schemas = {
+        "sql_lab_get_results_schema": sql_lab_get_results_schema,
+    }
+    openapi_spec_tag = "SQL Lab"
+    openapi_spec_component_schemas = (
+        ExecutePayloadSchema,
+        QueryExecutionResponseSchema,
+    )
+
+    @expose("/results/")
+    @protect()
+    @safe
+    @statsd_metrics
+    @rison(sql_lab_get_results_schema)
+    @handle_api_exception
+    @event_logger.log_this_with_context(
+        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}"
+        f".get_results",
+        log_to_statsd=False,
+    )
+    def get_results(self, **kwargs: Any) -> Response:
+        """Gets the result of a SQL query execution
+        ---
+        get:
+          summary: >-
+            Gets the result of a SQL query execution
+          parameters:
+          - in: query
+            name: q
+            content:
+              application/json:
+                schema:
+                  $ref: '#/components/schemas/sql_lab_get_results_schema'
+          responses:
+            200:
+              description: SQL query execution result
+              content:
+                application/json:
+                  schema:
+                    $ref: '#/components/schemas/QueryExecutionResponseSchema'
+            400:
+              $ref: '#/components/responses/400'
+            401:
+              $ref: '#/components/responses/401'
+            404:
+              $ref: '#/components/responses/404'
+            422:
+              $ref: '#/components/responses/422'
+            500:
+              $ref: '#/components/responses/500'
+        """
+        params = kwargs["rison"]
+        key = params.get("key")
+        rows = params.get("rows")
+        result = SqlExecutionResultsCommand(key=key, rows=rows).run()
+        return self.response(200, **result)
+
+    @expose("/execute/", methods=["POST"])
+    @protect()
+    @statsd_metrics
+    @requires_json
+    @handle_api_exception
+    @event_logger.log_this_with_context(
+        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}"
+        f".get_results",
+        log_to_statsd=False,
+    )
+    def execute_sql_query(self) -> Response:
+        """Executes a SQL query
+        ---
+        post:
+          description: >-
+            Starts the execution of a SQL query
+          requestBody:
+            description: SQL query and params
+            required: true
+            content:
+              application/json:
+                schema:
+                  $ref: '#/components/schemas/ExecutePayloadSchema'
+          responses:
+            200:
+              description: Query execution result
+              content:
+                application/json:
+                  schema:
+                    $ref: '#/components/schemas/QueryExecutionResponseSchema'
+            202:
+              description: Query execution result, query still running
+              content:
+                application/json:
+                  schema:
+                    $ref: '#/components/schemas/QueryExecutionResponseSchema'
+            400:
+              $ref: '#/components/responses/400'
+            401:
+              $ref: '#/components/responses/401'
+            404:
+              $ref: '#/components/responses/404'

Review Comment:
   don't think this one is possible



##########
superset/sqllab/api.py:
##########
@@ -0,0 +1,250 @@
+# 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
+
+from flask import request, Response
+from flask_appbuilder.api import expose, protect, rison, safe
+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.views.base import handle_api_exception
+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
+
+    execute_model_schema = ExecutePayloadSchema()
+
+    apispec_parameter_schemas = {
+        "sql_lab_get_results_schema": sql_lab_get_results_schema,
+    }
+    openapi_spec_tag = "SQL Lab"
+    openapi_spec_component_schemas = (
+        ExecutePayloadSchema,
+        QueryExecutionResponseSchema,
+    )
+
+    @expose("/results/")
+    @protect()
+    @safe
+    @statsd_metrics
+    @rison(sql_lab_get_results_schema)
+    @handle_api_exception
+    @event_logger.log_this_with_context(
+        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}"
+        f".get_results",
+        log_to_statsd=False,
+    )
+    def get_results(self, **kwargs: Any) -> Response:
+        """Gets the result of a SQL query execution
+        ---
+        get:
+          summary: >-
+            Gets the result of a SQL query execution
+          parameters:
+          - in: query
+            name: q
+            content:
+              application/json:
+                schema:
+                  $ref: '#/components/schemas/sql_lab_get_results_schema'
+          responses:
+            200:
+              description: SQL query execution result
+              content:
+                application/json:
+                  schema:
+                    $ref: '#/components/schemas/QueryExecutionResponseSchema'
+            400:
+              $ref: '#/components/responses/400'
+            401:
+              $ref: '#/components/responses/401'
+            404:
+              $ref: '#/components/responses/404'
+            422:
+              $ref: '#/components/responses/422'
+            500:
+              $ref: '#/components/responses/500'
+        """
+        params = kwargs["rison"]
+        key = params.get("key")
+        rows = params.get("rows")
+        result = SqlExecutionResultsCommand(key=key, rows=rows).run()
+        return self.response(200, **result)
+
+    @expose("/execute/", methods=["POST"])
+    @protect()
+    @statsd_metrics
+    @requires_json
+    @handle_api_exception
+    @event_logger.log_this_with_context(
+        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}"
+        f".get_results",
+        log_to_statsd=False,
+    )
+    def execute_sql_query(self) -> Response:
+        """Executes a SQL query
+        ---
+        post:
+          description: >-
+            Starts the execution of a SQL query
+          requestBody:
+            description: SQL query and params
+            required: true
+            content:
+              application/json:
+                schema:
+                  $ref: '#/components/schemas/ExecutePayloadSchema'
+          responses:
+            200:
+              description: Query execution result
+              content:
+                application/json:
+                  schema:
+                    $ref: '#/components/schemas/QueryExecutionResponseSchema'
+            202:
+              description: Query execution result, query still running
+              content:
+                application/json:
+                  schema:
+                    $ref: '#/components/schemas/QueryExecutionResponseSchema'
+            400:
+              $ref: '#/components/responses/400'
+            401:
+              $ref: '#/components/responses/401'

Review Comment:
   missing 403



##########
superset/sqllab/api.py:
##########
@@ -0,0 +1,250 @@
+# 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
+
+from flask import request, Response
+from flask_appbuilder.api import expose, protect, rison, safe
+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.views.base import handle_api_exception
+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
+
+    execute_model_schema = ExecutePayloadSchema()
+
+    apispec_parameter_schemas = {
+        "sql_lab_get_results_schema": sql_lab_get_results_schema,
+    }
+    openapi_spec_tag = "SQL Lab"
+    openapi_spec_component_schemas = (
+        ExecutePayloadSchema,
+        QueryExecutionResponseSchema,
+    )
+
+    @expose("/results/")
+    @protect()
+    @safe
+    @statsd_metrics
+    @rison(sql_lab_get_results_schema)
+    @handle_api_exception
+    @event_logger.log_this_with_context(
+        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}"
+        f".get_results",
+        log_to_statsd=False,
+    )
+    def get_results(self, **kwargs: Any) -> Response:
+        """Gets the result of a SQL query execution
+        ---
+        get:
+          summary: >-
+            Gets the result of a SQL query execution
+          parameters:
+          - in: query
+            name: q
+            content:
+              application/json:
+                schema:
+                  $ref: '#/components/schemas/sql_lab_get_results_schema'
+          responses:
+            200:
+              description: SQL query execution result
+              content:
+                application/json:
+                  schema:
+                    $ref: '#/components/schemas/QueryExecutionResponseSchema'
+            400:
+              $ref: '#/components/responses/400'
+            401:
+              $ref: '#/components/responses/401'
+            404:
+              $ref: '#/components/responses/404'
+            422:
+              $ref: '#/components/responses/422'
+            500:
+              $ref: '#/components/responses/500'
+        """
+        params = kwargs["rison"]
+        key = params.get("key")
+        rows = params.get("rows")
+        result = SqlExecutionResultsCommand(key=key, rows=rows).run()
+        return self.response(200, **result)
+
+    @expose("/execute/", methods=["POST"])
+    @protect()
+    @statsd_metrics
+    @requires_json
+    @handle_api_exception
+    @event_logger.log_this_with_context(
+        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}"
+        f".get_results",
+        log_to_statsd=False,
+    )
+    def execute_sql_query(self) -> Response:
+        """Executes a SQL query
+        ---
+        post:
+          description: >-
+            Starts the execution of a SQL query
+          requestBody:
+            description: SQL query and params
+            required: true
+            content:
+              application/json:
+                schema:
+                  $ref: '#/components/schemas/ExecutePayloadSchema'
+          responses:
+            200:
+              description: Query execution result
+              content:
+                application/json:
+                  schema:
+                    $ref: '#/components/schemas/QueryExecutionResponseSchema'
+            202:
+              description: Query execution result, query still running
+              content:
+                application/json:
+                  schema:
+                    $ref: '#/components/schemas/QueryExecutionResponseSchema'
+            400:
+              $ref: '#/components/responses/400'
+            401:
+              $ref: '#/components/responses/401'
+            404:
+              $ref: '#/components/responses/404'
+            422:
+              $ref: '#/components/responses/422'

Review Comment:
   don't think this one is possible



##########
superset/sqllab/api.py:
##########
@@ -0,0 +1,250 @@
+# 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
+
+from flask import request, Response
+from flask_appbuilder.api import expose, protect, rison, safe
+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.views.base import handle_api_exception
+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
+
+    execute_model_schema = ExecutePayloadSchema()
+
+    apispec_parameter_schemas = {
+        "sql_lab_get_results_schema": sql_lab_get_results_schema,
+    }
+    openapi_spec_tag = "SQL Lab"
+    openapi_spec_component_schemas = (
+        ExecutePayloadSchema,
+        QueryExecutionResponseSchema,
+    )
+
+    @expose("/results/")
+    @protect()
+    @safe
+    @statsd_metrics
+    @rison(sql_lab_get_results_schema)
+    @handle_api_exception
+    @event_logger.log_this_with_context(
+        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}"
+        f".get_results",
+        log_to_statsd=False,
+    )
+    def get_results(self, **kwargs: Any) -> Response:
+        """Gets the result of a SQL query execution
+        ---
+        get:
+          summary: >-
+            Gets the result of a SQL query execution
+          parameters:
+          - in: query
+            name: q
+            content:
+              application/json:
+                schema:
+                  $ref: '#/components/schemas/sql_lab_get_results_schema'
+          responses:
+            200:
+              description: SQL query execution result
+              content:
+                application/json:
+                  schema:
+                    $ref: '#/components/schemas/QueryExecutionResponseSchema'
+            400:
+              $ref: '#/components/responses/400'

Review Comment:
   missing HTTP 410



##########
tests/integration_tests/sql_lab/api_tests.py:
##########
@@ -0,0 +1,173 @@
+# 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.
+# isort:skip_file
+"""Unit tests for Superset"""
+import datetime
+import json
+import random
+
+import pytest
+import prison
+from sqlalchemy.sql import func
+from unittest import mock
+
+from tests.integration_tests.test_app import app
+from superset import sql_lab
+from superset.common.db_query_status import QueryStatus
+from superset.models.core import Database
+from superset.utils.database import get_example_database, get_main_database
+from superset.utils import core as utils
+from superset.models.sql_lab import Query
+
+from tests.integration_tests.base_tests import SupersetTestCase
+
+QUERIES_FIXTURE_COUNT = 10
+
+
+class TestSqlLabApi(SupersetTestCase):
+    @mock.patch("superset.sqllab.commands.results.results_backend_use_msgpack", False)
+    def test_execute_required_params(self):
+        self.login()
+        client_id = "{}".format(random.getrandbits(64))[:10]
+
+        data = {"client_id": client_id}
+        rv = self.client.post(
+            "/api/v1/sqllab/execute/",
+            json=data,
+        )
+        failed_resp = {
+            "message": {
+                "sql": ["Missing data for required field."],
+                "database_id": ["Missing data for required field."],
+            }
+        }
+        resp_data = json.loads(rv.data.decode("utf-8"))
+        self.assertDictEqual(resp_data, failed_resp)
+        self.assertEqual(rv.status_code, 400)
+
+        data = {"sql": "SELECT 1", "client_id": client_id}
+        rv = self.client.post(
+            "/api/v1/sqllab/execute/",
+            json=data,
+        )
+        failed_resp = {"message": {"database_id": ["Missing data for required field."]}}
+        resp_data = json.loads(rv.data.decode("utf-8"))
+        self.assertDictEqual(resp_data, failed_resp)
+        self.assertEqual(rv.status_code, 400)
+
+        data = {"database_id": 1, "client_id": client_id}
+        rv = self.client.post(
+            "/api/v1/sqllab/execute/",
+            json=data,
+        )
+        failed_resp = {"message": {"sql": ["Missing data for required field."]}}
+        resp_data = json.loads(rv.data.decode("utf-8"))
+        self.assertDictEqual(resp_data, failed_resp)
+        self.assertEqual(rv.status_code, 400)
+
+        from superset import sql_lab as core
+
+        core.results_backend = mock.Mock()
+        core.results_backend.get.return_value = {}
+
+        data = {"sql": "SELECT 1", "database_id": 1, "client_id": client_id}
+        rv = self.client.post(
+            "/api/v1/sqllab/execute/",
+            json=data,
+        )
+        resp_data = json.loads(rv.data.decode("utf-8"))
+        self.assertEqual(resp_data.get("status"), "success")
+        self.assertEqual(rv.status_code, 200)

Review Comment:
   nit: I personally like to split 400 test cases and 200 test cases into separate tests



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] EugeneTorap commented on pull request #22809: chore: migrate /sql_json and /results to apiv1

Posted by "EugeneTorap (via GitHub)" <gi...@apache.org>.
EugeneTorap commented on PR #22809:
URL: https://github.com/apache/superset/pull/22809#issuecomment-1400563411

   Hello @diegomedina248! Thanks so much for this PR! I like what you do.
   I also tried prepare the same PR but you did much more better. I believe we can deprecate all legacy API and move to v1 API this year.
   @dpgaspar @villebro Do you want to review the nice PR?


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] dpgaspar commented on a diff in pull request #22809: chore: migrate /sql_json and /results to apiv1

Posted by "dpgaspar (via GitHub)" <gi...@apache.org>.
dpgaspar commented on code in PR #22809:
URL: https://github.com/apache/superset/pull/22809#discussion_r1089054216


##########
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:
   Here, finishing up a small refactor here: https://github.com/apache/superset/pull/22887
   so planning for a `BaseSupersetApi` then we can add `statsd_metrics` to these endpoints has well



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] dpgaspar commented on a diff in pull request #22809: chore: migrate /sql_json and /results to apiv1

Posted by "dpgaspar (via GitHub)" <gi...@apache.org>.
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] dpgaspar commented on a diff in pull request #22809: chore: migrate /sql_json and /results to apiv1

Posted by "dpgaspar (via GitHub)" <gi...@apache.org>.
dpgaspar commented on code in PR #22809:
URL: https://github.com/apache/superset/pull/22809#discussion_r1086383655


##########
superset/sqllab/api.py:
##########
@@ -0,0 +1,250 @@
+# 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
+
+from flask import request, Response
+from flask_appbuilder.api import expose, protect, rison, safe
+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.views.base import handle_api_exception
+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
+
+    execute_model_schema = ExecutePayloadSchema()
+
+    apispec_parameter_schemas = {
+        "sql_lab_get_results_schema": sql_lab_get_results_schema,
+    }
+    openapi_spec_tag = "SQL Lab"
+    openapi_spec_component_schemas = (
+        ExecutePayloadSchema,
+        QueryExecutionResponseSchema,
+    )
+
+    @expose("/results/")
+    @protect()
+    @safe
+    @statsd_metrics
+    @rison(sql_lab_get_results_schema)
+    @handle_api_exception

Review Comment:
   I've read it, and the `Commands` are raising those. I like the pattern of just raising on the method block, but I actually don't think we need `@handle_api_exception` or even `@safe` anymore, since all exception are caught by `Flask` itself, https://github.com/apache/superset/blob/master/superset/views/base.py#L505
   
   how big of a change on the frontend would be if we change the error response format?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] codecov[bot] commented on pull request #22809: wip: chore: migrate /sql_json and /results to apiv1

Posted by codecov.
codecov[bot] commented on PR #22809:
URL: https://github.com/apache/superset/pull/22809#issuecomment-1398868231

   # [Codecov](https://codecov.io/gh/apache/superset/pull/22809?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) Report
   > Merging [#22809](https://codecov.io/gh/apache/superset/pull/22809?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (8c7ba93) into [master](https://codecov.io/gh/apache/superset/commit/858c6e19a0a474c0ef2940d9745c1d0eb0ebef9a?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (858c6e1) will **decrease** coverage by `10.09%`.
   > The diff coverage is `73.78%`.
   
   ```diff
   @@             Coverage Diff             @@
   ##           master   #22809       +/-   ##
   ===========================================
   - Coverage   65.95%   55.86%   -10.09%     
   ===========================================
     Files        1877     1880        +3     
     Lines       72008    72204      +196     
     Branches     7895     7895               
   ===========================================
   - Hits        47491    40337     -7154     
   - Misses      22489    29839     +7350     
     Partials     2028     2028               
   ```
   
   | Flag | Coverage Δ | |
   |---|---|---|
   | hive | `?` | |
   | mysql | `?` | |
   | postgres | `?` | |
   | presto | `52.61% <73.39%> (+0.11%)` | :arrow_up: |
   | python | `58.03% <73.39%> (-21.08%)` | :arrow_down: |
   | sqlite | `?` | |
   | unit | `51.65% <72.41%> (?)` | |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#carryforward-flags-in-the-pull-request-comment) to find out more.
   
   | [Impacted Files](https://codecov.io/gh/apache/superset/pull/22809?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) | Coverage Δ | |
   |---|---|---|
   | [superset/constants.py](https://codecov.io/gh/apache/superset/pull/22809?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQvY29uc3RhbnRzLnB5) | `100.00% <ø> (ø)` | |
   | [superset/sqllab/commands/execute.py](https://codecov.io/gh/apache/superset/pull/22809?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQvc3FsbGFiL2NvbW1hbmRzL2V4ZWN1dGUucHk=) | `87.93% <ø> (ø)` | |
   | [superset/sqllab/commands/results.py](https://codecov.io/gh/apache/superset/pull/22809?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQvc3FsbGFiL2NvbW1hbmRzL3Jlc3VsdHMucHk=) | `54.34% <54.34%> (ø)` | |
   | [superset/sqllab/api.py](https://codecov.io/gh/apache/superset/pull/22809?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQvc3FsbGFiL2FwaS5weQ==) | `65.90% <65.90%> (ø)` | |
   | [superset/sqllab/execution\_context\_convertor.py](https://codecov.io/gh/apache/superset/pull/22809?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQvc3FsbGFiL2V4ZWN1dGlvbl9jb250ZXh0X2NvbnZlcnRvci5weQ==) | `78.12% <66.66%> (-10.77%)` | :arrow_down: |
   | [superset-frontend/src/SqlLab/actions/sqlLab.js](https://codecov.io/gh/apache/superset/pull/22809?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQtZnJvbnRlbmQvc3JjL1NxbExhYi9hY3Rpb25zL3NxbExhYi5qcw==) | `63.93% <100.00%> (ø)` | |
   | [superset/initialization/\_\_init\_\_.py](https://codecov.io/gh/apache/superset/pull/22809?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQvaW5pdGlhbGl6YXRpb24vX19pbml0X18ucHk=) | `91.85% <100.00%> (+2.02%)` | :arrow_up: |
   | [superset/sqllab/query\_render.py](https://codecov.io/gh/apache/superset/pull/22809?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQvc3FsbGFiL3F1ZXJ5X3JlbmRlci5weQ==) | `88.46% <100.00%> (ø)` | |
   | [superset/sqllab/schemas.py](https://codecov.io/gh/apache/superset/pull/22809?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQvc3FsbGFiL3NjaGVtYXMucHk=) | `100.00% <100.00%> (ø)` | |
   | [superset/sqllab/validators.py](https://codecov.io/gh/apache/superset/pull/22809?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQvc3FsbGFiL3ZhbGlkYXRvcnMucHk=) | `88.88% <100.00%> (ø)` | |
   | ... and [345 more](https://codecov.io/gh/apache/superset/pull/22809?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) | |
   
   :mega: We’re building smart automated test selection to slash your CI/CD build times. [Learn more](https://about.codecov.io/iterative-testing/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation)
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] dpgaspar commented on a diff in pull request #22809: chore: migrate /sql_json and /results to apiv1

Posted by "dpgaspar (via GitHub)" <gi...@apache.org>.
dpgaspar commented on code in PR #22809:
URL: https://github.com/apache/superset/pull/22809#discussion_r1090366669


##########
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:
   ok



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] diegomedina248 commented on a diff in pull request #22809: chore: migrate /sql_json and /results to apiv1

Posted by "diegomedina248 (via GitHub)" <gi...@apache.org>.
diegomedina248 commented on code in PR #22809:
URL: https://github.com/apache/superset/pull/22809#discussion_r1087378368


##########
superset/sqllab/api.py:
##########
@@ -0,0 +1,250 @@
+# 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
+
+from flask import request, Response
+from flask_appbuilder.api import expose, protect, rison, safe
+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.views.base import handle_api_exception
+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
+
+    execute_model_schema = ExecutePayloadSchema()
+
+    apispec_parameter_schemas = {
+        "sql_lab_get_results_schema": sql_lab_get_results_schema,
+    }
+    openapi_spec_tag = "SQL Lab"
+    openapi_spec_component_schemas = (
+        ExecutePayloadSchema,
+        QueryExecutionResponseSchema,
+    )
+
+    @expose("/results/")
+    @protect()
+    @safe
+    @statsd_metrics
+    @rison(sql_lab_get_results_schema)
+    @handle_api_exception

Review Comment:
   right, good call! and no change was needed, at least in these two methods



##########
superset/sqllab/api.py:
##########
@@ -0,0 +1,250 @@
+# 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
+
+from flask import request, Response
+from flask_appbuilder.api import expose, protect, rison, safe
+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.views.base import handle_api_exception
+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
+
+    execute_model_schema = ExecutePayloadSchema()
+
+    apispec_parameter_schemas = {
+        "sql_lab_get_results_schema": sql_lab_get_results_schema,
+    }
+    openapi_spec_tag = "SQL Lab"
+    openapi_spec_component_schemas = (
+        ExecutePayloadSchema,
+        QueryExecutionResponseSchema,
+    )
+
+    @expose("/results/")
+    @protect()
+    @safe
+    @statsd_metrics
+    @rison(sql_lab_get_results_schema)
+    @handle_api_exception

Review Comment:
   right, good call! and no change was needed, at least in these two api endpoints



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] diegomedina248 commented on a diff in pull request #22809: chore: migrate /sql_json and /results to apiv1

Posted by "diegomedina248 (via GitHub)" <gi...@apache.org>.
diegomedina248 commented on code in PR #22809:
URL: https://github.com/apache/superset/pull/22809#discussion_r1089300717


##########
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:
   Yeah, these are all tied and intertwined with the entire sql lab tool (specially for stuff that can run in the background, since it can be read differently by non-deprecated api).
   We need to migrate all the related endpoints before making those changes.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org