Copilot commented on code in PR #42539:
URL: https://github.com/apache/superset/pull/42539#discussion_r3667954439


##########
superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/FiltersConfigForm.tsx:
##########
@@ -763,34 +764,19 @@ const FiltersConfigForm = (
   useEffect(() => {
     if (datasetId) {
       if (datasourceType === DatasourceType.SemanticView) {
-        cachedSupersetGet({
-          endpoint: `/api/v1/semantic_view/${datasetId}/structure`,
-        })
-          .then((response: JsonResponse) => {
-            const {
-              name: svName,
-              dimensions = [],
-              metrics: svMetrics = [],
-            } = response.json?.result ?? {};
-            const columns = dimensions.map(
-              (dim: { name: string; type: string }) => {
-                const mappedType = mapSemanticTypeToGenericDataType(dim.type);
-                return {
-                  column_name: dim.name,
-                  type: dim.type,
-                  is_dttm: mappedType === GenericDataType.Temporal,
-                  filterable: true,
-                  type_generic: mappedType,
-                };
-              },
-            );
+        fetchSemanticViewStructure(datasetId)
+          .then(({ name: svName, dimensions, metrics: svMetrics }) => {
+            const columns = semanticViewDimensionsToColumns(dimensions);
+            // verbose_name stays null at runtime (pre-refactor value —
+            // consumers only falsy-check it); Metric types it as an
+            // optional string, hence the cast.
             const mappedMetrics = svMetrics.map(
               (m: { name: string; definition: string }) => ({
                 metric_name: m.name,
                 expression: m.definition,
                 verbose_name: null,
               }),
-            );
+            ) as unknown as Metric[];

Review Comment:
   The `as unknown as Metric[]` cast is another sign the mapped object doesn’t 
match the `Metric` type. If `verbose_name` is optional, prefer omitting it or 
using `undefined` instead of `null` so the array can be typed as `Metric[]` 
without an unsafe cast. This will reduce the chance of future refactors 
silently breaking consumers that rely on the `Metric` shape.



##########
superset-frontend/src/hooks/apiResources/datasets.ts:
##########
@@ -31,6 +32,10 @@ import {
   cachedSupersetGet,
   supersetGetCache,
 } from 'src/utils/cachedSupersetGet';
+import {
+  fetchSemanticViewStructure,
+  semanticViewDimensionsToColumns,
+} from 
'src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/utils';

Review Comment:
   This introduces a cross-layer dependency from a generic API-resources hook 
into a dashboard modal utility module. That coupling can increase bundle 
entanglement and risks circular deps as more call sites use 
`useDatasetDrillInfo`. Consider relocating `fetchSemanticViewStructure` / 
`semanticViewDimensionsToColumns` into a neutral/shared module (e.g., 
`src/hooks/apiResources/semanticViews` or `src/features/semanticLayers/...`) 
and importing from there in both the dashboard and hooks layers.



##########
superset-frontend/src/hooks/apiResources/datasets.ts:
##########
@@ -41,6 +46,26 @@ export const getDatasetId = (datasetId: string | number): 
number =>
     ? Number(datasetId.split('__')[0])
     : Number(datasetId);
 
+/**
+ * Extract the datasource type from an `<id>__<type>` datasource string.
+ * Semantic views and regular datasets have independent numeric-id
+ * sequences, so the type is load-bearing: resolving by id alone reads
+ * whatever regular dataset shares the number (sc-111089). Absent or
+ * unrecognized suffixes fall back to a regular dataset, preserving
+ * legacy behaviour.
+ */
+export const getDatasourceTypeFromId = (
+  datasetId: string | number,
+): DatasourceType => {

Review Comment:
   The name `getDatasourceTypeFromId` is a bit misleading because the function 
is parsing a datasource UID-like string (`<id>__<type>`), not a plain id. 
Renaming to something like `getDatasourceTypeFromUid` / 
`getDatasourceTypeFromDatasourceId` would make call sites clearer and reduce 
confusion with `getDatasetId`.



##########
superset-frontend/src/dashboard/components/nativeFilters/useDisplayControlDatasource.ts:
##########
@@ -0,0 +1,133 @@
+/**
+ * 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 { useEffect, useRef, useState } from 'react';
+import { DatasourceType } from '@superset-ui/core';
+import { cachedSupersetGet } from 'src/utils/cachedSupersetGet';
+import {
+  fetchSemanticViewStructure,
+  semanticViewDimensionsToColumns,
+} from './FiltersConfigModal/FiltersConfigForm/utils';
+
+/** The column fields display controls read to build their options. */
+export interface DisplayControlColumn {
+  column_name?: string;
+  name?: string;
+  verbose_name?: string | null;
+  filterable?: boolean;
+}
+
+export interface DisplayControlDatasource {
+  /** The datasource's display name (dataset table_name / semantic view name). 
*/
+  name: string | undefined;
+  columns: DisplayControlColumn[];
+  loading: boolean;
+  error: Error | undefined;
+}
+
+/**
+ * The single, type-aware datasource resolution point for dashboard display
+ * controls (Dynamic group by today; siblings adopt this hook as they gain
+ * loaders).
+ *
+ * Semantic views and regular datasets have independent numeric-id
+ * sequences, so a binding must be resolved by BOTH id and datasourceType —
+ * an id-only lookup silently reads whatever regular dataset shares the
+ * view's number (sc-111089). The default branch preserves the legacy
+ * display-control request (`GET /api/v1/dataset/<id>`, full resource, no
+ * projection) byte-for-byte; changing that shape is a deliberate,
+ * separately-tested decision, not a drive-by.
+ *
+ * Responses are guarded by a monotonic request id: on a same-id type flip
+ * a slow response for the previous binding is discarded rather than
+ * overwriting the newer one — reintroducing the wrong-object bug through
+ * a race would otherwise be possible.
+ */
+export function useDisplayControlDatasource(
+  datasetId: number | string | undefined | null,
+  datasourceType?: DatasourceType,
+): DisplayControlDatasource {
+  const [name, setName] = useState<string | undefined>();
+  const [columns, setColumns] = useState<DisplayControlColumn[]>([]);
+  const [loading, setLoading] = useState(false);
+  const [error, setError] = useState<Error | undefined>();
+  const requestIdRef = useRef(0);
+
+  useEffect(() => {
+    // Invalidate any in-flight request on every binding change (and on
+    // unmount, via the cleanup below).
+    requestIdRef.current += 1;
+    const requestId = requestIdRef.current;
+
+    if (datasetId === undefined || datasetId === null || datasetId === '') {
+      // Unbound control: inert, nothing to fetch.
+      setName(undefined);
+      setColumns([]);
+      setLoading(false);
+      setError(undefined);
+      return undefined;
+    }
+
+    setLoading(true);
+    setError(undefined);
+
+    const load = async (): Promise<{
+      name: string | undefined;
+      columns: DisplayControlColumn[];
+    }> => {
+      if (datasourceType === DatasourceType.SemanticView) {
+        const structure = await fetchSemanticViewStructure(datasetId);
+        return {
+          name: structure.name,
+          columns: semanticViewDimensionsToColumns(structure.dimensions),
+        };
+      }
+      const { json } = await cachedSupersetGet({
+        endpoint: `/api/v1/dataset/${datasetId}`,
+      });

Review Comment:
   In the semantic-view branch, `datasetId` is interpolated directly into the 
structure endpoint via `fetchSemanticViewStructure(datasetId)`. Since the hook 
accepts `string | number`, callers may pass a datasource UID string like 
`\"3__semantic_view\"` (a common Superset pattern), which would produce an 
invalid endpoint (`/semantic_view/3__semantic_view/structure`). Consider 
normalizing/parsing `datasetId` to a numeric id inside the hook (or inside 
`fetchSemanticViewStructure`) to make the API robust to UID-shaped inputs, and 
add a small test to lock this behavior.



##########
superset-frontend/src/hooks/apiResources/datasets.ts:
##########
@@ -89,7 +114,29 @@ export const useDatasetDrillInfo = (
         );
         let result;
 
-        if (loadDrillByOptionsExtension && formData) {
+        if (
+          getDatasourceTypeFromId(datasetId) === DatasourceType.SemanticView
+        ) {
+          // Semantic views short-circuit BEFORE the extension check: the
+          // extension receives only the numeric id, which would resolve
+          // the colliding regular dataset (sc-111089 review consensus).
+          // The structure payload carries no changed_on/owners metadata —
+          // those metadata-bar rows render their not-available state, an
+          // accepted degradation. Columns are narrowed to metadata needs;
+          // no drill flags are fabricated.
+          const structure = await fetchSemanticViewStructure(numericDatasetId);
+          result = {
+            id: numericDatasetId,
+            table_name: structure.name,
+            datasource_type: DatasourceType.SemanticView,
+            columns: semanticViewDimensionsToColumns(structure.dimensions),
+            metrics: structure.metrics.map(metric => ({
+              metric_name: metric.name,
+              expression: metric.definition,
+              verbose_name: null,
+            })),
+          } as unknown as Dataset;

Review Comment:
   The `as unknown as Dataset` cast is masking a type mismatch and makes it 
easy to accidentally omit properties that downstream consumers assume exist. 
Prefer building a properly-typed object (e.g., a dedicated `DrillDatasetInfo` 
type returned by this hook, or a `Pick<Dataset, ...>`-based shape) and update 
`createVerboseMap`/consumers accordingly. If the only mismatch is 
`verbose_name: null`, consider switching to `undefined` or omitting the field 
(since the type is `string | undefined`) to avoid needing an `unknown` cast.



-- 
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]

Reply via email to