codeant-ai-for-open-source[bot] commented on code in PR #40128: URL: https://github.com/apache/superset/pull/40128#discussion_r3397909336
########## tests/unit_tests/commands/dashboard/restore_test.py: ########## @@ -0,0 +1,201 @@ +# 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. +"""Unit tests for RestoreDashboardCommand.""" + +from __future__ import annotations + +from datetime import datetime, timezone +from unittest.mock import MagicMock, patch + +import pytest + + +def test_restore_dashboard_not_found_raises(app_context: None) -> None: + """RestoreDashboardCommand raises DashboardNotFoundError for missing dashboard.""" + from superset.commands.dashboard.exceptions import DashboardNotFoundError + from superset.commands.dashboard.restore import RestoreDashboardCommand + + with patch("superset.daos.dashboard.DashboardDAO.find_by_id", return_value=None): + cmd = RestoreDashboardCommand("999") + with pytest.raises(DashboardNotFoundError): + cmd.run() + + +def test_restore_active_dashboard_raises_not_found(app_context: None) -> None: + """RestoreDashboardCommand raises DashboardNotFoundError for non-deleted dashboard.""" # noqa: E501 + from superset.commands.dashboard.exceptions import DashboardNotFoundError + from superset.commands.dashboard.restore import RestoreDashboardCommand + + dashboard = MagicMock() + dashboard.deleted_at = None # not soft-deleted + + with patch( + "superset.daos.dashboard.DashboardDAO.find_by_id", return_value=dashboard + ): + cmd = RestoreDashboardCommand("1") + with pytest.raises(DashboardNotFoundError): + cmd.run() + + +def test_restore_dashboard_forbidden_raises(app_context: None) -> None: + """RestoreDashboardCommand raises DashboardForbiddenError on permission check.""" + from superset.commands.dashboard.exceptions import DashboardForbiddenError + from superset.commands.dashboard.restore import RestoreDashboardCommand + from superset.exceptions import SupersetSecurityException + + dashboard = MagicMock() + dashboard.deleted_at = datetime(2026, 1, 1, tzinfo=timezone.utc) + + def raise_security(*args: object, **kwargs: object) -> None: + raise SupersetSecurityException(MagicMock()) Review Comment: **Suggestion:** Add an inline docstring to the newly introduced helper function so it complies with the rule that all new functions must be documented. [custom_rule] **Severity Level:** Minor ⚠️ <details> <summary><b>Why it matters? 🤔 </b></summary> This is a newly introduced Python function and it does not have a docstring. The provided rule requires all new functions and classes to be documented inline, so this is a real violation. </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=d5abf25804df424799d866ec3a917c65&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=d5abf25804df424799d866ec3a917c65&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** tests/unit_tests/commands/dashboard/restore_test.py **Line:** 63:64 **Comment:** *Custom Rule: Add an inline docstring to the newly introduced helper function so it complies with the rule that all new functions must be documented. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=ff3a8be5a0461d76f4044c92c32f9691634294e92998f02900fa6bf979c724fe&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=ff3a8be5a0461d76f4044c92c32f9691634294e92998f02900fa6bf979c724fe&reaction=dislike'>👎</a> ########## tests/unit_tests/migrations/test_add_deleted_at_to_dashboards.py: ########## @@ -0,0 +1,241 @@ +# 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 ``9e1f3b8c4d2a_add_deleted_at_to_dashboards``. + +Runs the migration's ``upgrade()`` and ``downgrade()`` against an +in-memory SQLite engine with a real Alembic ``Operations`` context. + +The migration has two responsibilities: + +1. Add ``deleted_at`` column + ``ix_dashboards_deleted_at`` index — the + shared soft-delete schema. +2. Swap the legacy full unique constraint on ``slug`` for a partial + index (Postgres) or functional index (MySQL 8.0.13+). On SQLite + and older MySQL the slug-constraint swap is a documented no-op + (the original full constraint stays in place). + +The tests pin both responsibilities. The slug-swap path is exercised +only on the no-op branch (the SQLite engine the unit tests run +against); the Postgres / MySQL functional-index paths are covered by +the integration tests against those backends. +""" + +from __future__ import annotations + +from datetime import datetime, timezone +from importlib import import_module + +import pytest +from alembic.migration import MigrationContext +from alembic.operations import Operations +from sqlalchemy import ( + Column, + create_engine, + Index, + insert, + inspect, + Integer, + MetaData, + select, + String, + Table, +) +from sqlalchemy.engine import Engine + +migration = import_module( + "superset.migrations.versions." + "2026-05-08_12-05_9e1f3b8c4d2a_add_deleted_at_to_dashboards" +) + +TABLE_NAME = migration.TABLE_NAME # "dashboards" +DELETED_AT_INDEX_NAME = migration.DELETED_AT_INDEX_NAME +LEGACY_SLUG_INDEX_NAME = migration.LEGACY_SLUG_INDEX_NAME + + [email protected] +def engine() -> Engine: + """In-memory SQLite seeded with a minimal pre-migration ``dashboards`` table. + + The real ``dashboards`` table has many columns; the migration only + touches ``deleted_at``, its index, and the legacy slug constraint, + so only those columns need to exist. The legacy unique constraint + on ``slug`` is included so SQLite's no-op branch can be asserted + against the post-migration state. + """ + engine = create_engine("sqlite:///:memory:") + md = MetaData() + table = Table( + TABLE_NAME, + md, + Column("id", Integer, primary_key=True), + Column("dashboard_title", String(500)), + Column("slug", String(255)), + ) + # Production seeds the legacy slug uniqueness as a named UNIQUE INDEX, + # not a column-level UNIQUE constraint. Mirror that here so ``inspect() + # .get_indexes()`` reports it — column-level UNIQUE on SQLite is not + # surfaced by the indexes inspector. + Index(LEGACY_SLUG_INDEX_NAME, table.c.slug, unique=True) + md.create_all(engine) + return engine + + +def _columns(engine: Engine) -> set[str]: + return {col["name"] for col in inspect(engine).get_columns(TABLE_NAME)} Review Comment: **Suggestion:** Add a short docstring to this helper function describing that it returns the set of column names for the dashboards table. [custom_rule] **Severity Level:** Minor ⚠️ <details> <summary><b>Why it matters? 🤔 </b></summary> The function is newly added and has no docstring. This matches the custom rule requiring newly added Python functions to be documented inline. </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=dad5d8c144554d89b44219abbbb5a1ea&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=dad5d8c144554d89b44219abbbb5a1ea&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** tests/unit_tests/migrations/test_add_deleted_at_to_dashboards.py **Line:** 97:98 **Comment:** *Custom Rule: Add a short docstring to this helper function describing that it returns the set of column names for the dashboards table. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=9c00a54223e310477de03b001a1c75fb00dffbaa04ac63b5dd22c0ba0bf8a24a&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=9c00a54223e310477de03b001a1c75fb00dffbaa04ac63b5dd22c0ba0bf8a24a&reaction=dislike'>👎</a> ########## tests/unit_tests/migrations/test_add_deleted_at_to_dashboards.py: ########## @@ -0,0 +1,241 @@ +# 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 ``9e1f3b8c4d2a_add_deleted_at_to_dashboards``. + +Runs the migration's ``upgrade()`` and ``downgrade()`` against an +in-memory SQLite engine with a real Alembic ``Operations`` context. + +The migration has two responsibilities: + +1. Add ``deleted_at`` column + ``ix_dashboards_deleted_at`` index — the + shared soft-delete schema. +2. Swap the legacy full unique constraint on ``slug`` for a partial + index (Postgres) or functional index (MySQL 8.0.13+). On SQLite + and older MySQL the slug-constraint swap is a documented no-op + (the original full constraint stays in place). + +The tests pin both responsibilities. The slug-swap path is exercised +only on the no-op branch (the SQLite engine the unit tests run +against); the Postgres / MySQL functional-index paths are covered by +the integration tests against those backends. +""" + +from __future__ import annotations + +from datetime import datetime, timezone +from importlib import import_module + +import pytest +from alembic.migration import MigrationContext +from alembic.operations import Operations +from sqlalchemy import ( + Column, + create_engine, + Index, + insert, + inspect, + Integer, + MetaData, + select, + String, + Table, +) +from sqlalchemy.engine import Engine + +migration = import_module( + "superset.migrations.versions." + "2026-05-08_12-05_9e1f3b8c4d2a_add_deleted_at_to_dashboards" +) + +TABLE_NAME = migration.TABLE_NAME # "dashboards" +DELETED_AT_INDEX_NAME = migration.DELETED_AT_INDEX_NAME +LEGACY_SLUG_INDEX_NAME = migration.LEGACY_SLUG_INDEX_NAME + + [email protected] +def engine() -> Engine: + """In-memory SQLite seeded with a minimal pre-migration ``dashboards`` table. + + The real ``dashboards`` table has many columns; the migration only + touches ``deleted_at``, its index, and the legacy slug constraint, + so only those columns need to exist. The legacy unique constraint + on ``slug`` is included so SQLite's no-op branch can be asserted + against the post-migration state. + """ + engine = create_engine("sqlite:///:memory:") + md = MetaData() + table = Table( + TABLE_NAME, + md, + Column("id", Integer, primary_key=True), + Column("dashboard_title", String(500)), + Column("slug", String(255)), + ) + # Production seeds the legacy slug uniqueness as a named UNIQUE INDEX, + # not a column-level UNIQUE constraint. Mirror that here so ``inspect() + # .get_indexes()`` reports it — column-level UNIQUE on SQLite is not + # surfaced by the indexes inspector. + Index(LEGACY_SLUG_INDEX_NAME, table.c.slug, unique=True) + md.create_all(engine) + return engine + + +def _columns(engine: Engine) -> set[str]: + return {col["name"] for col in inspect(engine).get_columns(TABLE_NAME)} + + +def _indexes(engine: Engine) -> set[str]: + return {ix["name"] for ix in inspect(engine).get_indexes(TABLE_NAME)} Review Comment: **Suggestion:** Add a brief docstring to this helper function clarifying that it returns the set of index names for the dashboards table. [custom_rule] **Severity Level:** Minor ⚠️ <details> <summary><b>Why it matters? 🤔 </b></summary> The helper is newly added and lacks a docstring, which violates the rule that new Python functions should be documented inline. </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=63552ae2f3c840828e378ad4652ac095&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=63552ae2f3c840828e378ad4652ac095&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** tests/unit_tests/migrations/test_add_deleted_at_to_dashboards.py **Line:** 101:102 **Comment:** *Custom Rule: Add a brief docstring to this helper function clarifying that it returns the set of index names for the dashboards table. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=617a4ae9afc0acda5f43ea9c945cfe3d982e53af9866d28943de223fa9986dd0&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=617a4ae9afc0acda5f43ea9c945cfe3d982e53af9866d28943de223fa9986dd0&reaction=dislike'>👎</a> ########## tests/unit_tests/migrations/test_add_deleted_at_to_dashboards.py: ########## @@ -0,0 +1,241 @@ +# 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 ``9e1f3b8c4d2a_add_deleted_at_to_dashboards``. + +Runs the migration's ``upgrade()`` and ``downgrade()`` against an +in-memory SQLite engine with a real Alembic ``Operations`` context. + +The migration has two responsibilities: + +1. Add ``deleted_at`` column + ``ix_dashboards_deleted_at`` index — the + shared soft-delete schema. +2. Swap the legacy full unique constraint on ``slug`` for a partial + index (Postgres) or functional index (MySQL 8.0.13+). On SQLite + and older MySQL the slug-constraint swap is a documented no-op + (the original full constraint stays in place). + +The tests pin both responsibilities. The slug-swap path is exercised +only on the no-op branch (the SQLite engine the unit tests run +against); the Postgres / MySQL functional-index paths are covered by +the integration tests against those backends. +""" + +from __future__ import annotations + +from datetime import datetime, timezone +from importlib import import_module + +import pytest +from alembic.migration import MigrationContext +from alembic.operations import Operations +from sqlalchemy import ( + Column, + create_engine, + Index, + insert, + inspect, + Integer, + MetaData, + select, + String, + Table, +) +from sqlalchemy.engine import Engine + +migration = import_module( + "superset.migrations.versions." + "2026-05-08_12-05_9e1f3b8c4d2a_add_deleted_at_to_dashboards" +) + +TABLE_NAME = migration.TABLE_NAME # "dashboards" +DELETED_AT_INDEX_NAME = migration.DELETED_AT_INDEX_NAME +LEGACY_SLUG_INDEX_NAME = migration.LEGACY_SLUG_INDEX_NAME + + [email protected] +def engine() -> Engine: + """In-memory SQLite seeded with a minimal pre-migration ``dashboards`` table. + + The real ``dashboards`` table has many columns; the migration only + touches ``deleted_at``, its index, and the legacy slug constraint, + so only those columns need to exist. The legacy unique constraint + on ``slug`` is included so SQLite's no-op branch can be asserted + against the post-migration state. + """ + engine = create_engine("sqlite:///:memory:") + md = MetaData() + table = Table( + TABLE_NAME, + md, + Column("id", Integer, primary_key=True), + Column("dashboard_title", String(500)), + Column("slug", String(255)), + ) + # Production seeds the legacy slug uniqueness as a named UNIQUE INDEX, + # not a column-level UNIQUE constraint. Mirror that here so ``inspect() + # .get_indexes()`` reports it — column-level UNIQUE on SQLite is not + # surfaced by the indexes inspector. + Index(LEGACY_SLUG_INDEX_NAME, table.c.slug, unique=True) + md.create_all(engine) + return engine + + +def _columns(engine: Engine) -> set[str]: + return {col["name"] for col in inspect(engine).get_columns(TABLE_NAME)} + + +def _indexes(engine: Engine) -> set[str]: + return {ix["name"] for ix in inspect(engine).get_indexes(TABLE_NAME)} + + +def test_upgrade_adds_deleted_at_column_and_index(engine: Engine) -> None: + with engine.connect() as conn: + ctx = MigrationContext.configure(conn) + with Operations.context(ctx): + migration.upgrade() + + assert "deleted_at" in _columns(engine), "upgrade() must add the deleted_at column" + assert DELETED_AT_INDEX_NAME in _indexes(engine), ( + "upgrade() must create the supporting index on deleted_at" + ) + + +def test_downgrade_drops_deleted_at_column_and_index(engine: Engine) -> None: + with engine.connect() as conn: + ctx = MigrationContext.configure(conn) + with Operations.context(ctx): + migration.upgrade() + migration.downgrade() + + assert "deleted_at" not in _columns(engine), ( + "downgrade() must drop the deleted_at column" + ) + assert DELETED_AT_INDEX_NAME not in _indexes(engine), ( + "downgrade() must drop the supporting index" + ) Review Comment: **Suggestion:** Add a docstring to this test function to explain the downgrade contract being asserted. [custom_rule] **Severity Level:** Minor ⚠️ <details> <summary><b>Why it matters? 🤔 </b></summary> This is a newly added Python function without a docstring, which directly matches the rule requiring inline documentation for new functions. </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=4a87e4e3f0c1498f8c2d9f07457a548e&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=4a87e4e3f0c1498f8c2d9f07457a548e&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** tests/unit_tests/migrations/test_add_deleted_at_to_dashboards.py **Line:** 117:129 **Comment:** *Custom Rule: Add a docstring to this test function to explain the downgrade contract being asserted. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=96d1e2fb1cb47623e2cba76b90d5382224c6c3cd453efb305984fc4e49e5e9ef&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=96d1e2fb1cb47623e2cba76b90d5382224c6c3cd453efb305984fc4e49e5e9ef&reaction=dislike'>👎</a> ########## tests/unit_tests/migrations/test_add_deleted_at_to_dashboards.py: ########## @@ -0,0 +1,241 @@ +# 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 ``9e1f3b8c4d2a_add_deleted_at_to_dashboards``. + +Runs the migration's ``upgrade()`` and ``downgrade()`` against an +in-memory SQLite engine with a real Alembic ``Operations`` context. + +The migration has two responsibilities: + +1. Add ``deleted_at`` column + ``ix_dashboards_deleted_at`` index — the + shared soft-delete schema. +2. Swap the legacy full unique constraint on ``slug`` for a partial + index (Postgres) or functional index (MySQL 8.0.13+). On SQLite + and older MySQL the slug-constraint swap is a documented no-op + (the original full constraint stays in place). + +The tests pin both responsibilities. The slug-swap path is exercised +only on the no-op branch (the SQLite engine the unit tests run +against); the Postgres / MySQL functional-index paths are covered by +the integration tests against those backends. +""" + +from __future__ import annotations + +from datetime import datetime, timezone +from importlib import import_module + +import pytest +from alembic.migration import MigrationContext +from alembic.operations import Operations +from sqlalchemy import ( + Column, + create_engine, + Index, + insert, + inspect, + Integer, + MetaData, + select, + String, + Table, +) +from sqlalchemy.engine import Engine + +migration = import_module( + "superset.migrations.versions." + "2026-05-08_12-05_9e1f3b8c4d2a_add_deleted_at_to_dashboards" +) + +TABLE_NAME = migration.TABLE_NAME # "dashboards" +DELETED_AT_INDEX_NAME = migration.DELETED_AT_INDEX_NAME +LEGACY_SLUG_INDEX_NAME = migration.LEGACY_SLUG_INDEX_NAME + + [email protected] +def engine() -> Engine: + """In-memory SQLite seeded with a minimal pre-migration ``dashboards`` table. + + The real ``dashboards`` table has many columns; the migration only + touches ``deleted_at``, its index, and the legacy slug constraint, + so only those columns need to exist. The legacy unique constraint + on ``slug`` is included so SQLite's no-op branch can be asserted + against the post-migration state. + """ + engine = create_engine("sqlite:///:memory:") + md = MetaData() + table = Table( + TABLE_NAME, + md, + Column("id", Integer, primary_key=True), + Column("dashboard_title", String(500)), + Column("slug", String(255)), + ) + # Production seeds the legacy slug uniqueness as a named UNIQUE INDEX, + # not a column-level UNIQUE constraint. Mirror that here so ``inspect() + # .get_indexes()`` reports it — column-level UNIQUE on SQLite is not + # surfaced by the indexes inspector. + Index(LEGACY_SLUG_INDEX_NAME, table.c.slug, unique=True) + md.create_all(engine) + return engine + + +def _columns(engine: Engine) -> set[str]: + return {col["name"] for col in inspect(engine).get_columns(TABLE_NAME)} + + +def _indexes(engine: Engine) -> set[str]: + return {ix["name"] for ix in inspect(engine).get_indexes(TABLE_NAME)} + + +def test_upgrade_adds_deleted_at_column_and_index(engine: Engine) -> None: + with engine.connect() as conn: + ctx = MigrationContext.configure(conn) + with Operations.context(ctx): + migration.upgrade() + + assert "deleted_at" in _columns(engine), "upgrade() must add the deleted_at column" + assert DELETED_AT_INDEX_NAME in _indexes(engine), ( + "upgrade() must create the supporting index on deleted_at" + ) Review Comment: **Suggestion:** Add a docstring to this test function summarizing the expected upgrade behavior it validates. [custom_rule] **Severity Level:** Minor ⚠️ <details> <summary><b>Why it matters? 🤔 </b></summary> The test function is newly added and does not have a docstring, so it violates the custom rule for new Python functions. </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=4122cb7807064720af5a53da5e341985&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=4122cb7807064720af5a53da5e341985&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** tests/unit_tests/migrations/test_add_deleted_at_to_dashboards.py **Line:** 105:114 **Comment:** *Custom Rule: Add a docstring to this test function summarizing the expected upgrade behavior it validates. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=501697d306a66eb97a618850bd8d2223f9db2e796704c174632eaa5a86359236&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=501697d306a66eb97a618850bd8d2223f9db2e796704c174632eaa5a86359236&reaction=dislike'>👎</a> ########## superset/commands/dashboard/exceptions.py: ########## @@ -70,6 +71,24 @@ class DashboardColorsConfigUpdateFailedError(UpdateFailedError): message = _("Dashboard color configuration could not be updated.") +class DashboardRestoreFailedError(UpdateFailedError): + # Restore semantically clears ``deleted_at``; it is an UPDATE, not a new + # row. ``UpdateFailedError`` is the nearest typed middle-tier base in the + # codebase. A dedicated ``RestoreFailedError`` in + # ``superset/commands/exceptions.py`` would be more precise across the + # entity rollouts but lives in already-merged infrastructure (#39977); + # introducing it can be a cross-entity follow-up. + message = _("Dashboard could not be restored.") Review Comment: **Suggestion:** Add a class docstring describing the purpose of this new exception class so the newly introduced class is documented inline. [custom_rule] **Severity Level:** Minor ⚠️ <details> <summary><b>Why it matters? 🤔 </b></summary> This is a newly added class and it does not include a docstring. The custom rule requires newly added Python classes to be documented inline, so the suggestion identifies a real violation. </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=01d0a8900c35448185bb8f75ea713eb6&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=01d0a8900c35448185bb8f75ea713eb6&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/commands/dashboard/exceptions.py **Line:** 74:81 **Comment:** *Custom Rule: Add a class docstring describing the purpose of this new exception class so the newly introduced class is documented inline. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=b65481fed81ae3ec4ef38b36cf1c784c17514eb368a2dc2693cb47fe5031e48c&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=b65481fed81ae3ec4ef38b36cf1c784c17514eb368a2dc2693cb47fe5031e48c&reaction=dislike'>👎</a> ########## superset/migrations/versions/2026-05-08_12-05_9e1f3b8c4d2a_add_deleted_at_to_dashboards.py: ########## @@ -0,0 +1,184 @@ +# 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. +"""Add deleted_at + partial unique slug index for soft-delete. + +Adds to the ``dashboards`` table: +- a nullable ``deleted_at`` column for soft-delete state +- an index ``ix_dashboards_deleted_at`` for the visibility-filter listener +- a partial unique index ``ix_dashboards_active_slug`` enforcing slug + uniqueness only among active (non-soft-deleted) rows + +Drops: +- the existing full unique constraint on ``slug`` (named + ``idx_unique_slug``, created in migration 1a48a5411020) + +The constraint change makes the ``slug`` field reusable after soft-delete: +soft-deleted rows no longer reserve their slug for the lifetime of the +row. ``RestoreDashboardCommand`` handles the reverse case (restoring a +dashboard whose slug has since been claimed by another active row) with +an explicit conflict error. See UPDATING.md for the user-facing change. + +Dialect support for the partial index: +- PostgreSQL: native ``WHERE deleted_at IS NULL`` partial index +- MySQL 8.0+: functional index over + ``(CASE WHEN deleted_at IS NULL THEN slug END)`` +- MySQL <8.0: keeps the original full unique constraint (documented + limitation; functional indexes are not supported on these versions) +- SQLite: keeps the original full unique constraint (column-level + ``UNIQUE`` cannot be dropped without recreating the table, which is + not worth the migration complexity for a test-only dialect). Tests + that need to verify the partial-index behaviour run only on + PostgreSQL and MySQL 8+. + +Revision ID: 9e1f3b8c4d2a +Revises: 31dae2559c05 +Create Date: 2026-05-08 12:05:00.000000 +""" + +from alembic import op +from sqlalchemy import Column, DateTime +from sqlalchemy.engine import Connection + +from superset.migrations.shared.utils import ( + add_columns, + create_index, + drop_columns, + drop_index, +) + +# revision identifiers, used by Alembic. +revision = "9e1f3b8c4d2a" +down_revision = "31dae2559c05" + +TABLE_NAME = "dashboards" +DELETED_AT_INDEX_NAME = f"ix_{TABLE_NAME}_deleted_at" +PARTIAL_SLUG_INDEX_NAME = f"ix_{TABLE_NAME}_active_slug" +# The original full unique constraint on ``slug`` was created with an +# explicit name in migration 1a48a5411020 (2015-12-04). Same name on +# PostgreSQL (constraint) and MySQL (index). +LEGACY_SLUG_INDEX_NAME = "idx_unique_slug" + + +def _mysql_supports_functional_index(bind: Connection) -> bool: + """Return True iff the connected MySQL is 8.0.13+ (supports functional indexes). + + MySQL added functional key parts in 8.0.13; 8.0.0–8.0.12 reject the + ``(CASE WHEN deleted_at IS NULL THEN slug END)`` expression at index + creation time, so deployments on those patch releases must keep the + original full slug constraint. See + https://dev.mysql.com/doc/mysql/8.0/en/create-index.html for the + 8.0.13 minimum. + + Excludes MariaDB even at server version ``>= (10, x)`` because MariaDB + reports through the same ``server_version_info`` attribute but uses + different functional-index semantics around ``CASE`` expressions. + Uses SQLAlchemy's parsed ``server_version_info`` rather than ``SELECT + VERSION()`` to avoid an extra round-trip and brittle string parsing. + """ + if getattr(bind.dialect, "is_mariadb", False): + return False + return (bind.dialect.server_version_info or ()) >= (8, 0, 13) + + +def upgrade() -> None: + bind = op.get_bind() + _add_deleted_at_column() + _replace_slug_constraint_with_partial_index(bind) + + +def downgrade() -> None: + bind = op.get_bind() + _restore_slug_constraint(bind) + _drop_deleted_at_column() Review Comment: **Suggestion:** Add a concise docstring to this new function to explain the downgrade behavior and intent. [custom_rule] **Severity Level:** Minor ⚠️ <details> <summary><b>Why it matters? 🤔 </b></summary> This newly added function does not include a docstring, which violates the rule that new Python functions should be documented inline. </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=934fa91475f34a0fad85eb16b5d0a399&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=934fa91475f34a0fad85eb16b5d0a399&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/migrations/versions/2026-05-08_12-05_9e1f3b8c4d2a_add_deleted_at_to_dashboards.py **Line:** 103:106 **Comment:** *Custom Rule: Add a concise docstring to this new function to explain the downgrade behavior and intent. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=ff681c0ee699ea569b9d964e4a872d0388760cf96330803556ffd8093a06e028&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=ff681c0ee699ea569b9d964e4a872d0388760cf96330803556ffd8093a06e028&reaction=dislike'>👎</a> ########## superset/commands/dashboard/exceptions.py: ########## @@ -70,6 +71,24 @@ class DashboardColorsConfigUpdateFailedError(UpdateFailedError): message = _("Dashboard color configuration could not be updated.") +class DashboardRestoreFailedError(UpdateFailedError): + # Restore semantically clears ``deleted_at``; it is an UPDATE, not a new + # row. ``UpdateFailedError`` is the nearest typed middle-tier base in the + # codebase. A dedicated ``RestoreFailedError`` in + # ``superset/commands/exceptions.py`` would be more precise across the + # entity rollouts but lives in already-merged infrastructure (#39977); + # introducing it can be a cross-entity follow-up. + message = _("Dashboard could not be restored.") + + +class DashboardSlugConflictError(CommandException): + status = 422 + message = _( + "Dashboard cannot be restored because its slug is now used by " + "another active dashboard. Rename one of the dashboards and retry." + ) Review Comment: **Suggestion:** Add a class docstring to this new exception class to satisfy the requirement that newly added classes include inline documentation. [custom_rule] **Severity Level:** Minor ⚠️ <details> <summary><b>Why it matters? 🤔 </b></summary> This is also a newly added class and it lacks a docstring. That directly violates the rule requiring newly added Python classes to include inline documentation. </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=c3fa95fc7aae4e46955631a912603535&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=c3fa95fc7aae4e46955631a912603535&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/commands/dashboard/exceptions.py **Line:** 84:89 **Comment:** *Custom Rule: Add a class docstring to this new exception class to satisfy the requirement that newly added classes include inline documentation. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=c43f2fadc6f7a0a4b8bdf2e2c104beb484bfa8dd334fdc8ccd9c540d7e6cc199&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=c43f2fadc6f7a0a4b8bdf2e2c104beb484bfa8dd334fdc8ccd9c540d7e6cc199&reaction=dislike'>👎</a> ########## superset/migrations/versions/2026-05-08_12-05_9e1f3b8c4d2a_add_deleted_at_to_dashboards.py: ########## @@ -0,0 +1,184 @@ +# 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. +"""Add deleted_at + partial unique slug index for soft-delete. + +Adds to the ``dashboards`` table: +- a nullable ``deleted_at`` column for soft-delete state +- an index ``ix_dashboards_deleted_at`` for the visibility-filter listener +- a partial unique index ``ix_dashboards_active_slug`` enforcing slug + uniqueness only among active (non-soft-deleted) rows + +Drops: +- the existing full unique constraint on ``slug`` (named + ``idx_unique_slug``, created in migration 1a48a5411020) + +The constraint change makes the ``slug`` field reusable after soft-delete: +soft-deleted rows no longer reserve their slug for the lifetime of the +row. ``RestoreDashboardCommand`` handles the reverse case (restoring a +dashboard whose slug has since been claimed by another active row) with +an explicit conflict error. See UPDATING.md for the user-facing change. + +Dialect support for the partial index: +- PostgreSQL: native ``WHERE deleted_at IS NULL`` partial index +- MySQL 8.0+: functional index over + ``(CASE WHEN deleted_at IS NULL THEN slug END)`` +- MySQL <8.0: keeps the original full unique constraint (documented + limitation; functional indexes are not supported on these versions) +- SQLite: keeps the original full unique constraint (column-level + ``UNIQUE`` cannot be dropped without recreating the table, which is + not worth the migration complexity for a test-only dialect). Tests + that need to verify the partial-index behaviour run only on + PostgreSQL and MySQL 8+. + +Revision ID: 9e1f3b8c4d2a +Revises: 31dae2559c05 +Create Date: 2026-05-08 12:05:00.000000 +""" + +from alembic import op +from sqlalchemy import Column, DateTime +from sqlalchemy.engine import Connection + +from superset.migrations.shared.utils import ( + add_columns, + create_index, + drop_columns, + drop_index, +) + +# revision identifiers, used by Alembic. +revision = "9e1f3b8c4d2a" +down_revision = "31dae2559c05" + +TABLE_NAME = "dashboards" +DELETED_AT_INDEX_NAME = f"ix_{TABLE_NAME}_deleted_at" +PARTIAL_SLUG_INDEX_NAME = f"ix_{TABLE_NAME}_active_slug" +# The original full unique constraint on ``slug`` was created with an +# explicit name in migration 1a48a5411020 (2015-12-04). Same name on +# PostgreSQL (constraint) and MySQL (index). +LEGACY_SLUG_INDEX_NAME = "idx_unique_slug" + + +def _mysql_supports_functional_index(bind: Connection) -> bool: + """Return True iff the connected MySQL is 8.0.13+ (supports functional indexes). + + MySQL added functional key parts in 8.0.13; 8.0.0–8.0.12 reject the + ``(CASE WHEN deleted_at IS NULL THEN slug END)`` expression at index + creation time, so deployments on those patch releases must keep the + original full slug constraint. See + https://dev.mysql.com/doc/mysql/8.0/en/create-index.html for the + 8.0.13 minimum. + + Excludes MariaDB even at server version ``>= (10, x)`` because MariaDB + reports through the same ``server_version_info`` attribute but uses + different functional-index semantics around ``CASE`` expressions. + Uses SQLAlchemy's parsed ``server_version_info`` rather than ``SELECT + VERSION()`` to avoid an extra round-trip and brittle string parsing. + """ + if getattr(bind.dialect, "is_mariadb", False): + return False + return (bind.dialect.server_version_info or ()) >= (8, 0, 13) + + +def upgrade() -> None: + bind = op.get_bind() + _add_deleted_at_column() + _replace_slug_constraint_with_partial_index(bind) Review Comment: **Suggestion:** Add a short docstring to this newly added function describing the migration step it performs. [custom_rule] **Severity Level:** Minor ⚠️ <details> <summary><b>Why it matters? 🤔 </b></summary> This is a newly added Python function and it has no docstring immediately under the definition. The custom rule requires newly added functions to be documented inline, so the suggestion identifies a real violation. </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=036cda3967024f7ba48275fe3f608398&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=036cda3967024f7ba48275fe3f608398&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/migrations/versions/2026-05-08_12-05_9e1f3b8c4d2a_add_deleted_at_to_dashboards.py **Line:** 97:100 **Comment:** *Custom Rule: Add a short docstring to this newly added function describing the migration step it performs. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=6933acf1a03343e45890e5441588cbd44d7840cf5a97b07def5761411f60b573&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=6933acf1a03343e45890e5441588cbd44d7840cf5a97b07def5761411f60b573&reaction=dislike'>👎</a> ########## superset/migrations/versions/2026-05-08_12-05_9e1f3b8c4d2a_add_deleted_at_to_dashboards.py: ########## @@ -0,0 +1,184 @@ +# 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. +"""Add deleted_at + partial unique slug index for soft-delete. + +Adds to the ``dashboards`` table: +- a nullable ``deleted_at`` column for soft-delete state +- an index ``ix_dashboards_deleted_at`` for the visibility-filter listener +- a partial unique index ``ix_dashboards_active_slug`` enforcing slug + uniqueness only among active (non-soft-deleted) rows + +Drops: +- the existing full unique constraint on ``slug`` (named + ``idx_unique_slug``, created in migration 1a48a5411020) + +The constraint change makes the ``slug`` field reusable after soft-delete: +soft-deleted rows no longer reserve their slug for the lifetime of the +row. ``RestoreDashboardCommand`` handles the reverse case (restoring a +dashboard whose slug has since been claimed by another active row) with +an explicit conflict error. See UPDATING.md for the user-facing change. + +Dialect support for the partial index: +- PostgreSQL: native ``WHERE deleted_at IS NULL`` partial index +- MySQL 8.0+: functional index over + ``(CASE WHEN deleted_at IS NULL THEN slug END)`` +- MySQL <8.0: keeps the original full unique constraint (documented + limitation; functional indexes are not supported on these versions) +- SQLite: keeps the original full unique constraint (column-level + ``UNIQUE`` cannot be dropped without recreating the table, which is + not worth the migration complexity for a test-only dialect). Tests + that need to verify the partial-index behaviour run only on + PostgreSQL and MySQL 8+. + +Revision ID: 9e1f3b8c4d2a +Revises: 31dae2559c05 +Create Date: 2026-05-08 12:05:00.000000 +""" + +from alembic import op +from sqlalchemy import Column, DateTime +from sqlalchemy.engine import Connection + +from superset.migrations.shared.utils import ( + add_columns, + create_index, + drop_columns, + drop_index, +) + +# revision identifiers, used by Alembic. +revision = "9e1f3b8c4d2a" +down_revision = "31dae2559c05" + +TABLE_NAME = "dashboards" +DELETED_AT_INDEX_NAME = f"ix_{TABLE_NAME}_deleted_at" +PARTIAL_SLUG_INDEX_NAME = f"ix_{TABLE_NAME}_active_slug" +# The original full unique constraint on ``slug`` was created with an +# explicit name in migration 1a48a5411020 (2015-12-04). Same name on +# PostgreSQL (constraint) and MySQL (index). +LEGACY_SLUG_INDEX_NAME = "idx_unique_slug" + + +def _mysql_supports_functional_index(bind: Connection) -> bool: + """Return True iff the connected MySQL is 8.0.13+ (supports functional indexes). + + MySQL added functional key parts in 8.0.13; 8.0.0–8.0.12 reject the + ``(CASE WHEN deleted_at IS NULL THEN slug END)`` expression at index + creation time, so deployments on those patch releases must keep the + original full slug constraint. See + https://dev.mysql.com/doc/mysql/8.0/en/create-index.html for the + 8.0.13 minimum. + + Excludes MariaDB even at server version ``>= (10, x)`` because MariaDB + reports through the same ``server_version_info`` attribute but uses + different functional-index semantics around ``CASE`` expressions. + Uses SQLAlchemy's parsed ``server_version_info`` rather than ``SELECT + VERSION()`` to avoid an extra round-trip and brittle string parsing. + """ + if getattr(bind.dialect, "is_mariadb", False): + return False + return (bind.dialect.server_version_info or ()) >= (8, 0, 13) + + +def upgrade() -> None: + bind = op.get_bind() + _add_deleted_at_column() + _replace_slug_constraint_with_partial_index(bind) + + +def downgrade() -> None: + bind = op.get_bind() + _restore_slug_constraint(bind) + _drop_deleted_at_column() + + +def _add_deleted_at_column() -> None: + add_columns(TABLE_NAME, Column("deleted_at", DateTime(), nullable=True)) + create_index(TABLE_NAME, DELETED_AT_INDEX_NAME, ["deleted_at"]) Review Comment: **Suggestion:** Add a docstring to this newly introduced helper function to describe the schema changes it applies. [custom_rule] **Severity Level:** Minor ⚠️ <details> <summary><b>Why it matters? 🤔 </b></summary> This helper function is newly introduced and has no docstring. That matches the custom rule requiring new Python functions to include docstrings. </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=cd62a9d8912540b2bdccf3153dc18203&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=cd62a9d8912540b2bdccf3153dc18203&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/migrations/versions/2026-05-08_12-05_9e1f3b8c4d2a_add_deleted_at_to_dashboards.py **Line:** 109:111 **Comment:** *Custom Rule: Add a docstring to this newly introduced helper function to describe the schema changes it applies. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=51309a6232f179e8a89435933d02b6ac08bf0b9225d3b4b27a9f8b17442f87d1&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=51309a6232f179e8a89435933d02b6ac08bf0b9225d3b4b27a9f8b17442f87d1&reaction=dislike'>👎</a> ########## superset/migrations/versions/2026-05-08_12-05_9e1f3b8c4d2a_add_deleted_at_to_dashboards.py: ########## @@ -0,0 +1,184 @@ +# 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. +"""Add deleted_at + partial unique slug index for soft-delete. + +Adds to the ``dashboards`` table: +- a nullable ``deleted_at`` column for soft-delete state +- an index ``ix_dashboards_deleted_at`` for the visibility-filter listener +- a partial unique index ``ix_dashboards_active_slug`` enforcing slug + uniqueness only among active (non-soft-deleted) rows + +Drops: +- the existing full unique constraint on ``slug`` (named + ``idx_unique_slug``, created in migration 1a48a5411020) + +The constraint change makes the ``slug`` field reusable after soft-delete: +soft-deleted rows no longer reserve their slug for the lifetime of the +row. ``RestoreDashboardCommand`` handles the reverse case (restoring a +dashboard whose slug has since been claimed by another active row) with +an explicit conflict error. See UPDATING.md for the user-facing change. + +Dialect support for the partial index: +- PostgreSQL: native ``WHERE deleted_at IS NULL`` partial index +- MySQL 8.0+: functional index over + ``(CASE WHEN deleted_at IS NULL THEN slug END)`` +- MySQL <8.0: keeps the original full unique constraint (documented + limitation; functional indexes are not supported on these versions) +- SQLite: keeps the original full unique constraint (column-level + ``UNIQUE`` cannot be dropped without recreating the table, which is + not worth the migration complexity for a test-only dialect). Tests + that need to verify the partial-index behaviour run only on + PostgreSQL and MySQL 8+. + +Revision ID: 9e1f3b8c4d2a +Revises: 31dae2559c05 +Create Date: 2026-05-08 12:05:00.000000 +""" + +from alembic import op +from sqlalchemy import Column, DateTime +from sqlalchemy.engine import Connection + +from superset.migrations.shared.utils import ( + add_columns, + create_index, + drop_columns, + drop_index, +) + +# revision identifiers, used by Alembic. +revision = "9e1f3b8c4d2a" +down_revision = "31dae2559c05" + +TABLE_NAME = "dashboards" +DELETED_AT_INDEX_NAME = f"ix_{TABLE_NAME}_deleted_at" +PARTIAL_SLUG_INDEX_NAME = f"ix_{TABLE_NAME}_active_slug" +# The original full unique constraint on ``slug`` was created with an +# explicit name in migration 1a48a5411020 (2015-12-04). Same name on +# PostgreSQL (constraint) and MySQL (index). +LEGACY_SLUG_INDEX_NAME = "idx_unique_slug" + + +def _mysql_supports_functional_index(bind: Connection) -> bool: + """Return True iff the connected MySQL is 8.0.13+ (supports functional indexes). + + MySQL added functional key parts in 8.0.13; 8.0.0–8.0.12 reject the + ``(CASE WHEN deleted_at IS NULL THEN slug END)`` expression at index + creation time, so deployments on those patch releases must keep the + original full slug constraint. See + https://dev.mysql.com/doc/mysql/8.0/en/create-index.html for the + 8.0.13 minimum. + + Excludes MariaDB even at server version ``>= (10, x)`` because MariaDB + reports through the same ``server_version_info`` attribute but uses + different functional-index semantics around ``CASE`` expressions. + Uses SQLAlchemy's parsed ``server_version_info`` rather than ``SELECT + VERSION()`` to avoid an extra round-trip and brittle string parsing. + """ + if getattr(bind.dialect, "is_mariadb", False): + return False + return (bind.dialect.server_version_info or ()) >= (8, 0, 13) + + +def upgrade() -> None: + bind = op.get_bind() + _add_deleted_at_column() + _replace_slug_constraint_with_partial_index(bind) + + +def downgrade() -> None: + bind = op.get_bind() + _restore_slug_constraint(bind) + _drop_deleted_at_column() + + +def _add_deleted_at_column() -> None: + add_columns(TABLE_NAME, Column("deleted_at", DateTime(), nullable=True)) + create_index(TABLE_NAME, DELETED_AT_INDEX_NAME, ["deleted_at"]) + + +def _drop_deleted_at_column() -> None: + drop_index(TABLE_NAME, DELETED_AT_INDEX_NAME) + drop_columns(TABLE_NAME, "deleted_at") Review Comment: **Suggestion:** Add a brief docstring to this newly added helper function so its cleanup responsibility is explicit. [custom_rule] **Severity Level:** Minor ⚠️ <details> <summary><b>Why it matters? 🤔 </b></summary> This newly added helper function lacks a docstring, so it violates the rule that new Python functions should be documented inline. </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=4810c98f561240c697b68b967e24316d&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=4810c98f561240c697b68b967e24316d&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/migrations/versions/2026-05-08_12-05_9e1f3b8c4d2a_add_deleted_at_to_dashboards.py **Line:** 114:116 **Comment:** *Custom Rule: Add a brief docstring to this newly added helper function so its cleanup responsibility is explicit. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=ecbb229889ef7deb767144c0102993e96067841a858a78057c6f6bd0ec36d3f0&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40128&comment_hash=ecbb229889ef7deb767144c0102993e96067841a858a78057c6f6bd0ec36d3f0&reaction=dislike'>👎</a> -- 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]
