aminghadersohi commented on code in PR #40361:
URL: https://github.com/apache/superset/pull/40361#discussion_r3328079499


##########
superset/commands/query/create.py:
##########
@@ -0,0 +1,75 @@
+# 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 functools import partial
+from typing import Any
+
+from flask import g
+from flask_appbuilder.models.sqla import Model
+from marshmallow import ValidationError
+
+from superset.commands.base import BaseCommand, CreateMixin
+from superset.commands.query.exceptions import (
+    SavedQueryCreateFailedError,
+    SavedQueryInvalidError,
+)
+from superset.daos.query import SavedQueryDAO
+from superset.utils.decorators import on_error, transaction
+
+logger = logging.getLogger(__name__)
+
+
+class CreateSavedQueryCommand(CreateMixin, BaseCommand):
+    def __init__(self, data: dict[str, Any]):
+        self._properties = data.copy()
+
+    @transaction(on_error=partial(on_error, 
reraise=SavedQueryCreateFailedError))
+    def run(self) -> Model:
+        self.validate()
+        self._properties["user_id"] = g.user.id
+        saved_query = SavedQueryDAO.create(attributes=self._properties)
+        return saved_query
+
+    def validate(self) -> None:
+        from superset.extensions import db, security_manager
+        from superset.models.core import Database
+
+        exceptions: list[ValidationError] = []
+
+        db_id = self._properties.get("db_id")
+        if not db_id:
+            exceptions.append(ValidationError("db_id is required", 
field_name="db_id"))
+            raise SavedQueryInvalidError(exceptions=exceptions)

Review Comment:
   Fixed — `CreateSavedQueryCommand.validate()` uses an explicit `if db_id is 
None:` check, not a falsy test.



##########
superset/mcp_service/saved_query/tool/create_saved_query.py:
##########
@@ -0,0 +1,126 @@
+# 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
+
+from fastmcp import Context
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset.extensions import event_logger
+from superset.mcp_service.saved_query.schemas import (
+    CreateSavedQueryRequest,
+    CreateSavedQueryResponse,
+)
+
+logger = logging.getLogger(__name__)
+
+
+@tool(
+    tags=["mutate"],
+    class_permission_name="SavedQuery",
+    method_permission_name="write",
+    annotations=ToolAnnotations(
+        title="Create saved query",
+        readOnlyHint=False,
+        destructiveHint=False,
+    ),
+)
+async def create_saved_query(
+    request: CreateSavedQueryRequest, ctx: Context
+) -> CreateSavedQueryResponse:
+    """Save a SQL query to the Saved Queries list so it can be reloaded and 
shared.
+
+    Creates a persistent SavedQuery that appears in the Saved Queries page
+    and can be opened in SQL Lab via the returned URL.
+
+    Workflow:
+    1. Call execute_sql to verify the query returns expected results
+    2. Call this tool with a label and the SQL to persist it
+    3. Use the returned ``url`` to open the saved query in SQL Lab
+    """
+    await ctx.info(
+        "Creating saved query: db_id=%s, label=%r" % (request.db_id, 
request.label)
+    )
+
+    try:
+        from superset.commands.query.create import CreateSavedQueryCommand
+        from superset.commands.query.exceptions import (
+            SavedQueryCreateFailedError,
+            SavedQueryInvalidError,
+        )
+        from superset.mcp_service.utils.url_utils import get_superset_base_url
+
+        properties: dict[str, Any] = {
+            "db_id": request.db_id,
+            "label": request.label,
+            "sql": request.sql,
+        }

Review Comment:
   Fixed — `catalog` has been added to `CreateSavedQueryRequest` and 
`CreateSavedQueryResponse`. The tool now passes `catalog` through to 
`CreateSavedQueryCommand` when provided, and surfaces `getattr(saved_query, 
'catalog', None)` in the response.



##########
superset/mcp_service/saved_query/tool/update_saved_query.py:
##########
@@ -0,0 +1,142 @@
+# 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
+
+from fastmcp import Context
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset.extensions import event_logger
+from superset.mcp_service.saved_query.schemas import (
+    UpdateSavedQueryRequest,
+    UpdateSavedQueryResponse,
+)
+
+logger = logging.getLogger(__name__)
+
+_LOGGABLE_FIELDS = (
+    "label",
+    "sql",
+    "db_id",
+    "schema",
+    "description",
+    "template_parameters",
+)
+
+
+def _build_update_properties(request: "UpdateSavedQueryRequest") -> dict[str, 
Any]:
+    """Return only the fields the caller explicitly provided."""
+    fields = {
+        "label": request.label,
+        "sql": request.sql,
+        "db_id": request.db_id,
+        "schema": request.schema,
+        "description": request.description,
+        "template_parameters": request.template_parameters,
+    }

Review Comment:
   Fixed — `catalog` has been added to `UpdateSavedQueryRequest`, 
`UpdateSavedQueryResponse`, `_LOGGABLE_FIELDS`, and 
`_build_update_properties()`. Callers can now update the catalog field 
independently or alongside `db_id`.



##########
superset/mcp_service/saved_query/tool/update_saved_query.py:
##########
@@ -0,0 +1,142 @@
+# 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
+
+from fastmcp import Context
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset.extensions import event_logger
+from superset.mcp_service.saved_query.schemas import (
+    UpdateSavedQueryRequest,
+    UpdateSavedQueryResponse,
+)
+
+logger = logging.getLogger(__name__)
+
+_LOGGABLE_FIELDS = (
+    "label",
+    "sql",
+    "db_id",
+    "schema",
+    "description",
+    "template_parameters",
+)
+
+
+def _build_update_properties(request: "UpdateSavedQueryRequest") -> dict[str, 
Any]:
+    """Return only the fields the caller explicitly provided."""
+    fields = {
+        "label": request.label,
+        "sql": request.sql,
+        "db_id": request.db_id,
+        "schema": request.schema,
+        "description": request.description,
+        "template_parameters": request.template_parameters,
+    }
+    return {k: v for k, v in fields.items() if v is not None}
+
+
+@tool(
+    tags=["mutate"],
+    class_permission_name="SavedQuery",
+    method_permission_name="write",
+    annotations=ToolAnnotations(
+        title="Update saved query",
+        readOnlyHint=False,
+        destructiveHint=True,
+    ),
+)
+async def update_saved_query(
+    request: UpdateSavedQueryRequest, ctx: Context
+) -> UpdateSavedQueryResponse:
+    """Update an existing saved query's label, SQL, database, schema, or 
description.
+
+    All fields except ``id`` are optional — only provided fields are changed.
+    The query must already exist and the caller must have write access to
+    the SavedQuery resource.
+
+    Example: rename only
+    ```json
+    {"id": 42, "label": "Monthly Revenue"}
+    ```
+
+    Example: update SQL and description
+    ```json
+    {"id": 42, "sql": "SELECT * FROM orders LIMIT 100", "description": "All 
orders"}
+    ```
+    """
+    changed = [f for f in _LOGGABLE_FIELDS if getattr(request, f, None) is not 
None]
+    await ctx.info("Updating saved query: id=%s, fields=%s" % (request.id, 
changed))
+
+    try:
+        from superset.commands.query.exceptions import (
+            SavedQueryInvalidError,
+            SavedQueryNotFoundError,
+            SavedQueryUpdateFailedError,
+        )
+        from superset.commands.query.update import UpdateSavedQueryCommand
+        from superset.mcp_service.utils.url_utils import get_superset_base_url
+
+        properties = _build_update_properties(request)
+
+        with event_logger.log_context(action="mcp.update_saved_query.update"):
+            saved_query = UpdateSavedQueryCommand(request.id, properties).run()

Review Comment:
   Fixed — `update_saved_query` validates that at least one mutable field is 
present before issuing any DB call. Requests with only `id` return a structured 
error: `UpdateSavedQueryResponse(id=None, error='No fields to update. Provide 
at least one of: ...')`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to