You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ru...@apache.org on 2026/09/29 02:27:45 UTC
(superset) branch master updated: fix(databases): surface dataset dependents in the delete confirmation (#44392)
This is an automated email from the ASF dual-hosted git repository.
rusackas 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 8bd92b7073e fix(databases): surface dataset dependents in the delete confirmation (#44392)
8bd92b7073e is described below
commit 8bd92b7073e2bfac6e52fa495468cb58dab83dae
Author: Geidō <60...@users.noreply.github.com>
AuthorDate: Tue Sep 29 05:27:38 2026 +0300
fix(databases): surface dataset dependents in the delete confirmation (#44392)
---
docs/static/resources/openapi.json | 33 +++
.../components/DeleteModal/DeleteModal.test.tsx | 37 ++-
.../src/components/DeleteModal/index.tsx | 14 +-
.../src/components/DeleteModal/types.ts | 4 +-
.../DatabaseList.datasetDependents.test.tsx | 289 +++++++++++++++++++++
superset-frontend/src/pages/DatabaseList/index.tsx | 108 +++++++-
superset/daos/database.py | 43 ++-
superset/databases/api.py | 23 ++
superset/databases/schemas.py | 15 ++
superset/translations/messages.pot | 14 +
tests/integration_tests/databases/api_tests.py | 3 +
tests/unit_tests/databases/api_test.py | 117 +++++++++
.../databases/dao/related_objects_test.py | 122 +++++++++
13 files changed, 797 insertions(+), 25 deletions(-)
diff --git a/docs/static/resources/openapi.json b/docs/static/resources/openapi.json
index 1072dce40a5..5ea742a07eb 100644
--- a/docs/static/resources/openapi.json
+++ b/docs/static/resources/openapi.json
@@ -4870,6 +4870,36 @@
},
"type": "object"
},
+ "DatabaseRelatedDataset": {
+ "properties": {
+ "id": {
+ "type": "integer"
+ },
+ "schema": {
+ "type": "string"
+ },
+ "table_name": {
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "DatabaseRelatedDatasets": {
+ "properties": {
+ "count": {
+ "description": "Dataset count",
+ "type": "integer"
+ },
+ "result": {
+ "description": "A list of datasets",
+ "items": {
+ "$ref": "#/components/schemas/DatabaseRelatedDataset"
+ },
+ "type": "array"
+ }
+ },
+ "type": "object"
+ },
"DatabaseRelatedObjectsResponse": {
"properties": {
"charts": {
@@ -4877,6 +4907,9 @@
},
"dashboards": {
"$ref": "#/components/schemas/DatabaseRelatedDashboards"
+ },
+ "datasets": {
+ "$ref": "#/components/schemas/DatabaseRelatedDatasets"
}
},
"type": "object"
diff --git a/superset-frontend/packages/superset-ui-core/src/components/DeleteModal/DeleteModal.test.tsx b/superset-frontend/packages/superset-ui-core/src/components/DeleteModal/DeleteModal.test.tsx
index 1a141e83989..07e329d22ec 100644
--- a/superset-frontend/packages/superset-ui-core/src/components/DeleteModal/DeleteModal.test.tsx
+++ b/superset-frontend/packages/superset-ui-core/src/components/DeleteModal/DeleteModal.test.tsx
@@ -215,9 +215,9 @@ test('Calling "onConfirm" only after typing "delete" in the input', async () =>
expect(screen.getByTestId('delete-modal-input')).toHaveValue('');
});
-test('external disable keeps the destructive action unavailable after confirmation', async () => {
+test('external disable blocks the action while allowing confirmation text', async () => {
const onConfirm = jest.fn();
- render(
+ const { rerender } = render(
<DeleteModal
title="Delete permanently?"
description="This cannot be undone."
@@ -228,11 +228,39 @@ test('external disable keeps the destructive action unavailable after confirmati
/>,
);
+ expect(screen.getByTestId('delete-modal-input')).toBeEnabled();
+ expect(screen.getByRole('button', { name: 'Delete' })).toBeDisabled();
await userEvent.type(screen.getByTestId('delete-modal-input'), 'DELETE');
-
expect(screen.getByRole('button', { name: 'Delete' })).toBeDisabled();
await userEvent.click(screen.getByRole('button', { name: 'Delete' }));
expect(onConfirm).not.toHaveBeenCalled();
+
+ rerender(
+ <DeleteModal
+ title="Delete permanently?"
+ description="This cannot be undone."
+ onConfirm={onConfirm}
+ onHide={jest.fn()}
+ open
+ />,
+ );
+ expect(screen.getByRole('button', { name: 'Delete' })).toBeEnabled();
+});
+
+test('blocked deletion disables the confirmation input and action', () => {
+ render(
+ <DeleteModal
+ title="Delete permanently?"
+ description="This cannot be undone."
+ onConfirm={jest.fn()}
+ onHide={jest.fn()}
+ open
+ disableConfirmationInput
+ />,
+ );
+
+ expect(screen.getByTestId('delete-modal-input')).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Delete' })).toBeDisabled();
});
test('loading disables the destructive action and exposes busy state', async () => {
@@ -247,8 +275,7 @@ test('loading disables the destructive action and exposes busy state', async ()
/>,
);
- await userEvent.type(screen.getByTestId('delete-modal-input'), 'DELETE');
-
+ expect(screen.getByTestId('delete-modal-input')).toBeEnabled();
expect(screen.getByTestId('modal-confirm-button')).toBeDisabled();
expect(screen.getByTestId('antd-modal')).toHaveAttribute('aria-busy', 'true');
});
diff --git a/superset-frontend/packages/superset-ui-core/src/components/DeleteModal/index.tsx b/superset-frontend/packages/superset-ui-core/src/components/DeleteModal/index.tsx
index d187dc57981..6acb1104a8e 100644
--- a/superset-frontend/packages/superset-ui-core/src/components/DeleteModal/index.tsx
+++ b/superset-frontend/packages/superset-ui-core/src/components/DeleteModal/index.tsx
@@ -43,6 +43,7 @@ export function DeleteModal({
primaryButtonName,
primaryButtonStyle,
disablePrimaryButton = false,
+ disableConfirmationInput = false,
loading = false,
confirmationResetKey,
}: DeleteModalProps) {
@@ -52,12 +53,14 @@ export function DeleteModal({
const [disableChange, setDisableChange] = useState(true);
const [confirmation, setConfirmation] = useState<string>('');
const inputRef = useRef<InputRef>(null);
+ const confirmationBlocked =
+ disablePrimaryButton || disableConfirmationInput || loading;
useEffect(() => {
- if (open && inputRef.current) {
+ if (open && !disableConfirmationInput && inputRef.current) {
inputRef.current.focus();
}
- }, [open]);
+ }, [disableConfirmationInput, open]);
useEffect(() => {
setConfirmation('');
@@ -86,7 +89,7 @@ export function DeleteModal({
};
const onPressEnter = () => {
- if (!disableChange && !disablePrimaryButton && !loading) {
+ if (!disableChange && !confirmationBlocked) {
confirm();
}
};
@@ -94,9 +97,7 @@ export function DeleteModal({
return (
<Modal
disablePrimaryButton={
- disablePrimaryButton ||
- loading ||
- (showConfirmationInput ? disableChange : false)
+ confirmationBlocked || (showConfirmationInput ? disableChange : false)
}
primaryButtonLoading={loading}
onHide={hide}
@@ -127,6 +128,7 @@ export function DeleteModal({
type="text"
id="delete"
autoComplete="off"
+ disabled={disableConfirmationInput}
value={confirmation}
onChange={onChange}
onPressEnter={onPressEnter}
diff --git a/superset-frontend/packages/superset-ui-core/src/components/DeleteModal/types.ts b/superset-frontend/packages/superset-ui-core/src/components/DeleteModal/types.ts
index 4c0bff7187b..a62917e6654 100644
--- a/superset-frontend/packages/superset-ui-core/src/components/DeleteModal/types.ts
+++ b/superset-frontend/packages/superset-ui-core/src/components/DeleteModal/types.ts
@@ -47,8 +47,10 @@ export interface DeleteModalProps {
* otherwise `'danger'`. Same precedence as `primaryButtonName`.
*/
primaryButtonStyle?: ButtonStyle;
- /** Disable confirmation independently of the typed-text gate. */
+ /** Disable the primary action independently of the typed-text gate. */
disablePrimaryButton?: boolean;
+ /** Disable the confirmation input and primary action when deletion is blocked. */
+ disableConfirmationInput?: boolean;
/** Show progress on the primary action and prevent duplicate submission. */
loading?: boolean;
/** Clear and re-arm the typed-text gate when the reviewed data changes. */
diff --git a/superset-frontend/src/pages/DatabaseList/DatabaseList.datasetDependents.test.tsx b/superset-frontend/src/pages/DatabaseList/DatabaseList.datasetDependents.test.tsx
new file mode 100644
index 00000000000..9d89a5c5206
--- /dev/null
+++ b/superset-frontend/src/pages/DatabaseList/DatabaseList.datasetDependents.test.tsx
@@ -0,0 +1,289 @@
+/**
+ * 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 fetchMock from 'fetch-mock';
+import { configureStore } from '@reduxjs/toolkit';
+import { render, screen, within } from 'spec/helpers/testing-library';
+import userEvent from '@testing-library/user-event';
+import DatabaseList from 'src/pages/DatabaseList';
+
+/**
+ * Datasets are dependents of a database connection, and
+ * `DeleteDatabaseCommand.validate` refuses to delete a connection while any
+ * dataset still references it. The confirmation modal used to enumerate only
+ * charts, dashboards and SQL Lab tabs, so a connection whose only dependents
+ * were datasets read as "linked to 0 charts ... 0 dashboards" and promised
+ * that deleting "will break those objects" -- then the delete failed with a
+ * toast the user only saw after typing DELETE.
+ *
+ * These tests pin the dataset dependents being named and counted up front, and
+ * the copy telling the truth about the delete being blocked.
+ */
+
+const DATABASE_ID = 7;
+
+const databaseRow = {
+ id: DATABASE_ID,
+ database_name: 'qa_postgres',
+ backend: 'postgresql',
+ allow_run_async: false,
+ allow_dml: false,
+ allow_file_upload: false,
+ expose_in_sqllab: true,
+ changed_on_delta_humanized: 'a day ago',
+ changed_by: null,
+};
+
+const DATABASE_LIST_ROUTE = 'glob:*/api/v1/database/?q=*';
+const RELATED_OBJECTS_ROUTE = `glob:*/api/v1/database/${DATABASE_ID}/related_objects/*`;
+
+const mockUser = {
+ userId: 1,
+ firstName: 'Admin',
+ lastName: 'User',
+ roles: { Admin: [['can_write', 'Database']] },
+ permissions: {},
+ isActive: true,
+ email: 'admin@example.com',
+ createdOn: '2026-01-01T00:00:00',
+};
+
+const dataset = (id: number, tableName: string) => ({
+ id,
+ table_name: tableName,
+ schema: 'public',
+});
+
+const setupMocks = ({
+ datasets,
+ datasetCount,
+}: {
+ datasets: { id: number; table_name: string }[];
+ datasetCount?: number;
+}) => {
+ fetchMock.clearHistory().removeRoutes();
+ fetchMock.get('glob:*/api/v1/database/_info*', {
+ permissions: ['can_read', 'can_write', 'can_export'],
+ });
+ fetchMock.get('glob:*/api/v1/database/related/*', { result: [], count: 0 });
+ fetchMock.get(RELATED_OBJECTS_ROUTE, {
+ charts: { count: 0, result: [] },
+ dashboards: { count: 0, result: [] },
+ sqllab_tab_states: { count: 0, result: [] },
+ datasets: {
+ count: datasetCount ?? datasets.length,
+ result: datasets,
+ },
+ });
+ fetchMock.get(DATABASE_LIST_ROUTE, {
+ result: [databaseRow],
+ count: 1,
+ });
+};
+
+const renderDatabaseList = () => {
+ const store = configureStore({
+ reducer: {
+ user: (state = mockUser) => state,
+ common: (
+ state = {
+ conf: {
+ CSV_EXTENSIONS: ['csv'],
+ EXCEL_EXTENSIONS: ['xls'],
+ COLUMNAR_EXTENSIONS: ['parquet'],
+ ALLOWED_EXTENSIONS: ['csv', 'xls', 'parquet'],
+ SYNC_DB_PERMISSIONS_IN_ASYNC_MODE: false,
+ },
+ },
+ ) => state,
+ },
+ middleware: getDefaultMiddleware =>
+ getDefaultMiddleware({ serializableCheck: false, immutableCheck: false }),
+ });
+
+ return render(<DatabaseList user={mockUser} />, {
+ store,
+ useQueryParams: true,
+ useRouter: true,
+ });
+};
+
+const openDeleteModal = async () => {
+ const deleteButton = await screen.findByTestId('database-delete');
+ await userEvent.click(deleteButton);
+ return screen.findByRole('dialog');
+};
+
+afterEach(() => {
+ fetchMock.clearHistory();
+ fetchMock.removeRoutes();
+});
+
+test('the delete confirmation names the dataset dependents of a connection', async () => {
+ setupMocks({ datasets: [dataset(1, 'qa_orders'), dataset(2, 'qa_users')] });
+ renderDatabaseList();
+
+ const dialog = await openDeleteModal();
+
+ expect(within(dialog).getByText('Affected Datasets')).toBeInTheDocument();
+ expect(within(dialog).getByText('qa_orders')).toBeInTheDocument();
+ expect(within(dialog).getByText('qa_users')).toBeInTheDocument();
+});
+
+test('the delete confirmation says the delete is blocked, not that it will break objects', async () => {
+ // The backend refuses the delete outright while datasets exist, so the
+ // modal must not promise a destructive outcome that cannot happen.
+ setupMocks({ datasets: [dataset(1, 'qa_orders'), dataset(2, 'qa_users')] });
+ renderDatabaseList();
+
+ const dialog = await openDeleteModal();
+
+ expect(
+ within(dialog).getByText(
+ /cannot be deleted because 2 datasets are still attached to it/i,
+ ),
+ ).toBeInTheDocument();
+ expect(
+ within(dialog).queryByText(/will break those objects/i),
+ ).not.toBeInTheDocument();
+});
+
+test('the delete controls stay disabled while datasets block deletion', async () => {
+ setupMocks({ datasets: [dataset(1, 'qa_orders')] });
+ renderDatabaseList();
+
+ const dialog = await openDeleteModal();
+ const confirmationInput = within(dialog).getByLabelText(
+ 'Type "DELETE" to confirm',
+ );
+ const deleteButton = within(dialog).getByTestId('modal-confirm-button');
+
+ expect(confirmationInput).toBeDisabled();
+ expect(deleteButton).toBeDisabled();
+ await userEvent.click(deleteButton);
+ expect(
+ fetchMock.callHistory.calls(
+ new RegExp(`/api/v1/database/${DATABASE_ID}$`),
+ {
+ method: 'DELETE',
+ },
+ ),
+ ).toHaveLength(0);
+});
+
+test('the blocked copy explains how to permanently remove archived datasets', async () => {
+ // Archived datasets still count against the backend delete guard, but do not
+ // appear in the normal dataset list.
+ setupMocks({ datasets: [], datasetCount: 1 });
+ renderDatabaseList();
+
+ const dialog = await openDeleteModal();
+
+ expect(
+ within(dialog).getByText(
+ /open Recently archived and select Delete permanently/i,
+ ),
+ ).toBeInTheDocument();
+});
+
+test('a single dataset dependent is announced in the singular', async () => {
+ setupMocks({ datasets: [dataset(1, 'qa_orders')] });
+ renderDatabaseList();
+
+ const dialog = await openDeleteModal();
+
+ expect(
+ within(dialog).getByText(
+ /cannot be deleted because 1 dataset is still attached to it/i,
+ ),
+ ).toBeInTheDocument();
+});
+
+test('a connection with no datasets keeps the existing dependents copy', async () => {
+ setupMocks({ datasets: [] });
+ renderDatabaseList();
+
+ const dialog = await openDeleteModal();
+
+ expect(
+ within(dialog).getByText(/will break those objects/i),
+ ).toBeInTheDocument();
+ expect(
+ within(dialog).queryByText('Affected Datasets'),
+ ).not.toBeInTheDocument();
+
+ expect(
+ within(dialog).getByLabelText('Type "DELETE" to confirm'),
+ ).toBeEnabled();
+ await userEvent.type(
+ within(dialog).getByLabelText('Type "DELETE" to confirm'),
+ 'DELETE',
+ );
+ expect(within(dialog).getByTestId('modal-confirm-button')).toBeEnabled();
+});
+
+test('datasets the user cannot access are counted but not named', async () => {
+ // The endpoint access-filters the names while leaving the count intact, so
+ // the modal must explain the block using the full count and list only what
+ // came back.
+ setupMocks({ datasets: [dataset(1, 'qa_orders')], datasetCount: 3 });
+ renderDatabaseList();
+
+ const dialog = await openDeleteModal();
+
+ expect(
+ within(dialog).getByText(
+ /cannot be deleted because 3 datasets are still attached to it/i,
+ ),
+ ).toBeInTheDocument();
+ expect(within(dialog).getByText('qa_orders')).toBeInTheDocument();
+ expect(within(dialog).getByText('... and 2 others')).toBeInTheDocument();
+});
+
+test('a fully access-filtered dataset list still explains the block', async () => {
+ // The caller can see the connection but none of its datasets. The count
+ // still has to explain why the delete is refused, without an empty list.
+ setupMocks({ datasets: [], datasetCount: 2 });
+ renderDatabaseList();
+
+ const dialog = await openDeleteModal();
+
+ expect(
+ within(dialog).getByText(
+ /cannot be deleted because 2 datasets are still attached to it/i,
+ ),
+ ).toBeInTheDocument();
+ expect(
+ within(dialog).queryByText('Affected Datasets'),
+ ).not.toBeInTheDocument();
+});
+
+test('the dataset list footer reports dependents beyond the listed page', async () => {
+ setupMocks({
+ datasets: Array.from({ length: 12 }, (_, i) =>
+ dataset(i + 1, `qa_table_${i + 1}`),
+ ),
+ });
+ renderDatabaseList();
+
+ const dialog = await openDeleteModal();
+
+ expect(within(dialog).getByText('qa_table_10')).toBeInTheDocument();
+ expect(within(dialog).queryByText('qa_table_11')).not.toBeInTheDocument();
+ expect(within(dialog).getByText('... and 2 others')).toBeInTheDocument();
+});
diff --git a/superset-frontend/src/pages/DatabaseList/index.tsx b/superset-frontend/src/pages/DatabaseList/index.tsx
index 055ea1fe075..6f6058d1840 100644
--- a/superset-frontend/src/pages/DatabaseList/index.tsx
+++ b/superset-frontend/src/pages/DatabaseList/index.tsx
@@ -101,11 +101,18 @@ interface DatabaseDeleteObject extends DatabaseObject {
charts: any;
dashboards: any;
sqllab_tab_count: number;
+ datasets: {
+ count: number;
+ result: { id: number; table_name: string }[];
+ };
}
/** How many dependent semantic views the delete confirmation lists by name. */
const MAX_DEPENDENT_VIEWS_LISTED = 10;
+/** How many dependent datasets the delete confirmation lists by name. */
+const MAX_DEPENDENT_DATASETS_LISTED = 10;
+
type SemanticLayerDeletePreview =
| { status: 'loading'; item: ConnectionItem }
| {
@@ -187,6 +194,56 @@ function SemanticLayerCascadeWarning({
</>
);
}
+/**
+ * Names the datasets blocking a connection delete.
+ *
+ * ``count`` is every dataset that blocks the delete; ``result`` is only the
+ * subset the caller may see, because the related_objects endpoint
+ * access-filters the names. The two therefore diverge, and the overflow footer
+ * counts from what is actually listed rather than assuming a full page.
+ */
+function DatabaseDatasetDependents({
+ datasets,
+}: {
+ datasets: DatabaseDeleteObject['datasets'];
+}) {
+ const listed = datasets.result.slice(0, MAX_DEPENDENT_DATASETS_LISTED);
+ if (listed.length === 0) {
+ // The count still explains the block in the message above; an empty list
+ // under a heading would only imply the dependents had vanished.
+ return null;
+ }
+ const unlistedCount = datasets.count - listed.length;
+
+ return (
+ <>
+ <h4>{t('Affected Datasets')}</h4>
+ <List
+ split={false}
+ size="small"
+ dataSource={listed}
+ renderItem={(result: { id: number; table_name: string }) => (
+ <List.Item key={result.id} compact>
+ <List.Item.Meta avatar={<span>•</span>} title={result.table_name} />
+ </List.Item>
+ )}
+ footer={
+ unlistedCount > 0 && (
+ <div>
+ {tn(
+ '... and %s other',
+ '... and %s others',
+ unlistedCount,
+ unlistedCount,
+ )}
+ </div>
+ )
+ }
+ />
+ </>
+ );
+}
+
interface DatabaseListProps {
addDangerToast: (msg: string) => void;
addSuccessToast: (msg: string) => void;
@@ -393,6 +450,9 @@ function DatabaseList({
charts: json.charts,
dashboards: json.dashboards,
sqllab_tab_count: json.sqllab_tab_states.count,
+ // Tolerate a backend that predates the datasets block rather than
+ // letting the confirmation crash on it.
+ datasets: json.datasets ?? { count: 0, result: [] },
});
})
.catch(
@@ -1138,16 +1198,40 @@ function DatabaseList({
<DeleteModal
description={
<>
- <p>
- {t('The %s', databaseLabelLower())}{' '}
- <b>{databaseCurrentlyDeleting.database_name}</b>{' '}
- {t(
- 'is linked to %s charts that appear on %s dashboards and users have %s SQL Lab tabs using this database open. Are you sure you want to continue? Deleting the database will break those objects.',
- databaseCurrentlyDeleting.charts.count,
- databaseCurrentlyDeleting.dashboards.count,
- databaseCurrentlyDeleting.sqllab_tab_count,
- )}
- </p>
+ {/* Datasets block the delete outright (the backend refuses while
+ any dataset still references the database), so the dataset
+ case must not promise a destructive outcome that cannot
+ happen -- it has to say the delete is blocked and name what
+ is blocking it. */}
+ {databaseCurrentlyDeleting.datasets.count >= 1 ? (
+ <p>
+ {t('The %s', databaseLabelLower())}{' '}
+ <b>{databaseCurrentlyDeleting.database_name}</b>{' '}
+ {tn(
+ 'cannot be deleted because %s dataset is still attached to it.',
+ 'cannot be deleted because %s datasets are still attached to it.',
+ databaseCurrentlyDeleting.datasets.count,
+ databaseCurrentlyDeleting.datasets.count,
+ )}{' '}
+ {t(
+ 'Delete or move active datasets. To remove archived datasets, open Recently archived and select Delete permanently.',
+ )}
+ </p>
+ ) : (
+ <p>
+ {t('The %s', databaseLabelLower())}{' '}
+ <b>{databaseCurrentlyDeleting.database_name}</b>{' '}
+ {t(
+ 'is linked to %s charts that appear on %s dashboards and users have %s SQL Lab tabs using this database open. Are you sure you want to continue? Deleting the database will break those objects.',
+ databaseCurrentlyDeleting.charts.count,
+ databaseCurrentlyDeleting.dashboards.count,
+ databaseCurrentlyDeleting.sqllab_tab_count,
+ )}
+ </p>
+ )}
+ <DatabaseDatasetDependents
+ datasets={databaseCurrentlyDeleting.datasets}
+ />
{databaseCurrentlyDeleting.dashboards.count >= 1 && (
<>
<h4>{t('Affected Dashboards')}</h4>
@@ -1246,6 +1330,10 @@ function DatabaseList({
}}
onHide={() => setDatabaseCurrentlyDeleting(null)}
open
+ disablePrimaryButton={databaseCurrentlyDeleting.datasets.count >= 1}
+ disableConfirmationInput={
+ databaseCurrentlyDeleting.datasets.count >= 1
+ }
title={
<ModalTitleWithIcon
icon={<Icons.DeleteOutlined />}
diff --git a/superset/daos/database.py b/superset/daos/database.py
index 4f0f2bc3cd4..0c6f215c7ae 100644
--- a/superset/daos/database.py
+++ b/superset/daos/database.py
@@ -18,12 +18,14 @@ from __future__ import annotations
import logging
import re
+from collections.abc import Iterator
from typing import Any
from urllib.parse import unquote
import requests
from flask import current_app as app
-from sqlalchemy.orm import joinedload
+from sqlalchemy import select
+from sqlalchemy.orm import joinedload, Query
try:
from odps import ODPS, options as odps_options
@@ -49,10 +51,34 @@ from superset.utils.ssh_tunnel import unmask_password_info
logger = logging.getLogger(__name__)
+RELATED_DATASET_BATCH_SIZE = 100
+
class DatabaseDAO(BaseDAO[Database]):
base_filter = DatabaseFilter
+ @staticmethod
+ def _related_datasets_query(database_id: int) -> Query[SqlaTable]:
+ return (
+ db.session.query(SqlaTable)
+ .filter(SqlaTable.database_id == database_id)
+ .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+ )
+
+ @classmethod
+ def _iter_related_datasets(cls, database_id: int) -> Iterator[SqlaTable]:
+ """Yield dataset dependents in bounded batches, including archived rows."""
+ last_id: int | None = None
+ while True:
+ query = cls._related_datasets_query(database_id)
+ if last_id is not None:
+ query = query.filter(SqlaTable.id > last_id)
+ batch = query.order_by(SqlaTable.id).limit(RELATED_DATASET_BATCH_SIZE).all()
+ if not batch:
+ return
+ yield from batch
+ last_id = batch[-1].id
+
@classmethod
def create(
cls,
@@ -213,8 +239,9 @@ class DatabaseDAO(BaseDAO[Database]):
@classmethod
def get_related_objects(cls, database_id: int) -> dict[str, Any]:
database: Any = cls.find_by_id(database_id)
- datasets = database.tables
- dataset_ids = [dataset.id for dataset in datasets]
+ dataset_ids = select(SqlaTable.id).where(SqlaTable.database_id == database.id)
+ if is_feature_enabled("SOFT_DELETE"):
+ dataset_ids = dataset_ids.where(SqlaTable.deleted_at.is_(None))
charts = (
db.session.query(Slice)
@@ -240,10 +267,20 @@ class DatabaseDAO(BaseDAO[Database]):
db.session.query(TabState).filter(TabState.database_id == database_id).all()
)
+ # Datasets are dependents in their own right: ``DeleteDatabaseCommand``
+ # refuses to delete a database while any ``SqlaTable`` row references it.
+ # Count with the soft-delete visibility filter bypassed, exactly as that
+ # validation does. Keep the detail query lazy and batched so its API
+ # consumer can stop once it has enough authorized names for the preview.
+ related_dataset_count = cls._related_datasets_query(database_id).count()
+ related_datasets = cls._iter_related_datasets(database_id)
+
return {
"charts": charts,
"dashboards": dashboards,
"sqllab_tab_states": sqllab_tab_states,
+ "datasets": related_datasets,
+ "dataset_count": related_dataset_count,
}
@classmethod
diff --git a/superset/databases/api.py b/superset/databases/api.py
index be972fb38f7..abf537fc22b 100644
--- a/superset/databases/api.py
+++ b/superset/databases/api.py
@@ -148,6 +148,8 @@ from superset.views.filters import BaseFilterRelatedUsers, FilterRelatedUsers
logger = logging.getLogger(__name__)
+MAX_RELATED_DATASETS = 10
+
# pylint: disable=too-many-public-methods
class DatabaseRestApi(BaseSupersetModelRestApi):
@@ -1388,6 +1390,26 @@ class DatabaseRestApi(BaseSupersetModelRestApi):
{"id": tab_state.id, "label": tab_state.label, "active": tab_state.active}
for tab_state in data["sqllab_tab_states"]
]
+ # Names are access-filtered like charts and dashboards above, but the
+ # count is not. This route only requires ``can_read`` on Database, and
+ # ``DatabaseFilter`` admits a caller holding ``datasource_access`` on a
+ # single dataset in the database, so returning every name here would let
+ # them enumerate datasets they hold no permission on. The count has to
+ # stay unfiltered because it is what explains the delete being blocked --
+ # a bare number discloses far less than a name and schema.
+ datasets = []
+ for dataset in data["datasets"]:
+ if not security_manager.can_access_datasource(dataset):
+ continue
+ datasets.append(
+ {
+ "id": dataset.id,
+ "table_name": dataset.table_name,
+ "schema": dataset.schema,
+ }
+ )
+ if len(datasets) == MAX_RELATED_DATASETS:
+ break
return self.response(
200,
charts={"count": len(charts), "result": charts},
@@ -1396,6 +1418,7 @@ class DatabaseRestApi(BaseSupersetModelRestApi):
"count": len(sqllab_tab_states),
"result": sqllab_tab_states,
},
+ datasets={"count": data["dataset_count"], "result": datasets},
)
@expose("/<int:pk>/validate_sql/", methods=("POST",))
diff --git a/superset/databases/schemas.py b/superset/databases/schemas.py
index cb7f92614f8..1e64b31d6ee 100644
--- a/superset/databases/schemas.py
+++ b/superset/databases/schemas.py
@@ -944,9 +944,24 @@ class DatabaseRelatedDashboards(Schema):
)
+class DatabaseRelatedDataset(Schema):
+ id = fields.Integer()
+ table_name = fields.String()
+ schema = fields.String()
+
+
+class DatabaseRelatedDatasets(Schema):
+ count = fields.Integer(metadata={"description": "Dataset count"})
+ result = fields.List(
+ fields.Nested(DatabaseRelatedDataset),
+ metadata={"description": "A list of datasets"},
+ )
+
+
class DatabaseRelatedObjectsResponse(Schema):
charts = fields.Nested(DatabaseRelatedCharts)
dashboards = fields.Nested(DatabaseRelatedDashboards)
+ datasets = fields.Nested(DatabaseRelatedDatasets)
class DatabaseFunctionNamesResponse(Schema):
diff --git a/superset/translations/messages.pot b/superset/translations/messages.pot
index 48452c96d6f..5a5764dc9dd 100644
--- a/superset/translations/messages.pot
+++ b/superset/translations/messages.pot
@@ -1487,6 +1487,9 @@ msgstr ""
msgid "Affected Dashboards"
msgstr ""
+msgid "Affected Datasets"
+msgstr ""
+
msgid "Affected semantic views"
msgstr ""
@@ -5222,6 +5225,11 @@ msgstr ""
msgid "Delete item"
msgstr ""
+msgid ""
+"Delete or move active datasets. To remove archived datasets, open "
+"Recently archived and select Delete permanently."
+msgstr ""
+
msgid "Delete permanently"
msgstr ""
@@ -17972,6 +17980,12 @@ msgstr ""
msgid "by using"
msgstr ""
+#, python-format
+msgid "cannot be deleted because %s dataset is still attached to it."
+msgid_plural "cannot be deleted because %s datasets are still attached to it."
+msgstr[0] ""
+msgstr[1] ""
+
msgid "cannot be empty"
msgstr ""
diff --git a/tests/integration_tests/databases/api_tests.py b/tests/integration_tests/databases/api_tests.py
index 0d9db512ded..e5b7104bffc 100644
--- a/tests/integration_tests/databases/api_tests.py
+++ b/tests/integration_tests/databases/api_tests.py
@@ -4258,6 +4258,9 @@ class TestDatabaseApi(SupersetTestCase):
assert "charts" in rv.json
assert "dashboards" in rv.json
assert "sqllab_tab_states" in rv.json
+ # Datasets block the delete, so the confirmation has to be able to
+ # enumerate them too.
+ assert "datasets" in rv.json
@pytest.mark.sql_json_flow
@pytest.mark.usefixtures("load_birth_names_data")
diff --git a/tests/unit_tests/databases/api_test.py b/tests/unit_tests/databases/api_test.py
index bc77c10b0c0..7bb92a4bf39 100644
--- a/tests/unit_tests/databases/api_test.py
+++ b/tests/unit_tests/databases/api_test.py
@@ -2747,3 +2747,120 @@ def test_import_includes_configuration_method(
f"'configuration_method' not found in database list response: {db_obj_api}"
)
assert db_obj_api["configuration_method"] == "dynamic_form"
+
+
+def test_related_objects_includes_datasets(
+ session: Session,
+ client: Any,
+ full_api_access: None,
+) -> None:
+ """The delete confirmation reads its dependents from this endpoint.
+
+ ``DeleteDatabaseCommand`` refuses to delete a database while any dataset
+ references it, so a response without a datasets block leaves the modal
+ reporting no dependents for a database that cannot be deleted.
+ """
+ from superset.connectors.sqla.models import SqlaTable
+ from superset.databases.api import DatabaseRestApi
+ from superset.models.core import Database
+
+ DatabaseRestApi.datamodel._session = session
+
+ SqlaTable.metadata.create_all(session.get_bind()) # pylint: disable=no-member
+
+ database = Database(database_name="related_db", sqlalchemy_uri="sqlite://")
+ db.session.add(database)
+ db.session.add(SqlaTable(table_name="qa_orders", database=database))
+ db.session.commit()
+
+ response = client.get(f"/api/v1/database/{database.id}/related_objects/")
+ assert response.status_code == 200
+
+ payload = response.json
+ assert payload["datasets"]["count"] == 1
+ assert payload["datasets"]["result"][0]["table_name"] == "qa_orders"
+
+
+def test_related_objects_datasets_filtered_by_access(
+ mocker: MockerFixture,
+ session: Session,
+ client: Any,
+ full_api_access: None,
+) -> None:
+ """Dataset names are access-filtered; the blocking count is not.
+
+ This route only requires ``can_read`` on Database, and ``DatabaseFilter``
+ admits a caller holding ``datasource_access`` on a single dataset in the
+ database. Returning every dataset name would let such a caller enumerate
+ datasets they hold no permission on. The count stays unfiltered because it
+ is what explains the delete being blocked, and a bare number discloses far
+ less than a name and schema.
+ """
+ from superset.connectors.sqla.models import SqlaTable
+ from superset.databases.api import DatabaseRestApi
+ from superset.extensions import security_manager
+ from superset.models.core import Database
+
+ DatabaseRestApi.datamodel._session = session
+
+ SqlaTable.metadata.create_all(session.get_bind()) # pylint: disable=no-member
+
+ database = Database(database_name="mixed_access_db", sqlalchemy_uri="sqlite://")
+ db.session.add(database)
+ db.session.add(SqlaTable(table_name="visible", database=database))
+ db.session.add(SqlaTable(table_name="secret", database=database))
+ db.session.commit()
+
+ mocker.patch.object(
+ security_manager,
+ "can_access_datasource",
+ side_effect=lambda datasource: datasource.table_name == "visible",
+ )
+
+ response = client.get(f"/api/v1/database/{database.id}/related_objects/")
+ assert response.status_code == 200
+
+ payload = response.json
+ # Both datasets block the delete, so both are counted...
+ assert payload["datasets"]["count"] == 2
+ # ...but only the accessible one is named.
+ assert [d["table_name"] for d in payload["datasets"]["result"]] == ["visible"]
+
+
+def test_related_objects_limits_dataset_details(
+ mocker: MockerFixture,
+ session: Session,
+ client: Any,
+ full_api_access: None,
+) -> None:
+ """The response returns only the dataset details the modal can display."""
+ from superset.connectors.sqla.models import SqlaTable
+ from superset.databases.api import DatabaseRestApi, MAX_RELATED_DATASETS
+ from superset.extensions import security_manager
+ from superset.models.core import Database
+
+ DatabaseRestApi.datamodel._session = session
+
+ SqlaTable.metadata.create_all(session.get_bind()) # pylint: disable=no-member
+
+ database = Database(database_name="large_related_db", sqlalchemy_uri="sqlite://")
+ db.session.add(database)
+ db.session.add_all(
+ SqlaTable(table_name=f"table_{index:02}", database=database)
+ for index in range(MAX_RELATED_DATASETS + 2)
+ )
+ db.session.commit()
+
+ can_access = mocker.patch.object(
+ security_manager,
+ "can_access_datasource",
+ return_value=True,
+ )
+
+ response = client.get(f"/api/v1/database/{database.id}/related_objects/")
+ assert response.status_code == 200
+
+ payload = response.json["datasets"]
+ assert payload["count"] == MAX_RELATED_DATASETS + 2
+ assert len(payload["result"]) == MAX_RELATED_DATASETS
+ assert can_access.call_count == MAX_RELATED_DATASETS
diff --git a/tests/unit_tests/databases/dao/related_objects_test.py b/tests/unit_tests/databases/dao/related_objects_test.py
new file mode 100644
index 00000000000..8fc5bb84ab4
--- /dev/null
+++ b/tests/unit_tests/databases/dao/related_objects_test.py
@@ -0,0 +1,122 @@
+# 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.
+
+"""Datasets are dependents of a database, so the delete confirmation's preview
+has to enumerate them.
+
+``DeleteDatabaseCommand.validate`` blocks the delete whenever any ``SqlaTable``
+row references the database, but ``get_related_objects`` used to return only
+charts, dashboards and SQL Lab tabs -- so the modal could report zero dependents
+for a database that cannot be deleted at all. These tests pin the datasets block
+and, crucially, that it is counted the same way ``validate`` counts: with the
+soft-delete visibility filter bypassed.
+"""
+
+from datetime import datetime
+
+from pytest_mock import MockerFixture
+from sqlalchemy.orm.session import Session
+
+
+def test_get_related_objects_includes_live_datasets(
+ mocker: MockerFixture,
+ session: Session,
+) -> None:
+ """A live dataset is surfaced so the modal can name it before deleting."""
+ from superset import db
+ from superset.connectors.sqla.models import SqlaTable
+ from superset.daos.database import DatabaseDAO
+ from superset.models.core import Database
+
+ SqlaTable.metadata.create_all(session.get_bind())
+
+ database = Database(database_name="related_db", sqlalchemy_uri="sqlite://")
+ dataset = SqlaTable(table_name="qa_orders", database=database)
+ db.session.add_all([database, dataset])
+ db.session.flush()
+
+ # ``find_by_id`` applies the database base filter, which needs a request
+ # user; the dataset lookup under test is independent of it.
+ mocker.patch.object(DatabaseDAO, "find_by_id", return_value=database)
+
+ related = DatabaseDAO.get_related_objects(database.id)
+
+ assert related["dataset_count"] == 1
+ assert [table.table_name for table in related["datasets"]] == ["qa_orders"]
+
+
+def test_get_related_objects_includes_soft_deleted_datasets(
+ mocker: MockerFixture,
+ session: Session,
+) -> None:
+ """The preview must agree with the delete gate.
+
+ A soft-deleted dataset still FK-references the database and still blocks
+ ``DeleteDatabaseCommand.validate``. If the preview hid it, the modal would
+ show zero dataset dependents and the delete would fail anyway -- the exact
+ dependent-blind case this block exists to prevent.
+ """
+ from superset import db
+ from superset.connectors.sqla.models import SqlaTable
+ from superset.daos.database import DatabaseDAO
+ from superset.models.core import Database
+
+ SqlaTable.metadata.create_all(session.get_bind())
+
+ database = Database(database_name="hidden_db", sqlalchemy_uri="sqlite://")
+ soft_deleted = SqlaTable(
+ table_name="gone",
+ database=database,
+ deleted_at=datetime(2026, 1, 1, 12, 0, 0),
+ )
+ db.session.add_all([database, soft_deleted])
+ db.session.flush()
+
+ # ``find_by_id`` applies the database base filter, which needs a request
+ # user; the dataset lookup under test is independent of it.
+ mocker.patch.object(DatabaseDAO, "find_by_id", return_value=database)
+
+ related = DatabaseDAO.get_related_objects(database.id)
+
+ assert related["dataset_count"] == 1
+ assert [table.table_name for table in related["datasets"]] == ["gone"]
+
+
+def test_get_related_objects_without_datasets(
+ mocker: MockerFixture,
+ session: Session,
+) -> None:
+ """No datasets means an empty block, not a missing key."""
+ from superset import db
+ from superset.connectors.sqla.models import SqlaTable
+ from superset.daos.database import DatabaseDAO
+ from superset.models.core import Database
+
+ SqlaTable.metadata.create_all(session.get_bind())
+
+ database = Database(database_name="empty_related_db", sqlalchemy_uri="sqlite://")
+ db.session.add(database)
+ db.session.flush()
+
+ # ``find_by_id`` applies the database base filter, which needs a request
+ # user; the dataset lookup under test is independent of it.
+ mocker.patch.object(DatabaseDAO, "find_by_id", return_value=database)
+
+ related = DatabaseDAO.get_related_objects(database.id)
+
+ assert related["dataset_count"] == 0
+ assert list(related["datasets"]) == []