You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by be...@apache.org on 2026/04/24 14:29:12 UTC
(superset) branch edit-modal created (now 04e768f9473)
This is an automated email from the ASF dual-hosted git repository.
betodealmeida pushed a change to branch edit-modal
in repository https://gitbox.apache.org/repos/asf/superset.git
at 04e768f9473 Fix padding
This branch includes the following new commits:
new 9a237e4af97 feat(semantic layers): edit modal for semantic views
new 04e768f9473 Fix padding
The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(superset) 02/02: Fix padding
Posted by be...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
betodealmeida pushed a commit to branch edit-modal
in repository https://gitbox.apache.org/repos/asf/superset.git
commit 04e768f9473874477b0682909563815d596d6024
Author: Beto Dealmeida <ro...@dealmeida.net>
AuthorDate: Fri Apr 24 10:28:39 2026 -0400
Fix padding
---
.../features/semanticLayers/SemanticLayerModal.tsx | 91 +++++++++--------
.../semanticViews/SemanticViewEditModal.tsx | 109 +++++++++++----------
2 files changed, 106 insertions(+), 94 deletions(-)
diff --git a/superset-frontend/src/features/semanticLayers/SemanticLayerModal.tsx b/superset-frontend/src/features/semanticLayers/SemanticLayerModal.tsx
index 2f0d2ebd174..0193f296488 100644
--- a/superset-frontend/src/features/semanticLayers/SemanticLayerModal.tsx
+++ b/superset-frontend/src/features/semanticLayers/SemanticLayerModal.tsx
@@ -31,6 +31,7 @@ import {
MODAL_STANDARD_WIDTH,
MODAL_MEDIUM_WIDTH,
} from 'src/components/Modal';
+import { styled } from '@apache-superset/core/theme';
import {
renderers,
sanitizeSchema,
@@ -41,6 +42,10 @@ import {
SCHEMA_REFRESH_DEBOUNCE_MS,
} from './jsonFormsHelpers';
+const ModalContent = styled.div`
+ padding: ${({ theme }) => theme.sizeUnit * 4}px;
+`;
+
type Step = 'type' | 'config';
type ValidationMode = 'ValidateAndHide' | 'ValidateAndShow';
@@ -336,8 +341,8 @@ export default function SemanticLayerModal({
saveLoading={saving}
contentLoading={loading}
>
- {step === 'type' ? (
- <>
+ <ModalContent>
+ {step === 'type' ? (
<ModalFormField label={t('Type')}>
<Select
ariaLabel={t('Semantic layer type')}
@@ -356,48 +361,48 @@ export default function SemanticLayerModal({
}}
/>
</ModalFormField>
- </>
- ) : (
- <>
- {!isEditMode && (
- <Button
- buttonStyle="link"
- icon={<Icons.CaretLeftOutlined iconSize="s" />}
- onClick={handleBack}
- >
- {t('Back')}
- </Button>
- )}
- <ModalFormField label={t('Name')} required>
- <Input
- value={name}
- onChange={e => setName(e.target.value)}
- placeholder={t('Name of the semantic layer')}
- />
- </ModalFormField>
- {configSchema && (
- // Wrap in a form with autocomplete="off" so browsers do not
- // autofill credential fields (service token, account, etc.).
- // eslint-disable-next-line jsx-a11y/no-redundant-roles
- <form
- role="presentation"
- autoComplete="off"
- onSubmit={e => e.preventDefault()}
- >
- <JsonForms
- schema={configSchema}
- uischema={uiSchema}
- data={formData}
- renderers={renderers}
- cells={cellRegistryEntries}
- config={{ refreshingSchema, formData }}
- validationMode={validationMode}
- onChange={handleFormChange}
+ ) : (
+ <>
+ {!isEditMode && (
+ <Button
+ buttonStyle="link"
+ icon={<Icons.CaretLeftOutlined iconSize="s" />}
+ onClick={handleBack}
+ >
+ {t('Back')}
+ </Button>
+ )}
+ <ModalFormField label={t('Name')} required>
+ <Input
+ value={name}
+ onChange={e => setName(e.target.value)}
+ placeholder={t('Name of the semantic layer')}
/>
- </form>
- )}
- </>
- )}
+ </ModalFormField>
+ {configSchema && (
+ // Wrap in a form with autocomplete="off" so browsers do not
+ // autofill credential fields (service token, account, etc.).
+ // eslint-disable-next-line jsx-a11y/no-redundant-roles
+ <form
+ role="presentation"
+ autoComplete="off"
+ onSubmit={e => e.preventDefault()}
+ >
+ <JsonForms
+ schema={configSchema}
+ uischema={uiSchema}
+ data={formData}
+ renderers={renderers}
+ cells={cellRegistryEntries}
+ config={{ refreshingSchema, formData }}
+ validationMode={validationMode}
+ onChange={handleFormChange}
+ />
+ </form>
+ )}
+ </>
+ )}
+ </ModalContent>
</StandardModal>
);
}
diff --git a/superset-frontend/src/features/semanticViews/SemanticViewEditModal.tsx b/superset-frontend/src/features/semanticViews/SemanticViewEditModal.tsx
index 572051cbbf8..148fb96885a 100644
--- a/superset-frontend/src/features/semanticViews/SemanticViewEditModal.tsx
+++ b/superset-frontend/src/features/semanticViews/SemanticViewEditModal.tsx
@@ -28,12 +28,17 @@ import {
TableSize,
} from '@superset-ui/core/components/Table';
import { Alert } from '@apache-superset/core/components';
+import { styled } from '@apache-superset/core/theme';
import {
StandardModal,
ModalFormField,
MODAL_LARGE_WIDTH,
} from 'src/components/Modal';
+const ModalContent = styled.div`
+ padding: ${({ theme }) => theme.sizeUnit * 4}px;
+`;
+
type InputNumberValue = number | null;
interface SemanticDimension {
@@ -176,59 +181,61 @@ export default function SemanticViewEditModal({
saveLoading={saving}
contentLoading={structureLoading}
>
- <Tabs>
- <Tabs.TabPane tab={t('Details')} key="details">
- <ModalFormField label={t('Description')}>
- <Input.TextArea
- value={description}
- onChange={e => setDescription(e.target.value)}
- rows={4}
+ <ModalContent>
+ <Tabs>
+ <Tabs.TabPane tab={t('Details')} key="details">
+ <ModalFormField label={t('Description')}>
+ <Input.TextArea
+ value={description}
+ onChange={e => setDescription(e.target.value)}
+ rows={4}
+ />
+ </ModalFormField>
+ <ModalFormField label={t('Cache timeout')}>
+ <InputNumber
+ value={cacheTimeout}
+ onChange={value => setCacheTimeout(value as InputNumberValue)}
+ min={0}
+ placeholder={t('Duration in seconds')}
+ style={{ width: '100%' }}
+ />
+ </ModalFormField>
+ </Tabs.TabPane>
+ <Tabs.TabPane
+ tab={t('Dimensions (%s)', dimensions.length)}
+ key="dimensions"
+ >
+ <Alert
+ type="info"
+ message={STRUCTURE_INFO_MESSAGE}
+ showIcon
+ css={{ marginBottom: 16 }}
+ />
+ <Table<SemanticDimension>
+ data={dimensions}
+ columns={DIMENSION_COLUMNS}
+ size={TableSize.Small}
+ rowKey="name"
+ usePagination={false}
+ />
+ </Tabs.TabPane>
+ <Tabs.TabPane tab={t('Metrics (%s)', metrics.length)} key="metrics">
+ <Alert
+ type="info"
+ message={STRUCTURE_INFO_MESSAGE}
+ showIcon
+ css={{ marginBottom: 16 }}
/>
- </ModalFormField>
- <ModalFormField label={t('Cache timeout')}>
- <InputNumber
- value={cacheTimeout}
- onChange={value => setCacheTimeout(value as InputNumberValue)}
- min={0}
- placeholder={t('Duration in seconds')}
- style={{ width: '100%' }}
+ <Table<SemanticMetric>
+ data={metrics}
+ columns={METRIC_COLUMNS}
+ size={TableSize.Small}
+ rowKey="name"
+ usePagination={false}
/>
- </ModalFormField>
- </Tabs.TabPane>
- <Tabs.TabPane
- tab={t('Dimensions (%s)', dimensions.length)}
- key="dimensions"
- >
- <Alert
- type="info"
- message={STRUCTURE_INFO_MESSAGE}
- showIcon
- css={{ marginBottom: 16 }}
- />
- <Table<SemanticDimension>
- data={dimensions}
- columns={DIMENSION_COLUMNS}
- size={TableSize.Small}
- rowKey="name"
- usePagination={false}
- />
- </Tabs.TabPane>
- <Tabs.TabPane tab={t('Metrics (%s)', metrics.length)} key="metrics">
- <Alert
- type="info"
- message={STRUCTURE_INFO_MESSAGE}
- showIcon
- css={{ marginBottom: 16 }}
- />
- <Table<SemanticMetric>
- data={metrics}
- columns={METRIC_COLUMNS}
- size={TableSize.Small}
- rowKey="name"
- usePagination={false}
- />
- </Tabs.TabPane>
- </Tabs>
+ </Tabs.TabPane>
+ </Tabs>
+ </ModalContent>
</StandardModal>
);
}
(superset) 01/02: feat(semantic layers): edit modal for semantic views
Posted by be...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
betodealmeida pushed a commit to branch edit-modal
in repository https://gitbox.apache.org/repos/asf/superset.git
commit 9a237e4af97e2dddb22b59619e5ae8794931221a
Author: Beto Dealmeida <ro...@dealmeida.net>
AuthorDate: Fri Apr 24 10:10:45 2026 -0400
feat(semantic layers): edit modal for semantic views
---
.../semanticViews/SemanticViewEditModal.test.tsx | 172 +++++++++++++++++++++
.../semanticViews/SemanticViewEditModal.tsx | 151 +++++++++++++++---
superset/semantic_layers/api.py | 77 ++++++++-
tests/unit_tests/semantic_layers/api_test.py | 152 ++++++++++++++++++
4 files changed, 532 insertions(+), 20 deletions(-)
diff --git a/superset-frontend/src/features/semanticViews/SemanticViewEditModal.test.tsx b/superset-frontend/src/features/semanticViews/SemanticViewEditModal.test.tsx
index 0e80c9e6e7c..20d5c7e3566 100644
--- a/superset-frontend/src/features/semanticViews/SemanticViewEditModal.test.tsx
+++ b/superset-frontend/src/features/semanticViews/SemanticViewEditModal.test.tsx
@@ -27,13 +27,44 @@ jest.mock('@superset-ui/core', () => ({
SupersetClient: {
...jest.requireActual('@superset-ui/core').SupersetClient,
put: jest.fn(),
+ get: jest.fn(),
},
getClientErrorObject: jest.fn(() => Promise.resolve({ error: '' })),
}));
const mockedPut = SupersetClient.put as jest.Mock;
+const mockedGet = SupersetClient.get as jest.Mock;
const mockedGetClientErrorObject = getClientErrorObject as jest.Mock;
+const MOCK_STRUCTURE = {
+ result: {
+ dimensions: [
+ {
+ name: 'order_date',
+ type: 'timestamp[us]',
+ definition: 'ordered_at',
+ description: 'Date of the order',
+ grain: 'Day',
+ },
+ {
+ name: 'customer_id',
+ type: 'int64',
+ definition: null,
+ description: null,
+ grain: null,
+ },
+ ],
+ metrics: [
+ {
+ name: 'orders',
+ type: 'double',
+ definition: 'SIMPLE',
+ description: 'Order count',
+ },
+ ],
+ },
+};
+
const createProps = () => ({
show: true,
onHide: jest.fn(),
@@ -50,8 +81,10 @@ const createProps = () => ({
beforeEach(() => {
mockedPut.mockReset();
+ mockedGet.mockReset();
mockedGetClientErrorObject.mockReset();
mockedGetClientErrorObject.mockResolvedValue({ error: '' });
+ mockedGet.mockResolvedValue({ json: MOCK_STRUCTURE });
});
test('saves semantic view and refreshes list', async () => {
@@ -60,6 +93,15 @@ test('saves semantic view and refreshes list', async () => {
render(<SemanticViewEditModal {...props} />);
+ // Wait for structure fetch to complete so save button is enabled
+ await waitFor(() => {
+ expect(mockedGet).toHaveBeenCalled();
+ });
+ // Wait for the tab content to render (structure loaded)
+ await waitFor(() => {
+ expect(screen.getByRole('tab', { name: /details/i })).toBeInTheDocument();
+ });
+
await userEvent.click(screen.getByRole('button', { name: /save/i }));
await waitFor(() => {
@@ -85,6 +127,16 @@ test('shows backend error toast when save fails', async () => {
render(<SemanticViewEditModal {...props} />);
+ // Wait for structure fetch to complete so save button is enabled
+ await waitFor(() => {
+ expect(screen.getByRole('tab', { name: /details/i })).toBeInTheDocument();
+ });
+
+ // Reset the mock so we only catch the save error, not the structure fetch
+ mockedGetClientErrorObject.mockResolvedValue({
+ error: 'Semantic view failed to save',
+ });
+
await userEvent.click(screen.getByRole('button', { name: /save/i }));
await waitFor(() => {
@@ -93,3 +145,123 @@ test('shows backend error toast when save fails', async () => {
);
});
});
+
+test('fetches structure on mount', async () => {
+ const props = createProps();
+
+ render(<SemanticViewEditModal {...props} />);
+
+ await waitFor(() => {
+ expect(mockedGet).toHaveBeenCalledWith({
+ endpoint: '/api/v1/semantic_view/7/structure',
+ });
+ });
+});
+
+test('fetches and displays dimensions tab', async () => {
+ const props = createProps();
+
+ render(<SemanticViewEditModal {...props} />);
+
+ await waitFor(() => {
+ expect(mockedGet).toHaveBeenCalled();
+ });
+
+ const dimensionsTab = screen.getByRole('tab', { name: /dimensions/i });
+ expect(dimensionsTab).toBeInTheDocument();
+ expect(dimensionsTab).toHaveTextContent('2');
+
+ await userEvent.click(dimensionsTab);
+
+ await waitFor(() => {
+ expect(screen.getByText('order_date')).toBeInTheDocument();
+ });
+ expect(screen.getByText('customer_id')).toBeInTheDocument();
+ expect(screen.getByText('timestamp[us]')).toBeInTheDocument();
+});
+
+test('fetches and displays metrics tab', async () => {
+ const props = createProps();
+
+ render(<SemanticViewEditModal {...props} />);
+
+ await waitFor(() => {
+ expect(mockedGet).toHaveBeenCalled();
+ });
+
+ const metricsTab = screen.getByRole('tab', { name: /metrics/i });
+ expect(metricsTab).toBeInTheDocument();
+ expect(metricsTab).toHaveTextContent('1');
+
+ await userEvent.click(metricsTab);
+
+ await waitFor(() => {
+ expect(screen.getByText('orders')).toBeInTheDocument();
+ });
+ expect(screen.getByText('SIMPLE')).toBeInTheDocument();
+ expect(screen.getByText('Order count')).toBeInTheDocument();
+});
+
+test('shows info alert in structure tabs', async () => {
+ const props = createProps();
+
+ render(<SemanticViewEditModal {...props} />);
+
+ await waitFor(() => {
+ expect(mockedGet).toHaveBeenCalled();
+ });
+
+ await userEvent.click(screen.getByRole('tab', { name: /dimensions/i }));
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(
+ 'Structure is managed by the upstream semantic layer and is read-only.',
+ ),
+ ).toBeInTheDocument();
+ });
+});
+
+test('handles structure fetch error', async () => {
+ mockedGet.mockRejectedValue(new Error('fetch failed'));
+ mockedGetClientErrorObject.mockResolvedValue({
+ error: 'Failed to load structure',
+ });
+ const props = createProps();
+
+ render(<SemanticViewEditModal {...props} />);
+
+ await waitFor(() => {
+ expect(props.addDangerToast).toHaveBeenCalledWith(
+ 'Failed to load structure',
+ );
+ });
+});
+
+test('details tab save still works after viewing structure tabs', async () => {
+ mockedPut.mockResolvedValue({});
+ const props = createProps();
+
+ render(<SemanticViewEditModal {...props} />);
+
+ await waitFor(() => {
+ expect(mockedGet).toHaveBeenCalled();
+ });
+
+ // Navigate to dimensions tab and back to details
+ await userEvent.click(screen.getByRole('tab', { name: /dimensions/i }));
+ await userEvent.click(screen.getByRole('tab', { name: /details/i }));
+
+ await userEvent.click(screen.getByRole('button', { name: /save/i }));
+
+ await waitFor(() => {
+ expect(mockedPut).toHaveBeenCalledWith({
+ endpoint: '/api/v1/semantic_view/7',
+ jsonPayload: {
+ description: 'old description',
+ cache_timeout: 60,
+ },
+ });
+ });
+ expect(props.addSuccessToast).toHaveBeenCalledWith('Semantic view updated');
+});
diff --git a/superset-frontend/src/features/semanticViews/SemanticViewEditModal.tsx b/superset-frontend/src/features/semanticViews/SemanticViewEditModal.tsx
index 458135b1754..572051cbbf8 100644
--- a/superset-frontend/src/features/semanticViews/SemanticViewEditModal.tsx
+++ b/superset-frontend/src/features/semanticViews/SemanticViewEditModal.tsx
@@ -21,14 +21,41 @@ import { t } from '@apache-superset/core/translation';
import { SupersetClient, getClientErrorObject } from '@superset-ui/core';
import { Input, InputNumber } from '@superset-ui/core/components';
import { Icons } from '@superset-ui/core/components/Icons';
+import Tabs from '@superset-ui/core/components/Tabs';
+import {
+ Table,
+ type ColumnsType,
+ TableSize,
+} from '@superset-ui/core/components/Table';
+import { Alert } from '@apache-superset/core/components';
import {
StandardModal,
ModalFormField,
- MODAL_STANDARD_WIDTH,
+ MODAL_LARGE_WIDTH,
} from 'src/components/Modal';
type InputNumberValue = number | null;
+interface SemanticDimension {
+ name: string;
+ type: string;
+ definition: string | null;
+ description: string | null;
+ grain: string | null;
+}
+
+interface SemanticMetric {
+ name: string;
+ type: string;
+ definition: string;
+ description: string | null;
+}
+
+interface SemanticViewStructure {
+ dimensions: SemanticDimension[];
+ metrics: SemanticMetric[];
+}
+
interface SemanticViewEditModalProps {
show: boolean;
onHide: () => void;
@@ -43,6 +70,25 @@ interface SemanticViewEditModalProps {
} | null;
}
+const DIMENSION_COLUMNS: ColumnsType<SemanticDimension> = [
+ { title: t('Name'), dataIndex: 'name', key: 'name' },
+ { title: t('Type'), dataIndex: 'type', key: 'type' },
+ { title: t('Grain'), dataIndex: 'grain', key: 'grain' },
+ { title: t('Description'), dataIndex: 'description', key: 'description' },
+ { title: t('Expression'), dataIndex: 'definition', key: 'definition' },
+];
+
+const METRIC_COLUMNS: ColumnsType<SemanticMetric> = [
+ { title: t('Name'), dataIndex: 'name', key: 'name' },
+ { title: t('Type'), dataIndex: 'type', key: 'type' },
+ { title: t('Description'), dataIndex: 'description', key: 'description' },
+ { title: t('Definition'), dataIndex: 'definition', key: 'definition' },
+];
+
+const STRUCTURE_INFO_MESSAGE = t(
+ 'Structure is managed by the upstream semantic layer and is read-only.',
+);
+
export default function SemanticViewEditModal({
show,
onHide,
@@ -54,6 +100,10 @@ export default function SemanticViewEditModal({
const [description, setDescription] = useState<string>('');
const [cacheTimeout, setCacheTimeout] = useState<number | null>(null);
const [saving, setSaving] = useState(false);
+ const [structure, setStructure] = useState<SemanticViewStructure | null>(
+ null,
+ );
+ const [structureLoading, setStructureLoading] = useState(false);
useEffect(() => {
if (semanticView) {
@@ -62,6 +112,30 @@ export default function SemanticViewEditModal({
}
}, [semanticView]);
+ useEffect(() => {
+ if (show && semanticView) {
+ setStructureLoading(true);
+ SupersetClient.get({
+ endpoint: `/api/v1/semantic_view/${semanticView.id}/structure`,
+ })
+ .then(({ json }) => {
+ setStructure(json.result);
+ })
+ .catch(async error => {
+ const clientError = await getClientErrorObject(error);
+ addDangerToast?.(
+ clientError.error ||
+ t('An error occurred while fetching the semantic view structure'),
+ );
+ })
+ .finally(() => {
+ setStructureLoading(false);
+ });
+ } else {
+ setStructure(null);
+ }
+ }, [show, semanticView]); // eslint-disable-line react-hooks/exhaustive-deps
+
const handleSave = async () => {
if (!semanticView) return;
setSaving(true);
@@ -87,6 +161,9 @@ export default function SemanticViewEditModal({
}
};
+ const dimensions = structure?.dimensions ?? [];
+ const metrics = structure?.metrics ?? [];
+
return (
<StandardModal
show={show}
@@ -95,25 +172,63 @@ export default function SemanticViewEditModal({
title={t('Edit %s', semanticView?.table_name || '')}
icon={<Icons.EditOutlined />}
isEditMode
- width={MODAL_STANDARD_WIDTH}
+ width={MODAL_LARGE_WIDTH}
saveLoading={saving}
+ contentLoading={structureLoading}
>
- <ModalFormField label={t('Description')}>
- <Input.TextArea
- value={description}
- onChange={e => setDescription(e.target.value)}
- rows={4}
- />
- </ModalFormField>
- <ModalFormField label={t('Cache timeout')}>
- <InputNumber
- value={cacheTimeout}
- onChange={value => setCacheTimeout(value as InputNumberValue)}
- min={0}
- placeholder={t('Duration in seconds')}
- style={{ width: '100%' }}
- />
- </ModalFormField>
+ <Tabs>
+ <Tabs.TabPane tab={t('Details')} key="details">
+ <ModalFormField label={t('Description')}>
+ <Input.TextArea
+ value={description}
+ onChange={e => setDescription(e.target.value)}
+ rows={4}
+ />
+ </ModalFormField>
+ <ModalFormField label={t('Cache timeout')}>
+ <InputNumber
+ value={cacheTimeout}
+ onChange={value => setCacheTimeout(value as InputNumberValue)}
+ min={0}
+ placeholder={t('Duration in seconds')}
+ style={{ width: '100%' }}
+ />
+ </ModalFormField>
+ </Tabs.TabPane>
+ <Tabs.TabPane
+ tab={t('Dimensions (%s)', dimensions.length)}
+ key="dimensions"
+ >
+ <Alert
+ type="info"
+ message={STRUCTURE_INFO_MESSAGE}
+ showIcon
+ css={{ marginBottom: 16 }}
+ />
+ <Table<SemanticDimension>
+ data={dimensions}
+ columns={DIMENSION_COLUMNS}
+ size={TableSize.Small}
+ rowKey="name"
+ usePagination={false}
+ />
+ </Tabs.TabPane>
+ <Tabs.TabPane tab={t('Metrics (%s)', metrics.length)} key="metrics">
+ <Alert
+ type="info"
+ message={STRUCTURE_INFO_MESSAGE}
+ showIcon
+ css={{ marginBottom: 16 }}
+ />
+ <Table<SemanticMetric>
+ data={metrics}
+ columns={METRIC_COLUMNS}
+ size={TableSize.Small}
+ rowKey="name"
+ usePagination={false}
+ />
+ </Tabs.TabPane>
+ </Tabs>
</StandardModal>
);
}
diff --git a/superset/semantic_layers/api.py b/superset/semantic_layers/api.py
index dea648718da..a0d839d8cfb 100644
--- a/superset/semantic_layers/api.py
+++ b/superset/semantic_layers/api.py
@@ -173,8 +173,11 @@ class SemanticViewRestApi(BaseSupersetModelRestApi):
resource_name = "semantic_view"
allow_browser_login = True
class_permission_name = "SemanticView"
- method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP
- include_route_methods = {"put", "post", "delete", "bulk_delete"}
+ method_permission_name = {
+ **MODEL_API_RW_METHOD_PERMISSION_MAP,
+ "structure": "read",
+ }
+ include_route_methods = {"put", "post", "delete", "bulk_delete", "structure"}
# SemanticViewRestApi exposes only write endpoints, but can_read must be
# declared explicitly so that FAB registers the permission. It is used by
# DatasourceRestApi.combined_list to gate access to semantic views in the
@@ -183,6 +186,76 @@ class SemanticViewRestApi(BaseSupersetModelRestApi):
edit_model_schema = SemanticViewPutSchema()
+ @expose("/<int:pk>/structure", methods=("GET",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.structure",
+ log_to_statsd=False,
+ )
+ def structure(self, pk: int) -> Response:
+ """Get the structure (dimensions and metrics) of a semantic view.
+ ---
+ get:
+ summary: Get semantic view structure
+ parameters:
+ - in: path
+ schema:
+ type: integer
+ name: pk
+ responses:
+ 200:
+ description: Semantic view structure
+ 401:
+ $ref: '#/components/responses/401'
+ 404:
+ $ref: '#/components/responses/404'
+ 422:
+ $ref: '#/components/responses/422'
+ """
+ if not is_feature_enabled("SEMANTIC_LAYERS"):
+ return self.response_404()
+
+ view = db.session.query(SemanticView).filter_by(id=pk).first()
+ if not view:
+ return self.response_404()
+
+ try:
+ dimensions = [
+ {
+ "name": dim.name,
+ "type": str(dim.type),
+ "definition": dim.definition,
+ "description": dim.description,
+ "grain": dim.grain.name if dim.grain else None,
+ }
+ for dim in sorted(
+ view.implementation.get_dimensions(), key=lambda d: d.name
+ )
+ ]
+ metrics = [
+ {
+ "name": metric.name,
+ "type": str(metric.type),
+ "definition": metric.definition,
+ "description": metric.description,
+ }
+ for metric in sorted(
+ view.implementation.get_metrics(), key=lambda m: m.name
+ )
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.error(
+ "Error fetching structure for semantic view %d: %s",
+ pk,
+ str(ex),
+ exc_info=True,
+ )
+ return self.response_422(message=str(ex))
+
+ return self.response(200, result={"dimensions": dimensions, "metrics": metrics})
+
@expose("/", methods=("POST",))
@protect()
@statsd_metrics
diff --git a/tests/unit_tests/semantic_layers/api_test.py b/tests/unit_tests/semantic_layers/api_test.py
index 682d87a4a3c..b7ac8de03a7 100644
--- a/tests/unit_tests/semantic_layers/api_test.py
+++ b/tests/unit_tests/semantic_layers/api_test.py
@@ -2017,6 +2017,158 @@ def test_get_views_flag_off_returns_404(
assert response.status_code == 404
+# =============================================================================
+# SemanticViewRestApi.structure tests
+# =============================================================================
+
+
+@SEMANTIC_LAYERS_APP
+def test_get_semantic_view_structure(
+ client: Any,
+ full_api_access: None,
+ mocker: MockerFixture,
+) -> None:
+ """Test GET /<pk>/structure returns dimensions and metrics."""
+ mock_dim = MagicMock()
+ mock_dim.name = "order_date"
+ mock_dim.type = "timestamp[us]"
+ mock_dim.definition = "ordered_at"
+ mock_dim.description = "Order date"
+ mock_dim.grain = MagicMock()
+ mock_dim.grain.name = "Day"
+
+ mock_metric = MagicMock()
+ mock_metric.name = "orders"
+ mock_metric.type = "double"
+ mock_metric.definition = "SIMPLE"
+ mock_metric.description = "Order count"
+
+ mock_view = MagicMock()
+ mock_view.implementation.get_dimensions.return_value = {mock_dim}
+ mock_view.implementation.get_metrics.return_value = {mock_metric}
+
+ mock_db_session = mocker.patch("superset.semantic_layers.api.db.session")
+ mock_db_session.query.return_value.filter_by.return_value.first.return_value = (
+ mock_view
+ )
+
+ response = client.get("/api/v1/semantic_view/1/structure")
+
+ assert response.status_code == 200
+ result = response.json["result"]
+ assert len(result["dimensions"]) == 1
+ assert result["dimensions"][0]["name"] == "order_date"
+ assert result["dimensions"][0]["type"] == "timestamp[us]"
+ assert result["dimensions"][0]["definition"] == "ordered_at"
+ assert result["dimensions"][0]["description"] == "Order date"
+ assert result["dimensions"][0]["grain"] == "Day"
+ assert len(result["metrics"]) == 1
+ assert result["metrics"][0]["name"] == "orders"
+ assert result["metrics"][0]["type"] == "double"
+ assert result["metrics"][0]["definition"] == "SIMPLE"
+ assert result["metrics"][0]["description"] == "Order count"
+
+
+@SEMANTIC_LAYERS_APP
+def test_get_semantic_view_structure_not_found(
+ client: Any,
+ full_api_access: None,
+ mocker: MockerFixture,
+) -> None:
+ """Test GET /<pk>/structure returns 404 when view not found."""
+ mock_db_session = mocker.patch("superset.semantic_layers.api.db.session")
+ mock_db_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ response = client.get("/api/v1/semantic_view/999/structure")
+
+ assert response.status_code == 404
+
+
+@pytest.mark.parametrize(
+ "app",
+ [{"FEATURE_FLAGS": {"SEMANTIC_LAYERS": False}}],
+ indirect=True,
+)
+def test_get_semantic_view_structure_feature_flag_off(
+ client: Any,
+ full_api_access: None,
+) -> None:
+ """Test GET /<pk>/structure returns 404 when feature flag is off."""
+ response = client.get("/api/v1/semantic_view/1/structure")
+
+ assert response.status_code == 404
+
+
+@SEMANTIC_LAYERS_APP
+def test_get_semantic_view_structure_implementation_error(
+ client: Any,
+ full_api_access: None,
+ mocker: MockerFixture,
+) -> None:
+ """Test GET /<pk>/structure returns 422 when implementation raises."""
+ mock_view = MagicMock()
+ mock_view.implementation.get_dimensions.side_effect = RuntimeError(
+ "Connection failed"
+ )
+
+ mock_db_session = mocker.patch("superset.semantic_layers.api.db.session")
+ mock_db_session.query.return_value.filter_by.return_value.first.return_value = (
+ mock_view
+ )
+
+ response = client.get("/api/v1/semantic_view/1/structure")
+
+ assert response.status_code == 422
+ assert "Connection failed" in response.json["message"]
+
+
+@SEMANTIC_LAYERS_APP
+def test_get_semantic_view_structure_no_grain(
+ client: Any,
+ full_api_access: None,
+ mocker: MockerFixture,
+) -> None:
+ """Test GET /<pk>/structure handles dimensions without grain."""
+ mock_dim = MagicMock()
+ mock_dim.name = "customer_id"
+ mock_dim.type = "int64"
+ mock_dim.definition = None
+ mock_dim.description = None
+ mock_dim.grain = None
+
+ mock_view = MagicMock()
+ mock_view.implementation.get_dimensions.return_value = {mock_dim}
+ mock_view.implementation.get_metrics.return_value = set()
+
+ mock_db_session = mocker.patch("superset.semantic_layers.api.db.session")
+ mock_db_session.query.return_value.filter_by.return_value.first.return_value = (
+ mock_view
+ )
+
+ response = client.get("/api/v1/semantic_view/1/structure")
+
+ assert response.status_code == 200
+ result = response.json["result"]
+ assert result["dimensions"][0]["grain"] is None
+ assert result["metrics"] == []
+
+
+def test_semantic_view_structure_flag_off_unwrapped() -> None:
+ """Cover structure() feature-flag guard without auth decorators."""
+ api = SemanticViewRestApi()
+ api.response_404 = MagicMock(return_value=("404", 404))
+ structure_fn = inspect.unwrap(SemanticViewRestApi.structure)
+
+ with patch(
+ "superset.semantic_layers.api.is_feature_enabled",
+ return_value=False,
+ ):
+ response = structure_fn(api, 1)
+
+ assert response == ("404", 404)
+ api.response_404.assert_called_once()
+
+
def test_semantic_view_post_flag_off_unwrapped() -> None:
"""Cover post() feature-flag guard without auth decorators."""
api = SemanticViewRestApi()