Skip to content

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

Add tooltip to run button when field filters are missing a target field in Native editor (#67670)

Romeo Van Snick6b0413820433
diff --git a/e2e/test/scenarios/native-filters/sql-field-filter.cy.spec.js b/e2e/test/scenarios/native-filters/sql-field-filter.cy.spec.js
index cef8dab0660..483875bf6db 100644
--- a/e2e/test/scenarios/native-filters/sql-field-filter.cy.spec.js
+++ b/e2e/test/scenarios/native-filters/sql-field-filter.cy.spec.js
@@ -218,4 +218,48 @@ describe("scenarios > filters > sql filters > field filter", () => {
H.tableInteractive().should("contain", "April 1, 2022");
});
});
+
+ describe("missing field", () => {
+ it("should show error message when the field mapping is missing", () => {
+ cy.log("Set up field filter");
+
+ H.startNewNativeQuestion();
+ SQLFilter.enterParameterizedQuery(
+ "SELECT * FROM products WHERE {{my_filter}}",
+ { allowFastSet: true },
+ );
+
+ cy.log("Test field filter");
+ SQLFilter.openTypePickerFromDefaultFilterType();
+ SQLFilter.chooseType("Field Filter");
+
+ SQLFilter.getSaveQueryButton().should("have.attr", "aria-disabled");
+ SQLFilter.getSaveQueryButton().click({ force: true });
+ H.tooltip()
+ .findByText('The variable "my_filter" needs to be mapped to a field.')
+ .should("be.visible");
+
+ SQLFilter.getRunQueryButton().should("be.disabled");
+ SQLFilter.getRunQueryButton().click({ force: true });
+ H.tooltip()
+ .findByText('The variable "my_filter" needs to be mapped to a field.')
+ .should("be.visible");
+
+ cy.log("Test time grouping");
+ SQLFilter.openTypePickerFromDefaultFilterType();
+ SQLFilter.chooseType("Time grouping");
+
+ SQLFilter.getSaveQueryButton().should("have.attr", "aria-disabled");
+ SQLFilter.getSaveQueryButton().click({ force: true });
+ H.tooltip()
+ .findByText('The variable "my_filter" needs to be mapped to a field.')
+ .should("be.visible");
+
+ SQLFilter.getRunQueryButton().should("be.disabled");
+ SQLFilter.getRunQueryButton().click({ force: true });
+ H.tooltip()
+ .findByText('The variable "my_filter" needs to be mapped to a field.')
+ .should("be.visible");
+ });
+ });
});
diff --git a/frontend/src/metabase-lib/native.ts b/frontend/src/metabase-lib/native.ts
index 80aa2982786..58955cc050f 100644
--- a/frontend/src/metabase-lib/native.ts
+++ b/frontend/src/metabase-lib/native.ts
@@ -1,7 +1,7 @@
import * as ML from "cljs/metabase.lib.js";
import type { DatabaseId, TemplateTags } from "metabase-types/api";
-import type { MetadataProvider, Query } from "./types";
+import type { MetadataProvider, Query, ValidationError } from "./types";
export function nativeQuery(
databaseId: DatabaseId,
@@ -75,3 +75,10 @@ export function withNativeExtras(
): Query {
return ML.with_native_extras(query, nativeExtras);
}
+
+/**
+ * Validates if the template tags in query are all valid and well-formed.
+ */
+export function validateTemplateTags(query: Query): ValidationError[] {
+ return ML.validate_template_tags(query);
+}
diff --git a/frontend/src/metabase-lib/types.ts b/frontend/src/metabase-lib/types.ts
index 7f514f4054d..c685b6a3a4e 100644
--- a/frontend/src/metabase-lib/types.ts
+++ b/frontend/src/metabase-lib/types.ts
@@ -673,3 +673,5 @@ export type FieldItem = {
};
export type DependentItem = DatabaseItem | SchemaItem | TableItem | FieldItem;
+
+export type ValidationError = { message: string };
diff --git a/frontend/src/metabase-lib/v1/Dimension.ts b/frontend/src/metabase-lib/v1/Dimension.ts
index 1384d99fece..f30c49f0da9 100644
--- a/frontend/src/metabase-lib/v1/Dimension.ts
+++ b/frontend/src/metabase-lib/v1/Dimension.ts
@@ -1,11 +1,5 @@
-import { t } from "ttag";
-
-import ValidationError, {
- VALIDATION_ERROR_TYPES,
-} from "metabase-lib/v1/ValidationError";
import type Metadata from "metabase-lib/v1/metadata/Metadata";
import type NativeQuery from "metabase-lib/v1/queries/NativeQuery";
-import TemplateTagVariable from "metabase-lib/v1/variables/TemplateTagVariable";
import type { VariableTarget } from "metabase-types/api";
export class TemplateTagDimension {
@@ -19,46 +13,6 @@ export class TemplateTagDimension {
this._tagName = tagName;
}
- validateTemplateTag(): ValidationError | null {
- const tag = this.tag();
- if (!tag) {
- return new ValidationError(t`Invalid template tag "${this.tagName()}"`);
- }
-
- if (this.isDimensionType() && tag.dimension == null) {
- return new ValidationError(
- t`The variable "${this.tagName()}" needs to be mapped to a field.`,
- VALIDATION_ERROR_TYPES.MISSING_TAG_DIMENSION,
- );
- }
-
- return null;
- }
-
- isValidDimensionType() {
- const maybeErrors = this.validateTemplateTag();
- return this.isDimensionType() && maybeErrors === null;
- }
-
- isDimensionType() {
- const maybeTag = this.tag();
- return maybeTag?.type === "dimension";
- }
-
- isVariableType() {
- const maybeTag = this.tag();
- return ["text", "number", "date"].includes(maybeTag?.type);
- }
-
- variable() {
- if (this.isVariableType()) {
- const tag = this.tag();
- return new TemplateTagVariable([tag.name], this._metadata, this._query);
- }
-
- return null;
- }
-
tag() {
const templateTagMap = this._query?.templateTagsMap() ?? {};
return templateTagMap[this.tagName()];
@@ -82,12 +36,6 @@ export class TemplateTagDimension {
return this.field()?.icon();
}
- name() {
- return this.isValidDimensionType()
- ? (this.field()?.name ?? "")
- : this.tagName();
- }
-
tagName() {
return this._tagName;
}
diff --git a/frontend/src/metabase-lib/v1/ValidationError/ValidationError.ts b/frontend/src/metabase-lib/v1/ValidationError/ValidationError.ts
deleted file mode 100644
index 95683d9812c..00000000000
--- a/frontend/src/metabase-lib/v1/ValidationError/ValidationError.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import type { ErrorType } from "./types";
-
-// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default class ValidationError extends Error {
- type?: ErrorType;
-
- constructor(message: string, errorType?: ErrorType) {
- super(message);
- this.type = errorType;
- }
-
- toString() {
- return `ValidationError: ${this.message} (type: ${this.type})`;
- }
-}
diff --git a/frontend/src/metabase-lib/v1/ValidationError/constants.ts b/frontend/src/metabase-lib/v1/ValidationError/constants.ts
deleted file mode 100644
index 7b0ed3ee8b5..00000000000
--- a/frontend/src/metabase-lib/v1/ValidationError/constants.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export const VALIDATION_ERROR_TYPES = {
- MISSING_TAG_DIMENSION: "MISSING_TAG_DIMENSION",
-} as const;
diff --git a/frontend/src/metabase-lib/v1/ValidationError/index.ts b/frontend/src/metabase-lib/v1/ValidationError/index.ts
deleted file mode 100644
index 1ba53c61308..00000000000
--- a/frontend/src/metabase-lib/v1/ValidationError/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-// eslint-disable-next-line import/no-default-export -- deprecated usage
-export { default } from "./ValidationError";
-export * from "./constants";
-export * from "./types";
diff --git a/frontend/src/metabase-lib/v1/ValidationError/types.ts b/frontend/src/metabase-lib/v1/ValidationError/types.ts
deleted file mode 100644
index 6a501400a83..00000000000
--- a/frontend/src/metabase-lib/v1/ValidationError/types.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import type { VALIDATION_ERROR_TYPES } from "./constants";
-
-export type ErrorType =
- (typeof VALIDATION_ERROR_TYPES)[keyof typeof VALIDATION_ERROR_TYPES];
diff --git a/frontend/src/metabase-lib/v1/queries/NativeQuery.ts b/frontend/src/metabase-lib/v1/queries/NativeQuery.ts
index 4e19a95493a..befbcbe20c9 100644
--- a/frontend/src/metabase-lib/v1/queries/NativeQuery.ts
+++ b/frontend/src/metabase-lib/v1/queries/NativeQuery.ts
@@ -1,11 +1,9 @@
import slugg from "slugg";
-import { t } from "ttag";
import _ from "underscore";
import { checkNotNull } from "metabase/lib/types";
import * as Lib from "metabase-lib";
import type Question from "metabase-lib/v1/Question";
-import ValidationError from "metabase-lib/v1/ValidationError";
import type Database from "metabase-lib/v1/metadata/Database";
import type Table from "metabase-lib/v1/metadata/Table";
import { getTemplateTagParameter } from "metabase-lib/v1/parameters/utils/template-tags";
@@ -295,30 +293,8 @@ export default class NativeQuery {
.filter((cardId): cardId is number => cardId != null);
}
- private _validateTemplateTags() {
- return this.templateTags()
- .map((tag) => {
- if (!tag["display-name"]) {
- return new ValidationError(t`Missing widget label: ${tag.name}`);
- }
- const dimension = new TemplateTagDimension(
- tag.name,
- this.metadata(),
- this,
- );
- if (!dimension) {
- return new ValidationError(t`Invalid template tag: ${tag.name}`);
- }
-
- return dimension.validateTemplateTag();
- })
- .filter(
- (maybeError): maybeError is ValidationError => maybeError != null,
- );
- }
-
private _allTemplateTagsAreValid() {
- const tagErrors = this._validateTemplateTags();
+ const tagErrors = Lib.validateTemplateTags(this._query());
return tagErrors.length === 0;
}
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx
index bc64e8e42a8..d71a9721fdf 100644
--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx
@@ -411,6 +411,7 @@ class NativeQueryEditor extends Component<Props, NativeQueryEditorState> {
this.props.nativeEditorSelectedText
}
runQuery={this.props.runQuery}
+ questionErrors={Lib.validateTemplateTags(question.query())}
/>
)}
</Stack>
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorRunButton/NativeQueryEditorRunButton.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorRunButton/NativeQueryEditorRunButton.tsx
index b9445dfec90..6da2640a3f2 100644
--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorRunButton/NativeQueryEditorRunButton.tsx
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorRunButton/NativeQueryEditorRunButton.tsx
@@ -2,6 +2,7 @@ import { t } from "ttag";
import { METAKEY } from "metabase/lib/browser";
import RunButtonWithTooltip from "metabase/query_builder/components/RunButtonWithTooltip";
+import type * as Lib from "metabase-lib";
import S from "./NativeQueryEditorRunButton.module.css";
@@ -11,6 +12,7 @@ interface NativeQueryEditorRunButtonProps {
isRunnable: boolean;
isRunning: boolean;
nativeEditorSelectedText?: string;
+ questionErrors?: Lib.ValidationError[] | null;
runQuery?: () => void;
}
@@ -21,10 +23,15 @@ const NativeQueryEditorRunButton = (props: NativeQueryEditorRunButtonProps) => {
isRunnable,
isRunning,
nativeEditorSelectedText,
+ questionErrors,
runQuery,
} = props;
const getTooltip = () => {
+ if (questionErrors && questionErrors.length > 0) {
+ return questionErrors[0].message;
+ }
+
const command = nativeEditorSelectedText
? t`Run selected text`
: t`Run query`;
diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/ViewTitleHeaderRightSide.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/ViewTitleHeaderRightSide.tsx
index 6ec964e3f2c..c8fe751dc20 100644
--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/ViewTitleHeaderRightSide.tsx
+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/ViewTitleHeaderRightSide.tsx
@@ -99,7 +99,6 @@ export function ViewTitleHeaderRightSide({
isObjectDetail,
}: ViewTitleHeaderRightSideProps): React.JSX.Element {
const isShowingNotebook = queryBuilderMode === "notebook";
- const { isEditable } = Lib.queryDisplayInfo(question.query());
const canWriteToCollections = useSelector(getUserCanWriteToCollections);
const hasExploreResultsLink =
@@ -143,9 +142,7 @@ export function ViewTitleHeaderRightSide({
const canSave = Lib.canSave(question.query(), question.type());
const isSaveDisabled = !canSave;
const isBrandNew = !isSaved && !result && queryBuilderMode === "notebook";
- const disabledSaveTooltip = isSaveDisabled
- ? getDisabledSaveTooltip(isEditable)
- : undefined;
+ const saveTooltip = getSaveTooltip(question);
useRegisterShortcut(
hasRunButton && !isShowingNotebook
@@ -247,11 +244,7 @@ export function ViewTitleHeaderRightSide({
/>
)}
{hasSaveButton && (
- <Tooltip
- disabled={!disabledSaveTooltip}
- label={disabledSaveTooltip}
- position="left"
- >
+ <Tooltip disabled={!saveTooltip} label={saveTooltip} position="left">
<Button
className={ViewTitleHeaderS.SaveButton}
data-testid="qb-save-button"
@@ -275,8 +268,13 @@ export function ViewTitleHeaderRightSide({
);
}
-function getDisabledSaveTooltip(isEditable: boolean) {
+function getSaveTooltip(question: Question) {
+ const query = question.query();
+ const { isEditable } = Lib.queryDisplayInfo(query);
if (!isEditable) {
return t`You don't have permission to save this question.`;
}
+
+ const errors = Lib.validateTemplateTags(query);
+ return errors[0]?.message;
}
diff --git a/src/metabase/lib/js.cljs b/src/metabase/lib/js.cljs
index e1e02706cea..79c3311cdc6 100644
--- a/src/metabase/lib/js.cljs
+++ b/src/metabase/lib/js.cljs
@@ -74,6 +74,7 @@
[metabase.lib.metadata.calculation :as lib.metadata.calculation]
[metabase.lib.metadata.column :as lib.metadata.column]
[metabase.lib.metadata.protocols :as lib.metadata.protocols]
+ [metabase.lib.native :as lib.native]
[metabase.lib.normalize :as lib.normalize]
[metabase.lib.order-by :as lib.order-by]
[metabase.lib.query :as lib.query]
@@ -2706,3 +2707,11 @@
(or (.get cache js-query)
(u/prog1 (from-js-query* mp js-query)
(.set cache js-query <>)))))
+
+(defn ^:export validate-template-tags
+ "Validates if the template tags in `query` are all valid and well-formed."
+ [js-query]
+ (-> js-query
+ js->clj
+ lib.native/validate-template-tags
+ clj->js))
diff --git a/src/metabase/lib/native.cljc b/src/metabase/lib/native.cljc
index 593f9e2b980..d5de186433d 100644
--- a/src/metabase/lib/native.cljc
+++ b/src/metabase/lib/native.cljc
@@ -368,16 +368,31 @@
(assert-native-query (lib.util/query-stage query 0))
(= :write (:native-permissions (lib.metadata/database query))))
+(mu/defn- validate-template-tag :- [:sequential [:map [:error/message :string] [:tag-name :string]]]
+ "Validate a single template tag, returning a list of errors."
+ [_query {tag-type :type tag-name :name, :keys [display-name dimension]}]
+ (cond-> []
+ (empty? display-name)
+ (conj {:error/message (i18n/tru "Missing widget label: {0}" tag-name)
+ :tag-name tag-name})
+
+ (and (#{:dimension :temporal-unit} tag-type) (nil? dimension))
+ (conj {:error/message (i18n/tru "The variable \"{0}\" needs to be mapped to a field." tag-name)
+ :tag-name tag-name})))
+
+(mu/defn validate-template-tags :- [:sequential [:map [:error/message :string] [:tag-name :string]]]
+ "Given a query, returns a list of errors for each template tag in the query that is not valid."
+ [query]
+ (mapcat #(validate-template-tag query %)
+ (lib.walk.util/all-template-tags query)))
+
(defmethod lib.query/can-run-method :mbql.stage/native
[query _card-type]
(and
(set/subset? (required-native-extras query)
(set (keys (native-extras query))))
(not (str/blank? (raw-native-query query)))
- (every? #(if (#{:dimension :temporal-unit} (:type %))
- (:dimension %)
- true)
- (vals (template-tags query)))))
+ (empty? (validate-template-tags query))))
(mu/defn engine :- [:maybe :keyword]
"Returns the database engine.
diff --git a/test/metabase/lib/native_test.cljc b/test/metabase/lib/native_test.cljc
index 61cd6943971..3e01d00c5be 100644
--- a/test/metabase/lib/native_test.cljc
+++ b/test/metabase/lib/native_test.cljc
@@ -590,3 +590,58 @@
:type :temporal-unit}})
lib/add-parameters-for-template-tags
:parameters))))
+
+(deftest ^:parallel validate-template-tags-test
+ (testing "valid template tags should return no errors"
+ (are
+ [template-tags]
+ (= [] (lib.native/validate-template-tags
+ (lib/query (lib.tu/metadata-provider-with-mock-cards)
+ {:database (meta/id)
+ :type :native
+ :native {:query {}
+ :template-tags template-tags}})))
+ {}
+
+ {"mytag" {:type :number
+ :name "mytag"
+ :display-name "My Tag"
+ :id "9ae1ea5e-ac33-4574-bc95-ff595b0ac1a7"}}))
+
+ (testing "invalid template tags should return the correct errors"
+ (mu/disable-enforcement
+ (are
+ [errors template-tags]
+ (= errors (lib.native/validate-template-tags
+ (lib/query (lib.tu/metadata-provider-with-mock-cards)
+ {:database (meta/id)
+ :type :native
+ :native {:query {}
+ :template-tags template-tags}})))
+ [{:tag-name "mytag"
+ :error/message "The variable \"mytag\" needs to be mapped to a field."}]
+ {"mytag" {:type :dimension
+ :name "mytag"
+ :display-name "My Tag"
+ :id "9ae1ea5e-ac33-4574-bc95-ff595b0ac1a7"}}
+
+ [{:tag-name "mytag"
+ :error/message "The variable \"mytag\" needs to be mapped to a field."}]
+ {"mytag" {:type :temporal-unit
+ :name "mytag"
+ :display-name "My Tag"
+ :id "9ae1ea5e-ac33-4574-bc95-ff595b0ac1a7"}}
+
+ [{:tag-name "mytag"
+ :error/message "Missing widget label: mytag"}]
+ {"mytag" {:type :number
+ :name "mytag"
+ :id "9ae1ea5e-ac33-4574-bc95-ff595b0ac1a7"}}
+
+ [{:tag-name "mytag"
+ :error/message "Missing widget label: mytag"}
+ {:tag-name "mytag"
+ :error/message "The variable \"mytag\" needs to be mapped to a field."}]
+ {"mytag" {:type :dimension
+ :name "mytag"
+ :id "9ae1ea5e-ac33-4574-bc95-ff595b0ac1a7"}}))))