Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Remove @ts-nocheck from metabase-lib Question (#76506)

Romeo Van Snick4f088825cac9
diff --git a/enterprise/frontend/src/metabase-enterprise/collections/utils.ts b/enterprise/frontend/src/metabase-enterprise/collections/utils.ts
index 2582ad6e006..b1751c76ca8 100644
--- a/enterprise/frontend/src/metabase-enterprise/collections/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/collections/utils.ts
@@ -45,7 +45,7 @@ export function getCollectionType({
}
export function isInstanceAnalyticsCollection(
- collection?: Pick<Collection, "type">,
+ collection?: Pick<Collection, "type"> | null,
): boolean {
return (
!!collection && getCollectionType(collection).type === "instance-analytics"
diff --git a/frontend/src/metabase-lib/v1/Question.ts b/frontend/src/metabase-lib/v1/Question.ts
index 814e4131217..8645864e84f 100644
--- a/frontend/src/metabase-lib/v1/Question.ts
+++ b/frontend/src/metabase-lib/v1/Question.ts
@@ -1,5 +1,3 @@
-// eslint-disable-next-line @typescript-eslint/ban-ts-comment
-// @ts-nocheck
import { assoc, assocIn, chain, dissoc, getIn } from "icepick";
import slugg from "slugg";
import _ from "underscore";
@@ -17,11 +15,12 @@ import NativeQuery, {
import { STRUCTURED_QUERY_TEMPLATE } from "metabase-lib/v1/queries/StructuredQuery";
import type {
Card,
+ CardDashboardInfo,
CardDisplayType,
CardType,
+ Collection,
CollectionId,
DashCardId,
- Dashboard,
DashboardId,
DatabaseId,
DatasetData,
@@ -31,6 +30,7 @@ import type {
ParameterId,
Parameter as ParameterObject,
ParameterValuesMap,
+ ResultsMetadata,
TableId,
UserInfo,
VisualizationDisplay,
@@ -90,21 +90,16 @@ class Question {
* Question constructor
*/
constructor(
+ // This deprecated wrapper is constructed from ~200 call sites with a mix of
+ // saved cards, unsaved/draft cards, and (in tests) partial card mocks, so the
+ // card boundary stays loosely typed. Internally it is treated as a `Card`,
+ // guarding the saved-only fields (id, name, type, ...) where they are read.
card: any,
metadata?: Metadata,
parameterValues?: ParameterValuesMap,
) {
this._card = card;
- this._metadata =
- metadata ||
- new Metadata({
- databases: {},
- tables: {},
- fields: {},
- metrics: {},
- segments: {},
- questions: {},
- });
+ this._metadata = metadata || new Metadata();
this._parameterValues = parameterValues || {};
}
@@ -167,7 +162,11 @@ class Question {
const isVirtualDashcard = !this._card.id;
// The `dataset_query` is null for questions on a dashboard the user doesn't have access to
if (!isVirtualDashcard) {
- console.warn("Unknown query type: " + datasetQuery?.type);
+ const queryType =
+ datasetQuery != null && "type" in datasetQuery
+ ? datasetQuery.type
+ : undefined;
+ console.warn("Unknown query type: " + queryType);
}
});
@@ -213,7 +212,10 @@ class Question {
* The visualization type of the question
*/
display(): CardDisplayType {
- return this._card && this._card.display;
+ // `_card.display` is typed `VisualizationDisplay` because `Card` reuses
+ // `UnsavedCard`, but a Question is never a virtual dashcard, so its display
+ // is always a renderable `CardDisplayType`.
+ return (this._card && this._card.display) as CardDisplayType;
}
setDisplay(display: VisualizationDisplay) {
@@ -232,7 +234,7 @@ class Question {
return this._card && this._card.persisted;
}
- setPersisted(isPersisted) {
+ setPersisted(isPersisted: boolean) {
return this.setCard(assoc(this.card(), "persisted", isPersisted));
}
@@ -256,7 +258,7 @@ class Question {
}
displayIsLocked(): boolean {
- return this._card && this._card.displayIsLocked;
+ return this._card?.displayIsLocked ?? false;
}
maybeResetDisplay(
@@ -285,7 +287,7 @@ class Question {
}
// Switches display to scalar if the data is 1 row x 1 column
- private _maybeSwitchToScalar({ rows, cols }): Question {
+ private _maybeSwitchToScalar({ rows, cols }: DatasetData): Question {
const isScalar = ["scalar", "progress", "gauge"].includes(this.display());
const isOneByOne = rows.length === 1 && cols.length === 1;
if (!isScalar && isOneByOne && !this.displayIsLocked()) {
@@ -309,7 +311,7 @@ class Question {
return (this._card && this._card.visualization_settings) || {};
}
- setting(settingName, defaultValue = undefined) {
+ setting(settingName: keyof VisualizationSettings, defaultValue = undefined) {
const value = this.settings()[settingName];
return value === undefined ? defaultValue : value;
}
@@ -322,7 +324,7 @@ class Question {
return this.setSettings({ ...this.settings(), ...settings });
}
- creationType(): string {
+ creationType(): string | undefined {
return this.card().creationType;
}
@@ -339,7 +341,7 @@ class Question {
canRun(): boolean {
const { isNative } = Lib.queryDisplayInfo(this.query());
return isNative
- ? this.legacyNativeQuery().canRun()
+ ? (this.legacyNativeQuery()?.canRun() ?? false)
: Lib.canRun(this.query(), this.type());
}
@@ -428,7 +430,7 @@ class Question {
}
collection(): Collection | null | undefined {
- return this?._card?.collection;
+ return this._card?.collection;
}
collectionId(): CollectionId | null | undefined {
@@ -439,7 +441,7 @@ class Question {
return this.setCard(assoc(this.card(), "collection_id", collectionId));
}
- dashboard(): Dashboard | undefined {
+ dashboard(): CardDashboardInfo | null {
return this._card.dashboard;
}
@@ -451,7 +453,7 @@ class Question {
return this._card?.dashboard?.name ?? undefined;
}
- dashboardCount(): number {
+ dashboardCount(): number | null {
return this._card.dashboard_count;
}
@@ -494,11 +496,11 @@ class Question {
return this._card && this._card.description;
}
- setDescription(description) {
+ setDescription(description: string | null) {
return this.setCard(assoc(this.card(), "description", description));
}
- lastEditInfo(): LastEditInfo {
+ lastEditInfo(): LastEditInfo | undefined {
return this._card && this._card["last-edit-info"];
}
@@ -510,7 +512,7 @@ class Question {
return !!this.id();
}
- publicUUID(): string {
+ publicUUID(): string | null {
return this._card && this._card.public_uuid;
}
@@ -534,7 +536,7 @@ class Question {
return this.card().result_metadata ?? [];
}
- setResultsMetadata(resultsMetadata) {
+ setResultsMetadata(resultsMetadata: ResultsMetadata | null) {
const metadataColumns = resultsMetadata && resultsMetadata.columns;
return this.setCard({
...this.card(),
@@ -554,7 +556,10 @@ class Question {
/**
* Returns true if the questions are equivalent (including id, card, and parameters)
*/
- isEqual(other, { compareResultsMetadata = true } = {}) {
+ isEqual(
+ other: Question | null | undefined,
+ { compareResultsMetadata = true } = {},
+ ) {
if (!other) {
return false;
}
@@ -590,17 +595,17 @@ class Question {
return this.setParameters(newParameters);
}
- setParameters(parameters) {
+ setParameters(parameters: ParameterObject[] | undefined) {
return this.setCard(assoc(this.card(), "parameters", parameters));
}
- setParameterValues(parameterValues) {
+ setParameterValues(parameterValues: ParameterValuesMap = {}) {
const question = this.clone();
question._parameterValues = parameterValues;
return question;
}
- private _getParameters = _.memoize((collectionPreview: boolean) => {
+ private _getParameters = _.memoize((collectionPreview?: boolean) => {
return getCardUiParameters(
this.card(),
this.metadata(),
@@ -610,7 +615,9 @@ class Question {
);
});
- parameters({ collectionPreview } = {}): ParameterObject[] {
+ parameters({
+ collectionPreview,
+ }: { collectionPreview?: boolean } = {}): ParameterObject[] {
return this._getParameters(collectionPreview);
}
@@ -661,8 +668,8 @@ class Question {
}
// Internal methods
- _getValueForComparison() {
- const value = {
+ _getValueForComparison(): Record<string, unknown> {
+ const value: Record<string, unknown> = {
...this._card,
...this._parameterValues,
};
@@ -681,12 +688,9 @@ class Question {
"visualization_settings",
];
- const res = {};
- for (const key of keys) {
- res[key] = value[key] ?? undefined;
- }
-
- return res;
+ return Object.fromEntries(
+ keys.map((key) => [key, value[key] ?? undefined]),
+ );
}
query(): Query {
@@ -775,7 +779,10 @@ class Question {
? NATIVE_QUERY_TEMPLATE
: STRUCTURED_QUERY_TEMPLATE,
}: QuestionCreatorOpts = {}) {
- let card: Card = {
+ // `create` builds an unsaved draft that lacks the fields a saved Card has
+ // (id, entity_id, name, type, ...). The Question class nevertheless treats
+ // `_card` as a full Card, so we assert the draft shape here.
+ let card = {
name,
collection_id: collectionId,
dashboard_id: dashboardId,
@@ -783,7 +790,7 @@ class Question {
visualization_settings,
dataset_query,
type: cardType,
- };
+ } as Card;
if (type === "native") {
card = assocIn(card, ["parameters"], []);
diff --git a/frontend/src/metabase-lib/v1/queries/StructuredQuery.ts b/frontend/src/metabase-lib/v1/queries/StructuredQuery.ts
index af7ec468db4..9a2ff5b7811 100644
--- a/frontend/src/metabase-lib/v1/queries/StructuredQuery.ts
+++ b/frontend/src/metabase-lib/v1/queries/StructuredQuery.ts
@@ -1,4 +1,6 @@
-export const STRUCTURED_QUERY_TEMPLATE = {
+import type { StructuredDatasetQuery } from "metabase-types/api";
+
+export const STRUCTURED_QUERY_TEMPLATE: StructuredDatasetQuery = {
database: null,
type: "query",
query: {
diff --git a/frontend/src/metabase-types/api/card.ts b/frontend/src/metabase-types/api/card.ts
index 462e53a2123..a83d8ac8950 100644
--- a/frontend/src/metabase-types/api/card.ts
+++ b/frontend/src/metabase-types/api/card.ts
@@ -121,6 +121,9 @@ export interface UnsavedCard<Q extends DatasetQuery = DatasetQuery> {
// Not part of the card API contract, a field used by query builder for showing lineage
original_card_id?: number;
displayIsLocked?: boolean;
+
+ // Not part of the card API contract, a transient marker for how the card was created
+ creationType?: string;
}
export type LineSize = "S" | "M" | "L";
diff --git a/frontend/src/metabase-types/api/query.ts b/frontend/src/metabase-types/api/query.ts
index 7b6676796f2..cdcfe264d35 100644
--- a/frontend/src/metabase-types/api/query.ts
+++ b/frontend/src/metabase-types/api/query.ts
@@ -157,7 +157,8 @@ type NestedQueryTableId = string;
type SourceTableId = TableId | NestedQueryTableId;
export type StructuredQuery = {
- "source-table"?: SourceTableId;
+ // `null` is the legacy MBQL marker for a not-yet-selected source table
+ "source-table"?: SourceTableId | null;
"source-query"?: StructuredQuery;
aggregation?: AggregationClause;
breakout?: BreakoutClause;
diff --git a/frontend/src/metabase/common/collections/utils.ts b/frontend/src/metabase/common/collections/utils.ts
index b74d7c054dd..d2fa2e459f5 100644
--- a/frontend/src/metabase/common/collections/utils.ts
+++ b/frontend/src/metabase/common/collections/utils.ts
@@ -111,7 +111,7 @@ export function isEditableCollection(
}
export function isInstanceAnalyticsCollection(
- collection?: Pick<Collection, "type">,
+ collection?: Pick<Collection, "type"> | null,
): boolean {
return (
!!collection &&
@@ -185,7 +185,9 @@ export function isPersonalCollectionChild(
return Boolean(parentCollection && !!parentCollection.personal_owner_id);
}
-export function isRootCollection(collection: Pick<Collection, "id">): boolean {
+export function isRootCollection(
+ collection: Pick<Collection, "id"> | null | undefined,
+): boolean {
return canonicalCollectionId(collection?.id) === null;
}
@@ -359,7 +361,7 @@ export function isValidCollectionId(
}
export const getCollectionName = (
- collection: Pick<Collection, "id" | "name">,
+ collection: Pick<Collection, "id" | "name"> | null | undefined,
) => {
if (isRootCollection(collection)) {
return t`Our analytics`;
diff --git a/frontend/src/metabase/common/collections/utils.unit.spec.ts b/frontend/src/metabase/common/collections/utils.unit.spec.ts
index 673f9258490..ce4e87a6735 100644
--- a/frontend/src/metabase/common/collections/utils.unit.spec.ts
+++ b/frontend/src/metabase/common/collections/utils.unit.spec.ts
@@ -166,9 +166,7 @@ describe("Collections > utils", () => {
it("returns true if there is no collection", () => {
/* @ts-expect-error checking if a race condition not returning expected data behaves as expected */
expect(isRootCollection({})).toBe(true);
- /* @ts-expect-error checking if a race condition not returning expected data behaves as expected */
expect(isRootCollection(null)).toBe(true);
- /* @ts-expect-error checking if a race condition not returning expected data behaves as expected */
expect(isRootCollection(undefined)).toBe(true);
});
diff --git a/frontend/src/metabase/metrics/pages/MetricQueryPage/MetricQueryPage.tsx b/frontend/src/metabase/metrics/pages/MetricQueryPage/MetricQueryPage.tsx
index 330749f5b0d..6563a326ec7 100644
--- a/frontend/src/metabase/metrics/pages/MetricQueryPage/MetricQueryPage.tsx
+++ b/frontend/src/metabase/metrics/pages/MetricQueryPage/MetricQueryPage.tsx
@@ -103,9 +103,9 @@ function MetricQueryPageBody({
};
const handleSave = async () => {
- const questionWithMetadata = question.setResultsMetadata({
- columns: resultMetadata,
- });
+ const questionWithMetadata = question.setResultsMetadata(
+ resultMetadata ? { columns: resultMetadata } : null,
+ );
const { display, settings } = Lib.defaultDisplay(
questionWithMetadata.query(),
);
diff --git a/frontend/src/metabase/querying/components/DataReference/QuestionPane/QuestionPane.tsx b/frontend/src/metabase/querying/components/DataReference/QuestionPane/QuestionPane.tsx
index a63ecadaa17..045d46f1ff8 100644
--- a/frontend/src/metabase/querying/components/DataReference/QuestionPane/QuestionPane.tsx
+++ b/frontend/src/metabase/querying/components/DataReference/QuestionPane/QuestionPane.tsx
@@ -79,6 +79,8 @@ export const QuestionPane = ({
return <LoadingAndErrorWrapper loading />;
}
+ const lastEditInfo = question.lastEditInfo();
+
return (
<SidebarContent
title={question.displayName() || undefined}
@@ -119,7 +121,7 @@ export const QuestionPane = ({
{collection?.name ?? t`Our analytics`}
</Box>
</Flex>
- {question.lastEditInfo() && (
+ {lastEditInfo && (
<Flex
color="text-secondary"
align="center"
@@ -129,11 +131,7 @@ export const QuestionPane = ({
<Icon className={S.QuestionPaneIcon} name="calendar" />
<Box component="span" ml="sm" fw="normal">
{jt`Last edited ${(
- <DateTime
- key="day"
- unit="day"
- value={question.lastEditInfo().timestamp}
- />
+ <DateTime key="day" unit="day" value={lastEditInfo.timestamp} />
)}`}
</Box>
</Flex>
diff --git a/frontend/src/types/global.d.ts b/frontend/src/types/global.d.ts
index 752c6b1ecc6..ca62958fe5f 100644
--- a/frontend/src/types/global.d.ts
+++ b/frontend/src/types/global.d.ts
@@ -23,6 +23,11 @@ interface Window {
overrideIsWithinIframe?: boolean; // Mock that we're embedding, so we could test embed components
METABASE?: boolean; // Add a global so we can check if the parent iframe is Metabase
+ // Dev-only helpers for inspecting the current query from CLJS REPLs
+ __lib_metadata?: unknown;
+ __lib_query?: unknown;
+ Lib?: unknown;
+
// Make iFrameResizer available so that embed users can
// have their embeds autosize to their content
iFrameResizer?: {