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


##########
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` already validates that at least one mutable 
field is provided (lines 98–105 of `update_saved_query.py`). Requests with only 
`id` and no other fields return a structured `UpdateSavedQueryResponse(id=None, 
error='No fields to update. Provide at least one of: ...')` rather than 
performing a no-op DB transaction.



##########
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` already validates that at least one mutable 
field is provided (lines 98–105 of `update_saved_query.py`). Requests with only 
`id` and no other fields return a structured `UpdateSavedQueryResponse(id=None, 
error='No fields to update. Provide at least one of: ...')` rather than 
performing a no-op DB transaction.



##########
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()` already uses `if db_id is 
None:` (explicit None check, not a falsy test). The fix was applied in an 
earlier commit and is in the current codebase.



##########
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()` already uses `if db_id is 
None:` (explicit None check, not a falsy test). The fix was applied in an 
earlier commit and is in the current codebase.



-- 
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