This is an automated email from the ASF dual-hosted git repository. villebro pushed a commit to branch 7.0 in repository https://gitbox.apache.org/repos/asf/superset.git
commit 943cc5440117551504f783d76ffc9a592eff2c9f Author: Mike Bridge <[email protected]> AuthorDate: Fri Nov 6 12:33:13 2026 -0600 fix(chart): include semantic views in datasource filter (#46021) (cherry picked from commit 5abdb20986d52a3a63cd5d34cbb6555a4bf7a415) --- .../creating-your-first-dashboard.mdx | 5 + superset-frontend/src/components/ListView/types.ts | 1 + .../src/pages/ChartList/ChartList.test.tsx | 87 +++++++++++++++- .../src/pages/ChartList/ChartList.testHelpers.tsx | 6 +- superset-frontend/src/pages/ChartList/index.tsx | 23 ++++- superset/charts/api.py | 2 + superset/charts/filters.py | 42 +++++++- tests/unit_tests/charts/test_filters.py | 109 +++++++++++++++++++++ 8 files changed, 270 insertions(+), 5 deletions(-) diff --git a/docs/docs/using-superset/creating-your-first-dashboard.mdx b/docs/docs/using-superset/creating-your-first-dashboard.mdx index 5ee81e3ba27..37c0409eae9 100644 --- a/docs/docs/using-superset/creating-your-first-dashboard.mdx +++ b/docs/docs/using-superset/creating-your-first-dashboard.mdx @@ -165,6 +165,11 @@ You can also certify metrics if you'd like for your team in this view. - [Blog: Unlocking the Power of Virtual Datasets](https://preset.io/blog/unlocking-the-power-of-virtual-datasets-in-apache-superset/) ::: +### Finding charts by semantic view + +With Semantic Layers enabled, the **Datasource** filter on the Charts list includes +semantic views as well as datasets. Select a view to find charts built from it. + ### Native filters on semantic views When the `SEMANTIC_LAYERS` feature flag is enabled, Superset can connect to external semantic layers diff --git a/superset-frontend/src/components/ListView/types.ts b/superset-frontend/src/components/ListView/types.ts index 571b02306f3..387b0762c90 100644 --- a/superset-frontend/src/components/ListView/types.ts +++ b/superset-frontend/src/components/ListView/types.ts @@ -127,6 +127,7 @@ export enum ListViewFilterOperator { NameOrDescription = 'name_or_description', AllText = 'all_text', ChartAllText = 'chart_all_text', + ChartDatasource = 'chart_datasource', DatasetIsNullOrEmpty = 'dataset_is_null_or_empty', Between = 'between', DashboardIsFav = 'dashboard_is_favorite', diff --git a/superset-frontend/src/pages/ChartList/ChartList.test.tsx b/superset-frontend/src/pages/ChartList/ChartList.test.tsx index f5e557b9bba..843f7ce553d 100644 --- a/superset-frontend/src/pages/ChartList/ChartList.test.tsx +++ b/superset-frontend/src/pages/ChartList/ChartList.test.tsx @@ -17,13 +17,15 @@ * under the License. */ import fetchMock from 'fetch-mock'; +import rison from 'rison'; import { screen, waitFor, fireEvent, + userEvent, within, } from 'spec/helpers/testing-library'; -import { isFeatureEnabled } from '@superset-ui/core'; +import { FeatureFlag, isFeatureEnabled } from '@superset-ui/core'; import { API_ENDPOINTS, mockCharts, @@ -318,6 +320,89 @@ describe('ChartList - Global Filter Interactions', () => { }); }); + test('Datasource filter offers semantic views and sends their typed identity', async () => { + ( + isFeatureEnabled as jest.MockedFunction<typeof isFeatureEnabled> + ).mockImplementation(flag => flag === FeatureFlag.SemanticLayers); + fetchMock.removeRoutes({ names: [API_ENDPOINTS.CATCH_ALL] }); + fetchMock.get('glob:*/api/v1/datasource/?q=*', { + result: [ + { id: 7, table_name: 'orders', kind: 'physical' }, + { id: 7, table_name: 'orders', kind: 'semantic_view' }, + ], + count: 2, + }); + + renderChartList(mockUser); + await screen.findByTestId('listview-table'); + await userEvent.click(findFilterByLabel('Datasource')!); + await userEvent.type(screen.getByPlaceholderText('Search'), 'orders'); + await waitFor(() => + expect( + fetchMock.callHistory.calls().some(call => { + if (!call.url.includes('/api/v1/datasource/?q=')) return false; + const query = rison.decode( + decodeURIComponent(call.url.split('?q=')[1]), + ) as { filters: Array<{ col: string; opr: string; value: string }> }; + return query.filters.some( + filter => + filter.col === 'table_name' && + filter.opr === 'ct' && + filter.value === 'orders', + ); + }), + ).toBe(true), + ); + await waitFor(() => + expect( + screen.queryAllByRole('option').map(option => option.textContent), + ).toContain('orders (Semantic View)'), + ); + const semanticOption = await screen.findByRole('option', { + name: 'orders (Semantic View)', + }); + expect( + screen.getByRole('option', { name: 'orders (Dataset)' }), + ).toBeInTheDocument(); + await userEvent.click(semanticOption); + + await waitFor(() => { + const chartCalls = fetchMock.callHistory + .calls() + .filter(call => call.url.includes('/api/v1/chart/?')); + const query = rison.decode( + decodeURIComponent(chartCalls.at(-1)!.url.split('?q=')[1]), + ) as { filters: Array<{ col: string; opr: string; value: string }> }; + expect(query.filters).toContainEqual({ + col: 'datasource_id', + opr: 'chart_datasource', + value: '7__semantic_view', + }); + }); + }); + + test('Dataset filter keeps the dataset-only endpoint when semantic layers are off', async () => { + ( + isFeatureEnabled as jest.MockedFunction<typeof isFeatureEnabled> + ).mockReturnValue(false); + renderChartList(mockUser); + await screen.findByTestId('listview-table'); + await userEvent.click(findFilterByLabel('Dataset')!); + + await waitFor(() => + expect( + fetchMock.callHistory + .calls() + .some(call => call.url.includes('/api/v1/dataset/?q=')), + ).toBe(true), + ); + expect( + fetchMock.callHistory + .calls() + .some(call => call.url.includes('/api/v1/datasource/?q=')), + ).toBe(false); + }); + test('renders Tags filter when TAGGING_SYSTEM is enabled', async () => { // Mock feature flag to enable tags ( diff --git a/superset-frontend/src/pages/ChartList/ChartList.testHelpers.tsx b/superset-frontend/src/pages/ChartList/ChartList.testHelpers.tsx index 0cc59b2915d..9a56f1b0828 100644 --- a/superset-frontend/src/pages/ChartList/ChartList.testHelpers.tsx +++ b/superset-frontend/src/pages/ChartList/ChartList.testHelpers.tsx @@ -346,5 +346,9 @@ export const setupMocks = ( count: 0, }); - fetchMock.get(API_ENDPOINTS.CATCH_ALL, { result: [], count: 0 }); + fetchMock.get( + API_ENDPOINTS.CATCH_ALL, + { result: [], count: 0 }, + { name: API_ENDPOINTS.CATCH_ALL }, + ); }; diff --git a/superset-frontend/src/pages/ChartList/index.tsx b/superset-frontend/src/pages/ChartList/index.tsx index 7d2f90f4bff..4f811176fd8 100644 --- a/superset-frontend/src/pages/ChartList/index.tsx +++ b/superset-frontend/src/pages/ChartList/index.tsx @@ -92,6 +92,7 @@ import { QueryObjectColumns } from 'src/views/CRUD/types'; import { WIDER_DROPDOWN_WIDTH } from 'src/components/ListView/utils'; import { Tag } from 'src/components/Tag'; import { datasetLabel } from 'src/features/semanticLayers/label'; +import { fetchDatasourceList } from 'src/features/datasets/fetchDatasourceList'; import { isUserEditorOrAdmin } from 'src/dashboard/util/permissionUtils'; import type { CellProps } from 'react-table'; @@ -206,6 +207,24 @@ const createFetchDatasets = async ( page: number, pageSize: number, ) => { + if (isFeatureEnabled(FeatureFlag.SemanticLayers)) { + const { result, count } = await fetchDatasourceList( + filterValue, + page, + pageSize, + ); + return { + data: result.map(({ id, kind, table_name: tableName }) => { + const semanticView = kind === 'semantic_view'; + return { + label: `${tableName} (${semanticView ? t('Semantic View') : t('Dataset')})`, + value: `${id}__${semanticView ? 'semantic_view' : 'table'}`, + }; + }), + totalCount: count, + }; + } + // add filters if filterValue const filters = filterValue ? { filters: [{ col: 'table_name', opr: 'sw', value: filterValue }] } @@ -821,7 +840,9 @@ function ChartList(props: ChartListProps) { key: 'dataset', id: 'datasource_id', input: 'select', - operator: FilterOperator.Equals, + operator: isFeatureEnabled(FeatureFlag.SemanticLayers) + ? FilterOperator.ChartDatasource + : FilterOperator.Equals, unfilteredLabel: t('All'), fetchSelects: createFetchDatasets, paginate: true, diff --git a/superset/charts/api.py b/superset/charts/api.py index 1e35f67140e..76f317c4041 100644 --- a/superset/charts/api.py +++ b/superset/charts/api.py @@ -53,6 +53,7 @@ from superset.charts.filters import ( ChartAllTextFilter, ChartCertifiedFilter, ChartCreatedByMeFilter, + ChartDatasourceFilter, ChartDeletedRecencyFilter, ChartDeletedStateFilter, ChartEditableFilter, @@ -356,6 +357,7 @@ class ChartRestApi(SoftDeleteApiMixin, BaseSupersetModelRestApi): ChartOwnedCreatedFavoredByMeFilter, ], "slice_name": [ChartAllTextFilter], + "datasource_id": [ChartDatasourceFilter], "created_by": [ChartHasCreatedByFilter, ChartCreatedByMeFilter], "tags": [ChartTagNameFilter, ChartTagIdFilter], } diff --git a/superset/charts/filters.py b/superset/charts/filters.py index 203ccb79d61..a3e48f37db0 100644 --- a/superset/charts/filters.py +++ b/superset/charts/filters.py @@ -14,11 +14,11 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. -from typing import Any +from typing import Any, ClassVar from flask import current_app from flask_babel import lazy_gettext as _ -from sqlalchemy import and_, or_ +from sqlalchemy import and_, false, or_ from sqlalchemy.orm import aliased from sqlalchemy.orm.query import Query from sqlalchemy.sql.elements import ColumnElement @@ -67,6 +67,44 @@ class ChartAllTextFilter(BaseFilter): # pylint: disable=too-few-public-methods ) +class ChartDatasourceFilter(BaseFilter): # pylint: disable=too-few-public-methods + """Match a chart's datasource by both type and ID.""" + + name: ClassVar[str] = _("Datasource") + arg_name: ClassVar[str] = "chart_datasource" + + def apply(self, query: Query, value: object) -> Query: + """Keep malformed identities from widening the chart list.""" + # Saved Charts URLs used integer dataset IDs before typed identities. + if isinstance(value, int) and not isinstance(value, bool): + value = f"{value}__table" + if not isinstance(value, str): + return query.filter(false()) + + parts: list[str] = value.split("__") + if ( + len(parts) != 2 + or parts[1] not in {"table", "semantic_view"} + or not parts[0].isascii() + or not parts[0].isdigit() + ): + return query.filter(false()) + + try: + datasource_id: int = int(parts[0]) + except ValueError: + return query.filter(false()) + if datasource_id > 2**63 - 1: + return query.filter(false()) + + return query.filter( + and_( + self.model.datasource_id == datasource_id, + self.model.datasource_type == parts[1], + ) + ) + + class ChartFavoriteFilter(BaseFavoriteFilter): # pylint: disable=too-few-public-methods """ Custom filter for the GET list that filters all charts that a user has favored diff --git a/tests/unit_tests/charts/test_filters.py b/tests/unit_tests/charts/test_filters.py index 7c560cad1e2..0db9271bf83 100644 --- a/tests/unit_tests/charts/test_filters.py +++ b/tests/unit_tests/charts/test_filters.py @@ -20,9 +20,118 @@ from typing import Any from unittest.mock import MagicMock +import prison import pytest +from flask.testing import FlaskClient from pytest_mock import MockerFixture from sqlalchemy import create_engine +from sqlalchemy.orm import Session +from werkzeug.test import TestResponse + +from tests.unit_tests.conftest import with_feature_flags + + [email protected]("datasource_type", ["table", "semantic_view"]) +def test_chart_datasource_filter_matches_id_and_type(datasource_type: str) -> None: + """Same-numbered tables and semantic views must remain distinct.""" + from superset.charts.filters import ChartDatasourceFilter + from superset.models.slice import Slice + + query: MagicMock = MagicMock() + filt: ChartDatasourceFilter = ChartDatasourceFilter.__new__(ChartDatasourceFilter) + filt.model = Slice + + filt.apply(query, f"7__{datasource_type}") + + clause: Any = query.filter.call_args.args[0] + compiled: str = str( + clause.compile( + create_engine("sqlite://"), compile_kwargs={"literal_binds": True} + ) + ) + assert "datasource_id = 7" in compiled + assert f"datasource_type = '{datasource_type}'" in compiled + + [email protected]( + "identity", + [ + "7__unknown", + "-7__table", + "7__table__extra", + "99999999999999999999__table", + None, + True, + -7, + 7.0, + ], +) +def test_chart_datasource_filter_rejects_malformed_identity(identity: object) -> None: + """Malformed filter values must not turn into an unfiltered chart list.""" + from superset.charts.filters import ChartDatasourceFilter + from superset.models.slice import Slice + + query: MagicMock = MagicMock() + filt: ChartDatasourceFilter = ChartDatasourceFilter.__new__(ChartDatasourceFilter) + filt.model = Slice + + filt.apply(query, identity) + + clause: Any = query.filter.call_args.args[0] + compiled: str = str( + clause.compile( + create_engine("sqlite://"), compile_kwargs={"literal_binds": True} + ) + ) + assert compiled == "0" + + [email protected]( + "identity, expected", + [ + (7, "table chart"), + ("7__table", "table chart"), + ("7__semantic_view", "semantic chart"), + ], +) +@with_feature_flags(SEMANTIC_LAYERS=True) +def test_chart_list_datasource_identity( + client: FlaskClient, + full_api_access: None, + mocker: MockerFixture, + session: Session, + identity: int | str, + expected: str, +) -> None: + """The registered list operator separates same-ID sources and accepts old links.""" + # Avoid app-init imports: models and API registration need the app fixture. + from superset.charts.api import ChartRestApi + from superset.models.slice import Slice + + mocker.patch.object(ChartRestApi.datamodel, "_session", session) + mocker.patch( + "superset.security_manager.can_access_all_datasources", return_value=True + ) + Slice.metadata.create_all(session.get_bind()) + table_chart: Slice = Slice( + slice_name="table chart", datasource_id=7, datasource_type="table" + ) + semantic_chart: Slice = Slice( + slice_name="semantic chart", datasource_id=7, datasource_type="semantic_view" + ) + session.add_all([table_chart, semantic_chart]) + session.flush() + query: str = prison.dumps( + { + "columns": ["id", "slice_name"], + "filters": [ + {"col": "datasource_id", "opr": "chart_datasource", "value": identity} + ], + } + ) + response: TestResponse = client.get("/api/v1/chart/", query_string={"q": query}) + assert response.status_code == 200 + assert [row["slice_name"] for row in response.json["result"]] == [expected] def test_chart_filter_scopes_guest_to_token_dashboards(mocker: MockerFixture) -> None:
