Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/docs/using-superset/recently-archived.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ has dependent charts, the confirmation lists the affected objects and explains
that those charts become unavailable until the dataset is recovered. Chart and
dashboard totals are separate: some affected charts may not belong to a dashboard.

An archived dataset still reserves its name within the same database, catalog,
and schema. Attempting to create a duplicate names the archived dataset in the
error message. Restore it to use the existing dataset, or delete it permanently
from **Recently Archived** before creating a replacement.

Back and Forward restore the selected type and its page, sort, and search from
the URL. On chart and dashboard cards in the Charts and Dashboards lists,
Tab to the **More Options** button to read why Edit or Archive is unavailable
Expand Down
10 changes: 5 additions & 5 deletions superset/commands/dataset/create.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,14 +230,14 @@ def validate(self) -> None: # noqa: C901
table = Table(table_name, schema, catalog)

if not DatasetDAO.validate_uniqueness(database, table):
# Distinguish the hidden-twin case: uniqueness fails while
# the caller's dataset list looks empty. Raise the targeted
# 422 (naming the twin's uuid and the restore endpoint)
# instead of the opaque "already exists".
# Archived datasets are hidden from the dataset picker; name
# the duplicate and explain how to recover or remove it.
if soft_twin := DatasetDAO.find_soft_deleted_logical_duplicate(
database, table
):
raise DatasetSoftDeletedTwinExistsError(str(soft_twin.uuid))
raise DatasetSoftDeletedTwinExistsError(
str(soft_twin.uuid), dataset_name=str(soft_twin.table_name)
)
Comment on lines +238 to +240

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: When archived datasets share a table name across schemas or catalogs, Recently Archived displays only that name, so this error cannot identify which row to restore or purge.

Assessment: 🟠 Major · 🔁 Occurrence: Rarely · 🏷️ Incomplete implementation

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/commands/dataset/create.py
**Line:** 238:240
**Comment:**
	*Incomplete Implementation: When archived datasets share a table name across schemas or catalogs, Recently Archived displays only that name, so this error cannot identify which row to restore or purge.

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

exceptions.append(DatasetExistsValidationError(table))

# Validate table exists on dataset if sql is not provided
Expand Down
18 changes: 13 additions & 5 deletions superset/commands/dataset/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,15 +226,23 @@ class DatasetRestoreFailedError(UpdateFailedError):
class DatasetSoftDeletedTwinExistsError(CommandException):
"""A soft-deleted dataset holds the physical table the caller targets.

Single source of the blocked-by-hidden-twin message: the create command,
``get_or_create_dataset``, and any future caller raise this so the
wording (restore pointer, executable recoveries only) cannot drift
between surfaces.
Creation callers supply the dataset name for user-facing recovery guidance.
Callers without a name retain the UUID and restore endpoint.
"""

status = 422

def __init__(self, dataset_uuid: str) -> None:
def __init__(self, dataset_uuid: str, dataset_name: str | None = None) -> None:
if dataset_name is not None:
super().__init__(
_(
'Dataset "%(name)s" already exists in Recently Archived. '
"Restore it to use the existing dataset, or delete it permanently "
"before creating a new dataset with the same name.",
Comment on lines +239 to +241

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The previous message ended "…or use a different table name", and that option is gone. Restore and Delete permanently are limited to the dataset's editors and admins, so a user who can create datasets on this database but never owned the archived one gets no action they can take. Suggest restoring the alternative and adding an ask-an-owner-or-admin path:

Suggested change
'Dataset "%(name)s" already exists in Recently Archived. '
"Restore it to use the existing dataset, or delete it permanently "
"before creating a new dataset with the same name.",
'Dataset "%(name)s" already exists in Recently Archived. '
"Restore it or delete it permanently from Recently Archived, "
"or use a different name. If you can't restore it, ask one of "
"its owners or an admin.",

The docs paragraph in recently-archived.mdx would want the same addition.

name=dataset_name,
)
)
return
super().__init__(
_(
"A soft-deleted dataset (uuid %(uuid)s) already references "
Expand Down
3 changes: 1 addition & 2 deletions superset/datasets/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1993,8 +1993,7 @@ def get_or_create_dataset(self) -> Response:
tbl = CreateDatasetCommand(body).run()
return self.response(200, result={"table_id": tbl.id})
except DatasetSoftDeletedTwinExistsError as ex:
# Targeted hidden-twin 422 (single-sourced in the exception):
# names the twin's uuid and the restore endpoint.
# Share the archived dataset's recovery guidance with POST /dataset/.
return self.response_422(message=str(ex))
except DatasetInvalidError as ex:
return self.response_422(message=ex.normalized_messages())
Expand Down
12 changes: 5 additions & 7 deletions tests/unit_tests/commands/dataset/test_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -639,9 +639,7 @@ def test_create_dataset_physical_table_no_parse_error(


def test_create_dataset_blocked_by_soft_deleted_twin() -> None:
"""Uniqueness failure caused by a hidden twin raises the targeted,
single-sourced 422 (naming the twin's uuid and the restore endpoint)
instead of the opaque "already exists" validation error."""
"""An archived duplicate raises a targeted 422 naming the dataset."""
from superset.commands.dataset.exceptions import (
DatasetSoftDeletedTwinExistsError,
)
Expand All @@ -651,6 +649,7 @@ def test_create_dataset_blocked_by_soft_deleted_twin() -> None:
mock_database.get_default_catalog.return_value = None
twin = Mock()
twin.uuid = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
twin.table_name = "blocked_tbl"

with patch(
"superset.commands.dataset.create.DatasetDAO.get_database_by_id",
Expand All @@ -672,11 +671,10 @@ def test_create_dataset_blocked_by_soft_deleted_twin() -> None:
command.validate()

message = str(exc_info.value)
assert "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" in message
assert "blocked_tbl" in message
assert "Recently Archived" in message
assert "restore" in message.lower()
# Executable recoveries only — no hard-delete/purge claims.
assert "hard-delete" not in message.lower()
assert "purge" not in message.lower()
assert "delete it permanently" in message


def test_create_dataset_generic_exists_error_when_no_twin() -> None:
Expand Down
59 changes: 59 additions & 0 deletions tests/unit_tests/datasets/api_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,65 @@ def _create_dataset(name: str) -> Any:
return dataset


@pytest.mark.parametrize("sql", [None, "SELECT 1"])
def test_post_dataset_with_archived_duplicate_returns_actionable_422(
session: Session,
client: FlaskClient,
full_api_access: None,
sql: str | None,
) -> None:
"""An archived duplicate must be named with guidance for recovering from it."""
from superset.connectors.sqla.models import SqlaTable
from superset.models.core import Database
from superset.models.helpers import skip_visibility_filter

SqlaTable.metadata.create_all(session.get_bind())
database = Database(database_name="archive_db", sqlalchemy_uri="sqlite://")
session.add(database)
session.commit()
payload = {
"database": database.id,
"schema": "main",
"table_name": "Vehicle Sales",
"sql": sql,
}

with (
patch(
"superset.daos.dataset.DatasetDAO.validate_table_exists", return_value=True
),
patch.object(SqlaTable, "fetch_metadata"),
):
created = client.post("/api/v1/dataset/", json=payload)
assert created.status_code == 201
assert created.json is not None

duplicate = client.post("/api/v1/dataset/", json=payload)
assert duplicate.status_code == 422
assert duplicate.json is not None
assert duplicate.json["message"] == {
"table": ["Dataset main.Vehicle Sales already exists"]
}

dataset = session.get(SqlaTable, created.json["id"])
assert dataset is not None
dataset.soft_delete()
session.commit()
assert session.query(SqlaTable).count() == 0

response = client.post("/api/v1/dataset/", json=payload)

assert response.status_code == 422
assert response.json is not None
assert response.json["message"] == (
'Dataset "Vehicle Sales" already exists in Recently Archived. '
"Restore it to use the existing dataset, or delete it permanently "
"before creating a new dataset with the same name."
)
with skip_visibility_filter(session, SqlaTable):
assert session.query(SqlaTable).one().is_deleted


def test_post_dataset_with_invalid_sql_returns_actionable_422(
session: Session,
client: Any,
Expand Down
Loading