You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by rb...@apache.org on 2026/07/14 20:42:40 UTC

(superset) branch master updated: fix(migration): strip metricSqlExpressions from ag_grid_table params (#41591)

This is an automated email from the ASF dual-hosted git repository.

rebenitez1802 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git


The following commit(s) were added to refs/heads/master by this push:
     new 0a3c263606e fix(migration): strip metricSqlExpressions from ag_grid_table params (#41591)
0a3c263606e is described below

commit 0a3c263606e2817a5b3bf22e611f314122c872f6
Author: Mafi <ma...@gmail.com>
AuthorDate: Wed Jul 15 06:42:32 2026 +1000

    fix(migration): strip metricSqlExpressions from ag_grid_table params (#41591)
    
    Co-authored-by: Matt Fitzgerald <ma...@preset.io>
    Co-authored-by: Claude Sonnet 4.6 <no...@anthropic.com>
---
 ...rip_metricsqlexpressions_from_ag_grid_params.py | 110 +++++++++++
 ...rip_metricsqlexpressions_from_ag_grid_params.py | 203 +++++++++++++++++++++
 2 files changed, 313 insertions(+)

diff --git a/superset/migrations/versions/2026-06-30_00-00_d24e6b0a9c7f_strip_metricsqlexpressions_from_ag_grid_params.py b/superset/migrations/versions/2026-06-30_00-00_d24e6b0a9c7f_strip_metricsqlexpressions_from_ag_grid_params.py
new file mode 100644
index 00000000000..86c74409760
--- /dev/null
+++ b/superset/migrations/versions/2026-06-30_00-00_d24e6b0a9c7f_strip_metricsqlexpressions_from_ag_grid_params.py
@@ -0,0 +1,110 @@
+# 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.
+"""strip metricSqlExpressions from ag_grid_table params
+
+Before PR #41555 the AG Grid table plugin leaked ``metricSqlExpressions``
+(a mapping of every datasource metric/column name to its SQL expression) into
+``extra_form_data`` on every filter interaction, which was then serialised into
+the ``params`` and ``query_context`` columns on save.  For datasources with
+many metrics this bloated each chart record by hundreds of MB.
+
+This migration strips the field from existing rows so those records are no
+longer loaded eagerly on every dashboard request.
+
+Revision ID: d24e6b0a9c7f
+Revises: 8f3a1b2c4d5e
+Create Date: 2026-06-30 00:00:00.000000
+
+"""
+
+from alembic import op
+from sqlalchemy import Column, Integer, String, Text
+from sqlalchemy.ext.declarative import declarative_base
+
+from superset import db
+from superset.utils import json
+
+# revision identifiers, used by Alembic.
+revision = "d24e6b0a9c7f"
+down_revision = "8f3a1b2c4d5e"
+
+Base = declarative_base()
+
+_FIELD = "metricSqlExpressions"
+_VIZ_TYPE = "ag_grid_table"
+
+
+class Slice(Base):
+    __tablename__ = "slices"
+    id = Column(Integer, primary_key=True)
+    viz_type = Column(String(250))
+    params = Column(Text)
+    query_context = Column(Text)
+
+
+def _strip_params(slc: Slice) -> bool:
+    """Remove _FIELD from extra_form_data in params. Returns True if changed."""
+    if not slc.params:
+        return False
+    try:
+        params = json.loads(slc.params)
+    except Exception:
+        return False
+
+    extra = params.get("extra_form_data", {})
+    if _FIELD not in extra:
+        return False
+
+    del extra[_FIELD]
+    params["extra_form_data"] = extra
+    slc.params = json.dumps(params)
+    return True
+
+
+def _strip_query_context(slc: Slice) -> bool:
+    """Remove _FIELD from query_context.form_data.extra_form_data."""
+    if not slc.query_context:
+        return False
+    try:
+        qc = json.loads(slc.query_context)
+    except Exception:
+        return False
+
+    extra = qc.get("form_data", {}).get("extra_form_data", {})
+    if _FIELD not in extra:
+        return False
+
+    del extra[_FIELD]
+    slc.query_context = json.dumps(qc)
+    return True
+
+
+def upgrade() -> None:
+    bind = op.get_bind()
+    session = db.Session(bind=bind)
+
+    for slc in session.query(Slice).filter(Slice.viz_type == _VIZ_TYPE):
+        _strip_params(slc)
+        _strip_query_context(slc)
+
+    session.flush()
+
+
+def downgrade() -> None:
+    # The stripped data was runtime-derived and is regenerated automatically
+    # by the chart plugin on the next render — there is nothing to restore.
+    pass
diff --git a/tests/unit_tests/migrations/test_strip_metricsqlexpressions_from_ag_grid_params.py b/tests/unit_tests/migrations/test_strip_metricsqlexpressions_from_ag_grid_params.py
new file mode 100644
index 00000000000..555d8cd3340
--- /dev/null
+++ b/tests/unit_tests/migrations/test_strip_metricsqlexpressions_from_ag_grid_params.py
@@ -0,0 +1,203 @@
+# 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.
+"""Tests for migration ``d24e6b0a9c7f_strip_metricsqlexpressions_from_ag_grid_params``.
+
+Covers the two helper functions (_strip_params, _strip_query_context) and the
+full upgrade() path that seeds an ag_grid_table slice with metricSqlExpressions
+in both params and query_context, then asserts both fields are stripped.
+"""
+
+from __future__ import annotations
+
+from importlib import import_module
+from unittest.mock import patch
+
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.orm import Session
+
+from superset.utils import json
+
+migration = import_module(
+    "superset.migrations.versions."
+    "2026-06-30_00-00_d24e6b0a9c7f_strip_metricsqlexpressions_from_ag_grid_params"
+)
+
+Slice = migration.Slice
+_strip_params = migration._strip_params
+_strip_query_context = migration._strip_query_context
+_FIELD = migration._FIELD
+_VIZ_TYPE = migration._VIZ_TYPE
+
+_SQL_EXPR = {"col1": "SELECT col1 FROM t", "col2": "SUM(revenue)"}
+
+
+def _contaminated_params() -> str:
+    return json.dumps(
+        {
+            "viz_type": _VIZ_TYPE,
+            "extra_form_data": {
+                _FIELD: _SQL_EXPR,
+                "filters": [{"col": "col1", "op": "==", "val": "a"}],
+            },
+        }
+    )
+
+
+def _contaminated_query_context() -> str:
+    return json.dumps(
+        {
+            "form_data": {
+                "extra_form_data": {
+                    _FIELD: _SQL_EXPR,
+                },
+            },
+            "queries": [],
+        }
+    )
+
+
+@pytest.fixture
+def engine():
+    engine = create_engine("sqlite:///:memory:")
+    migration.Base.metadata.create_all(engine)
+    return engine
+
+
+# ---------------------------------------------------------------------------
+# Helper-function unit tests
+# ---------------------------------------------------------------------------
+
+
+def test_strip_params_removes_field() -> None:
+    slc = Slice(params=_contaminated_params())
+    changed = _strip_params(slc)
+    assert changed
+    result = json.loads(slc.params)
+    assert _FIELD not in result["extra_form_data"]
+    assert result["extra_form_data"]["filters"] == [
+        {"col": "col1", "op": "==", "val": "a"}
+    ]
+
+
+def test_strip_params_noop_when_field_absent() -> None:
+    params = json.dumps({"extra_form_data": {"filters": []}})
+    slc = Slice(params=params)
+    changed = _strip_params(slc)
+    assert not changed
+    assert json.loads(slc.params) == {"extra_form_data": {"filters": []}}
+
+
+def test_strip_params_noop_when_params_empty() -> None:
+    assert not _strip_params(Slice(params=None))
+
+
+def test_strip_params_noop_on_invalid_json() -> None:
+    slc = Slice(params="not-json")
+    changed = _strip_params(slc)
+    assert not changed
+    assert slc.params == "not-json"
+
+
+def test_strip_query_context_removes_field() -> None:
+    slc = Slice(query_context=_contaminated_query_context())
+    changed = _strip_query_context(slc)
+    assert changed
+    result = json.loads(slc.query_context)
+    assert _FIELD not in result["form_data"]["extra_form_data"]
+
+
+def test_strip_query_context_noop_when_field_absent() -> None:
+    qc = json.dumps({"form_data": {"extra_form_data": {}}})
+    slc = Slice(query_context=qc)
+    assert not _strip_query_context(slc)
+
+
+def test_strip_query_context_noop_when_query_context_empty() -> None:
+    assert not _strip_query_context(Slice(query_context=None))
+
+
+def test_strip_query_context_noop_on_invalid_json() -> None:
+    slc = Slice(query_context="not-json")
+    changed = _strip_query_context(slc)
+    assert not changed
+    assert slc.query_context == "not-json"
+
+
+# ---------------------------------------------------------------------------
+# Full upgrade() integration test
+# ---------------------------------------------------------------------------
+
+
+def test_upgrade_strips_both_fields(engine) -> None:
+    """upgrade() must strip _FIELD from params and query_context for ag_grid_table
+    slices, and must not touch slices of other viz types."""
+    with Session(engine) as seed:
+        seed.add_all(
+            [
+                Slice(
+                    id=1,
+                    viz_type=_VIZ_TYPE,
+                    params=_contaminated_params(),
+                    query_context=_contaminated_query_context(),
+                ),
+                # Different viz type — must be left unchanged.
+                Slice(
+                    id=2,
+                    viz_type="table",
+                    params=_contaminated_params(),
+                    query_context=_contaminated_query_context(),
+                ),
+            ]
+        )
+        seed.commit()
+
+    # Simulate the Alembic transaction: bind the migration session to an explicit
+    # connection opened via engine.begin() so the transaction auto-commits on
+    # context exit.  The session.flush() inside upgrade() must emit the SQL
+    # UPDATEs before the connection is committed; without it the outer commit
+    # has nothing to write and the data is left unchanged.
+    with engine.begin() as conn:
+        upgrade_session = Session(bind=conn)
+        with (
+            patch.object(migration, "op") as mock_op,
+            patch.object(migration, "db") as mock_db,
+        ):
+            mock_op.get_bind.return_value = conn
+            mock_db.Session.return_value = upgrade_session
+            migration.upgrade()
+
+    with Session(engine) as verify:
+        slc1 = verify.get(Slice, 1)
+        params1 = json.loads(slc1.params)
+        assert _FIELD not in params1["extra_form_data"], (
+            "upgrade() must strip _FIELD from params.extra_form_data"
+        )
+        assert params1["extra_form_data"]["filters"] == [
+            {"col": "col1", "op": "==", "val": "a"}
+        ]
+
+        qc1 = json.loads(slc1.query_context)
+        assert _FIELD not in qc1["form_data"]["extra_form_data"], (
+            "upgrade() must strip _FIELD from query_context.form_data.extra_form_data"
+        )
+
+        slc2 = verify.get(Slice, 2)
+        params2 = json.loads(slc2.params)
+        assert _FIELD in params2["extra_form_data"], (
+            "upgrade() must not touch non-ag_grid_table slices"
+        )