Skip to content

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

Enable editing/creating native questions in the SDK (#68138)

Sébastien1b80d7dc168e
diff --git a/docs/embedding/sdk/questions.md b/docs/embedding/sdk/questions.md
index 2cfcc8e0550..980804a7d98 100644
--- a/docs/embedding/sdk/questions.md
+++ b/docs/embedding/sdk/questions.md
@@ -162,10 +162,20 @@ To prevent people from saving changes to an interactive question, or from saving
![Query builder](../images/query-builder.png)
+### Embed the visual query builder
+
You can embed the query builder for creating new questions by passing the `questionId="new"` prop to the `InteractiveQuestion` component. You can use the [`children` prop](#customizing-interactive-questions) to customize the layout for creating new questions.
```tsx
{% include_file "{{ dirname }}/snippets/questions/new-question.tsx" %}
```
+### Embed the SQL editor
+
+You can also embed the SQL editor to enable people to build questions with SQL by passing `questionId="new-native"` to the `InteractiveQuestion` component:
+
+```tsx
+{% include_file "{{ dirname }}/snippets/questions/new-native-question.tsx" %}
+```
+
To customize the question editor's layout, use the `InteractiveQuestion` component [directly with a custom `children` prop](#customizing-interactive-questions).
diff --git a/docs/embedding/sdk/snippets/questions/new-native-question.tsx b/docs/embedding/sdk/snippets/questions/new-native-question.tsx
new file mode 100644
index 00000000000..b3e6575c6f2
--- /dev/null
+++ b/docs/embedding/sdk/snippets/questions/new-native-question.tsx
@@ -0,0 +1,18 @@
+import React from "react";
+import {
+ InteractiveQuestion,
+ MetabaseProvider,
+ defineMetabaseAuthConfig,
+} from "@metabase/embedding-sdk-react";
+
+const authConfig = defineMetabaseAuthConfig({
+ metabaseInstanceUrl: "https://your-metabase.example.com",
+});
+
+export default function App() {
+ return (
+ <MetabaseProvider authConfig={authConfig}>
+ <InteractiveQuestion questionId="new-native" />
+ </MetabaseProvider>
+ );
+}
\ No newline at end of file
diff --git a/e2e/support/helpers/e2e-native-editor-helpers.ts b/e2e/support/helpers/e2e-native-editor-helpers.ts
index 33b4458f994..96fe757e377 100644
--- a/e2e/support/helpers/e2e-native-editor-helpers.ts
+++ b/e2e/support/helpers/e2e-native-editor-helpers.ts
@@ -10,7 +10,14 @@ export function selectNativeEditorDataSource(name: string) {
popover().findByText(name).click();
}
+function clickOnRun() {
+ cy.findByTestId("native-query-editor-container").within(() =>
+ cy.findByTestId("run-button").click(),
+ );
+}
+
export const NativeEditor = codeMirrorHelpers("native-query-editor", {
dataSource: nativeEditorDataSource,
selectDataSource: selectNativeEditorDataSource,
+ clickOnRun,
});
diff --git a/e2e/test-component/scenarios/embedding-sdk/interactive-question.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/interactive-question.cy.spec.tsx
index 8f049f985b5..77761e8a58a 100644
--- a/e2e/test-component/scenarios/embedding-sdk/interactive-question.cy.spec.tsx
+++ b/e2e/test-component/scenarios/embedding-sdk/interactive-question.cy.spec.tsx
@@ -47,4 +47,59 @@ describe("scenarios > embedding-sdk > interactive-question", () => {
H.assertTableRowsCount(4);
});
});
+
+ it("should be able to edit a native question with the QueryEditor", () => {
+ cy.intercept("GET", "/api/database").as("schema");
+
+ cy.get("@sqlQuestionId").then((sqlQuestionId) => {
+ mountSdkContent(
+ <InteractiveQuestion questionId={sqlQuestionId} withParameters />,
+ );
+ });
+
+ getSdkRoot().within(() => {
+ cy.findByText("SQL Orders").should("be.visible");
+ H.assertTableRowsCount(5);
+
+ cy.findByTestId("notebook-button").click();
+ cy.findByTestId("native-query-editor").should("be.visible");
+ cy.wait("@schema");
+
+ H.NativeEditor.value().should("equal", "select * from ORDERS limit 5");
+ cy.findByRole("textbox").should("be.visible").click();
+
+ H.NativeEditor.type("{movetoend}{backspace}10");
+
+ H.NativeEditor.clickOnRun();
+
+ cy.button("Visualize").should("be.visible").click();
+
+ H.assertTableRowsCount(10);
+ });
+ });
+
+ it("should be able to create a native question with the QueryEditor", () => {
+ cy.intercept("GET", "/api/database?can-query=true").as("schema");
+
+ mountSdkContent(
+ <InteractiveQuestion questionId="new-native" withParameters />,
+ );
+
+ getSdkRoot().within(() => {
+ cy.findByTestId("native-query-editor").should("be.visible");
+ cy.findByLabelText("placeholder SELECT * FROM TABLE_NAME").should(
+ "be.visible",
+ );
+
+ cy.wait("@schema");
+
+ H.NativeEditor.type("SELECT * from ORDERS LIMIT 10");
+
+ H.NativeEditor.clickOnRun();
+
+ cy.button("Visualize").should("be.visible").click();
+
+ H.assertTableRowsCount(10);
+ });
+ });
});
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/Editor.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/Editor.tsx
index 7a020396d13..264ba543221 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/Editor.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/Editor.tsx
@@ -11,8 +11,11 @@ import { Notebook as QBNotebook } from "metabase/querying/notebook/components/No
import { getMetadata } from "metabase/selectors/metadata";
import { getSetting } from "metabase/selectors/settings";
import { ScrollArea } from "metabase/ui";
+import * as Lib from "metabase-lib";
import Question from "metabase-lib/v1/Question";
+import { QueryEditorAndResults } from "./QueryEditorAndResults";
+
/**
* @interface
* @expand
@@ -70,28 +73,43 @@ export const Editor = ({
getSetting(state, "report-timezone-long"),
);
- return (
- question && (
- <ScrollArea w="100%" h="100%">
- <QBNotebook
- question={question}
- isDirty={isDirty}
- isRunnable={isRunnable}
- // the visualization button relies on this boolean
- isResultDirty={true}
- reportTimezone={reportTimezone}
- readOnly={false}
- updateQuestion={async (nextQuestion: Question) =>
- await updateQuestion(nextQuestion, { run: false })
- }
- runQuestionQuery={async () => {
- onApply();
- await queryQuestion();
- }}
- setQueryBuilderMode={() => {}}
- hasVisualizeButton={hasVisualizeButton}
- />
- </ScrollArea>
- )
+ if (!question) {
+ return null;
+ }
+
+ return Lib.queryDisplayInfo(question.query()).isNative ? (
+ <QueryEditorAndResults
+ question={question}
+ hasVisualizeButton={hasVisualizeButton}
+ isDirty={isDirty}
+ updateQuestion={async (nextQuestion: Question) =>
+ await updateQuestion(nextQuestion, { run: false })
+ }
+ runQuestionQuery={async () => {
+ onApply();
+ await queryQuestion();
+ }}
+ />
+ ) : (
+ <ScrollArea w="100%" h="100%">
+ <QBNotebook
+ question={question}
+ isDirty={isDirty}
+ isRunnable={isRunnable}
+ // the visualization button relies on this boolean
+ isResultDirty={true}
+ reportTimezone={reportTimezone}
+ readOnly={false}
+ updateQuestion={async (nextQuestion: Question) =>
+ await updateQuestion(nextQuestion, { run: false })
+ }
+ runQuestionQuery={async () => {
+ onApply();
+ await queryQuestion();
+ }}
+ setQueryBuilderMode={() => {}}
+ hasVisualizeButton={hasVisualizeButton}
+ />
+ </ScrollArea>
);
};
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/EditorButton/EditorButton.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/EditorButton/EditorButton.tsx
index a5fd9ae0908..a25355e226c 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/EditorButton/EditorButton.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/EditorButton/EditorButton.tsx
@@ -1,8 +1,9 @@
import type { HTMLAttributes, MouseEventHandler } from "react";
import { useSdkQuestionContext } from "embedding-sdk-bundle/components/private/SdkQuestion/context";
-import { QuestionNotebookButton } from "metabase/query_builder/components/view/ViewHeader/components";
import { ActionIcon, type ActionIconProps, Icon } from "metabase/ui";
+import * as Lib from "metabase-lib";
+import type Question from "metabase-lib/v1/Question";
import S from "./EditorButton.module.css";
@@ -25,6 +26,21 @@ export type EditorButtonProps = {
} & ActionIconProps &
HTMLAttributes<HTMLButtonElement>;
+function shouldShowEditButton({
+ question,
+ isActionListVisible,
+ isBrandNew = false,
+}: {
+ question: Question;
+ isActionListVisible: boolean;
+ isBrandNew?: boolean;
+}) {
+ const { isEditable } = Lib.queryDisplayInfo(question.query());
+ return (
+ isEditable && isActionListVisible && !question.isArchived() && !isBrandNew
+ );
+}
+
/**
* Toggle button for showing/hiding the Editor interface.
* In custom layouts, the `EditorButton` _must_ have an {@link InteractiveQuestionEditorButtonProps.onClick}` handler or the button won't do anything when clicked.
@@ -40,7 +56,7 @@ export const EditorButton = ({
const { question } = useSdkQuestionContext();
return (
question &&
- QuestionNotebookButton.shouldRender({
+ shouldShowEditButton({
question,
isActionListVisible: true,
}) && (
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/QueryEditorAndResults.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/QueryEditorAndResults.tsx
new file mode 100644
index 00000000000..9d6cfcce8d7
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/QueryEditorAndResults.tsx
@@ -0,0 +1,75 @@
+import { useState } from "react";
+
+import {
+ QueryEditor,
+ getInitialUiState,
+} from "metabase/querying/editor/components/QueryEditor";
+import { useQueryResults } from "metabase/querying/editor/hooks/use-query-results";
+import { VisualizeButton } from "metabase/querying/notebook/components/Notebook";
+import type * as Lib from "metabase-lib";
+import type Question from "metabase-lib/v1/Question";
+
+interface QueryEditorAndResultsProps {
+ question: Question;
+ hasVisualizeButton?: boolean;
+ isDirty: boolean;
+ runQuestionQuery?: () => Promise<void>;
+ updateQuestion: (question: Question) => Promise<void>;
+}
+
+export function QueryEditorAndResults(props: QueryEditorAndResultsProps) {
+ const {
+ question: initialQuestion,
+ hasVisualizeButton = true,
+ isDirty,
+ runQuestionQuery,
+ updateQuestion,
+ } = props;
+
+ const [uiState, setUiState] = useState(getInitialUiState);
+ const [currentQuestion, setCurrentQuestion] = useState(initialQuestion);
+
+ const { isRunnable, runQuery, result } = useQueryResults(
+ currentQuestion,
+ uiState,
+ setUiState,
+ );
+
+ const onQueryChange = (query: Lib.Query) => {
+ const updatedQuestion = currentQuestion.setQuery(query);
+ setCurrentQuestion(updatedQuestion);
+ updateQuestion(updatedQuestion);
+ };
+
+ const handleRunQuery = () => {
+ if (isRunnable) {
+ runQuery();
+ }
+ };
+
+ return (
+ <>
+ <QueryEditor
+ query={currentQuestion.query()}
+ uiState={uiState}
+ onChangeQuery={onQueryChange}
+ onChangeUiState={setUiState}
+ onAcceptProposed={handleRunQuery}
+ onRejectProposed={() => {}}
+ height={hasVisualizeButton ? "calc(100% - 100px)" : undefined}
+ extraEditorButton={
+ hasVisualizeButton && runQuestionQuery && result && !result?.error ? (
+ <VisualizeButton
+ question={currentQuestion}
+ isDirty={isDirty}
+ isRunnable={isRunnable}
+ isResultDirty
+ updateQuestion={updateQuestion}
+ runQuestionQuery={runQuestionQuery}
+ />
+ ) : undefined
+ }
+ />
+ </>
+ );
+}
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx
index 720985311c5..e980a6473b9 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx
@@ -77,7 +77,7 @@ export const SdkQuestionProvider = ({
useSetupContentTranslations({ token });
- const isNewQuestion = questionId === "new";
+ const isNewQuestion = questionId === "new" || questionId === "new-native";
const error = useSdkSelector(getError);
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx
index e04f592ffa6..d5be8f8dabe 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx
@@ -124,12 +124,12 @@ export const SdkQuestionDefaultView = ({
question && shouldRunCardQuery({ question, isGuestEmbed }) && !queryResults;
useEffect(() => {
- const isNewQuestion = originalId === "new";
+ const isNewQuestion = originalId === "new" || originalId === "new-native";
const isExistingQuestion =
question &&
!isQuestionLoading &&
question?.isSaved() &&
- originalId !== "new" &&
+ !isNewQuestion &&
queryResults;
const onNavigate = onNavigateBack ?? onReset ?? undefined;
@@ -137,7 +137,7 @@ export const SdkQuestionDefaultView = ({
if (isNewQuestion) {
reportLocation({
type: "question",
- id: "new",
+ id: originalId,
name: "New exploration",
onNavigate,
});
diff --git a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.EditorButton.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.EditorButton.unit.spec.tsx
index caa33db0701..82fccb37c7e 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.EditorButton.unit.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.EditorButton.unit.spec.tsx
@@ -13,7 +13,6 @@ import { screen } from "__support__/ui";
import { renderWithSDKProviders } from "embedding-sdk-bundle/test/__support__/ui";
import { createMockSdkConfig } from "embedding-sdk-bundle/test/mocks/config";
import { setupSdkState } from "embedding-sdk-bundle/test/server-mocks/sdk-init";
-import { QuestionNotebookButton } from "metabase/query_builder/components/view/ViewHeader/components";
import {
createMockCard,
createMockCardQueryMetadata,
@@ -115,20 +114,15 @@ describe("InteractiveQuestion.EditorButton", () => {
});
it("should render the editor button", async () => {
- const shouldRenderSpy = jest.spyOn(QuestionNotebookButton, "shouldRender");
-
setup({ isOpen: true });
expect(await screen.findByTestId("notebook-button")).toBeInTheDocument();
- expect(shouldRenderSpy).toHaveBeenCalledTimes(1);
});
it("should fire click handler when clicking the notebook button", async () => {
- const shouldRenderSpy = jest.spyOn(QuestionNotebookButton, "shouldRender");
const { clickSpy } = setup({ isOpen: true });
await userEvent.click(await screen.findByTestId("notebook-button"));
- expect(shouldRenderSpy).toHaveBeenCalledTimes(1);
expect(clickSpy).toHaveBeenCalledTimes(1);
});
});
diff --git a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/types.ts b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/types.ts
index 4f4805a157f..2b751ef5301 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/types.ts
+++ b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/types.ts
@@ -11,6 +11,8 @@ export type SdkQuestionIdProps = {
* - The `entity_id` key of the question object. You can find a question's Entity ID in the info panel when viewing a question
* <br/>
* - `new` to show the notebook editor for creating new questions. `isSaveEnabled` must be `true` to allow saving the question
+ * <br/>
+ * - `new-native` to show the SQL editor for creating new native questions. `isSaveEnabled` must be `true` to allow saving the question
*/
questionId: SdkQuestionId | null;
};
diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-existing-question-editor-sync.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-existing-question-editor-sync.ts
index acb45cffd1d..1927563655d 100644
--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-existing-question-editor-sync.ts
+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-existing-question-editor-sync.ts
@@ -28,7 +28,8 @@ export function useExistingQuestionEditorSync({
}
const isTransitionToExistingQuestion =
- prevOriginalId === "new" && originalId !== "new";
+ (prevOriginalId === "new" && originalId !== "new") ||
+ (prevOriginalId === "new-native" && originalId !== "new-native");
const isTransitionToSaved = !isPrevQuestionSaved && isQuestionSaved;
if (isTransitionToExistingQuestion || isTransitionToSaved) {
diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-question-editor-sync.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-question-editor-sync.ts
index 15d9bc31add..06aa68ddee7 100644
--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-question-editor-sync.ts
+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-question-editor-sync.ts
@@ -22,7 +22,7 @@ export function useQuestionEditorSync({
queryResults,
queryQuestion,
}: UseQuestionEditorSyncOptions) {
- const isNewQuestion = originalId === "new";
+ const isNewQuestion = originalId === "new" || originalId === "new-native";
const [
isEditorOpen,
diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-question/load-question.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-question/load-question.ts
index 0601898b35f..7c85a6b07f8 100644
--- a/frontend/src/embedding-sdk-bundle/lib/sdk-question/load-question.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-question/load-question.ts
@@ -37,7 +37,9 @@ export const loadQuestionSdk =
> => {
const isGuestEmbed = getIsGuestEmbed(getState());
- const isNewQuestion = initQuestionId === "new";
+ const isNewQuestion =
+ initQuestionId === "new" || initQuestionId === "new-native";
+ const isNativeQuestion = initQuestionId === "new-native";
const questionId = isNewQuestion ? undefined : initQuestionId;
const { card: resolvedCard, originalCard } = await resolveCards({
@@ -47,6 +49,7 @@ export const loadQuestionSdk =
dispatch,
getState,
deserializedCard,
+ questionType: isNativeQuestion ? "native" : "gui",
});
const card = isNewQuestion
diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts
index 804baaabf11..674f8405393 100644
--- a/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts
@@ -3,7 +3,6 @@ import type { SdkQuestionState } from "embedding-sdk-bundle/types/question";
import type { Deferred } from "metabase/lib/promise";
import { runQuestionQuery } from "metabase/services";
import { getSensibleDisplays } from "metabase/visualizations";
-import * as Lib from "metabase-lib";
import type Question from "metabase-lib/v1/Question";
import type { ParameterValuesMap } from "metabase-types/api";
import type { EntityToken } from "metabase-types/api/entity";
@@ -90,8 +89,5 @@ export function shouldRunCardQuery({
return true;
}
- const query = question.query();
- const { isNative } = Lib.queryDisplayInfo(query);
-
- return question.canRun() && (question.isSaved() || !isNative);
+ return question.canRun();
}
diff --git a/frontend/src/embedding-sdk-bundle/types/question.ts b/frontend/src/embedding-sdk-bundle/types/question.ts
index edc7dc82409..c6a65704056 100644
--- a/frontend/src/embedding-sdk-bundle/types/question.ts
+++ b/frontend/src/embedding-sdk-bundle/types/question.ts
@@ -11,7 +11,29 @@ import type { SdkEntityId, SdkEntityToken } from "./entity";
export type { MetabaseQuestion } from "metabase/embedding-sdk/types/question";
-export type SdkQuestionId = number | "new" | SdkEntityId;
+/**
+ * Represents the identifier for a question in the Metabase SDK.
+ *
+ * @example
+ * ```typescript
+ * // Numerical ID from question URL
+ * const questionId: SdkQuestionId = 123;
+ *
+ * // Entity ID string
+ * const questionId: SdkQuestionId = "abc123def456";
+ *
+ * // Create new notebook-style question
+ * const questionId: SdkQuestionId = "new";
+ *
+ * // Create new native SQL question
+ * const questionId: SdkQuestionId = "new-native";
+ * ```
+ */
+export type SdkQuestionId =
+ | number // Numerical question ID (e.g., 123)
+ | "new" // Create new notebook-style question
+ | "new-native" // Create new native SQL question
+ | SdkEntityId; // Entity ID string (e.g., "abc123def456")
export type SdkQuestionEntityPublicProps =
| {
@@ -23,6 +45,10 @@ export type SdkQuestionEntityPublicProps =
* - the numerical ID when accessing a question link, i.e. `http://localhost:3000/question/1-my-question` where the ID is `1`
* <br/>
* - the string ID found in the `entity_id` key of the question object when using the API directly or using the SDK Collection Browser to return data
+ * <br/>
+ * - `new` to show the notebook editor for creating new questions
+ * <br/>
+ * - `new-native` to show the SQL editor for creating new native questions
*/
questionId: SdkQuestionId | null;
token?: never;
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/analytics.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/analytics.ts
index 06239db36d4..2bf71f658f2 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/analytics.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/analytics.ts
@@ -132,6 +132,7 @@ export function createEmbeddedAnalyticsJsUsage(
})
.with(
{ componentName: "metabase-question", questionId: "new" },
+ { componentName: "metabase-question", questionId: "new-native" },
(properties) => {
if (!usage.exploration) {
usage = assocIn(usage, ["exploration"], {
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx
index 4963da611e2..ecd75073280 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx
@@ -206,7 +206,11 @@ const SdkIframeEmbedView = ({
// Embedding based on a questionId (Metabase Account auth type) with disabled drills
{
componentName: "metabase-question",
- questionId: P.intersection(P.nonNullable, P.not("new")),
+ questionId: P.intersection(
+ P.nonNullable,
+ P.not("new"),
+ P.not("new-native"),
+ ),
drills: false,
},
// Embedding based on a token (Guest Embed auth type) with default/disabled drills
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts
index 1c9dd7ac1b9..91a2825b554 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts
@@ -213,7 +213,9 @@ export type SdkIframeEmbedElementSettings = SdkIframeEmbedBaseSettings &
(
| DashboardEmbedOptions
| QuestionEmbedOptions
- | (Omit<ExplorationEmbedOptions, "questionId"> & { questionId: "new" })
+ | (Omit<ExplorationEmbedOptions, "questionId"> & {
+ questionId: "new" | "new-native";
+ })
| BrowserEmbedOptions
| MetabotEmbedOptions
);
diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
index fe55d183c39..1ac46f125de 100644
--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
@@ -92,6 +92,25 @@ function getCardForBlankQuestion(
return question.card();
}
+function getCardForBlankNativeQuestion(
+ metadata: Metadata,
+ options: BlankQueryOptions,
+) {
+ const databaseId = options.db ? parseInt(options.db) : undefined;
+
+ // TODO don't use DEPRECATED_RAW_MBQL_* as it'd be better to:
+ // 1° load the db first
+ // 2° use the lib to create a provider
+ // 3° then create a native query
+ const question = Question.create({
+ DEPRECATED_RAW_MBQL_type: "native",
+ DEPRECATED_RAW_MBQL_databaseId: databaseId,
+ metadata,
+ });
+
+ return question.card();
+}
+
function filterBySegmentId(question: Question, segmentId: SegmentId) {
const stageIndex = -1;
const query = question.query();
@@ -178,6 +197,7 @@ export async function resolveCards({
options,
dispatch,
getState,
+ questionType,
}: {
cardId?: string | number;
token?: EntityToken | null;
@@ -185,13 +205,17 @@ export async function resolveCards({
options: BlankQueryOptions;
dispatch: Dispatch;
getState: GetState;
+ questionType?: "native" | "gui";
}): Promise<ResolveCardsResult> {
if (!cardId && !deserializedCard) {
const metadata = getMetadata(getState());
- return {
- card: getCardForBlankQuestion(metadata, options),
- };
+ const card =
+ questionType === "native"
+ ? getCardForBlankNativeQuestion(metadata, options)
+ : getCardForBlankQuestion(metadata, options);
+
+ return { card };
}
return cardId
? fetchAndPrepareSavedQuestionCards({ cardId, token }, dispatch, getState)
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx
index 22c9c0fb9b2..3d248b1957f 100644
--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx
@@ -117,6 +117,7 @@ type OwnProps = {
onSetDatabaseId?: (id: DatabaseId) => void;
databaseIsDisabled?: (database: Database) => boolean;
topBarInnerContent?: ReactNode;
+ extraButton?: ReactNode;
onBlur?: () => void;
};
@@ -262,6 +263,7 @@ class NativeQueryEditor extends Component<Props, NativeQueryEditorState> {
highlightedLineNumbers,
placeholder,
extensions,
+ extraButton,
onBlur,
} = this.props;
@@ -404,19 +406,24 @@ class NativeQueryEditor extends Component<Props, NativeQueryEditorState> {
</Tooltip>
</>
)}
- {hasRunButton && !readOnly && (
- <NativeQueryEditorRunButton
- cancelQuery={this.props.cancelQuery}
- isResultDirty={this.props.isResultDirty}
- isRunnable={this.props.isRunnable}
- isRunning={this.props.isRunning}
- nativeEditorSelectedText={
- this.props.nativeEditorSelectedText
- }
- runQuery={this.props.runQuery}
- questionErrors={Lib.validateTemplateTags(question.query())}
- />
- )}
+ <Flex gap="sm">
+ {extraButton}
+ {hasRunButton && !readOnly && (
+ <NativeQueryEditorRunButton
+ cancelQuery={this.props.cancelQuery}
+ isResultDirty={this.props.isResultDirty}
+ isRunnable={this.props.isRunnable}
+ isRunning={this.props.isRunning}
+ nativeEditorSelectedText={
+ this.props.nativeEditorSelectedText
+ }
+ runQuery={this.props.runQuery}
+ questionErrors={Lib.validateTemplateTags(
+ question.query(),
+ )}
+ />
+ )}
+ </Flex>
</Stack>
</Flex>
</ResizableBox>
diff --git a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsx b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsx
index 0955ca79b2b..1b3138262e1 100644
--- a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsx
+++ b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsx
@@ -28,6 +28,8 @@ type QueryEditorProps = {
onRejectProposed?: () => void;
onBlur?: () => void;
topBarInnerContent?: ReactNode;
+ height?: string | number;
+ extraEditorButton?: ReactNode;
};
export function QueryEditor({
@@ -41,6 +43,8 @@ export function QueryEditor({
onRejectProposed,
onBlur,
topBarInnerContent,
+ height = "100%",
+ extraEditorButton,
}: QueryEditorProps) {
const {
question,
@@ -78,7 +82,7 @@ export function QueryEditor({
if (isLoading || error != null) {
return (
- <Center h="100%">
+ <Center h={height}>
<LoadingAndErrorWrapper loading={isLoading} error={error} />
</Center>
);
@@ -86,7 +90,7 @@ export function QueryEditor({
return (
<>
- <Flex flex={1} h="100%" mih={0}>
+ <Flex flex={1} h={height} mih={0}>
<Flex flex="2 1 0" miw={0} direction="column" pos="relative">
<QueryEditorBody
question={question}
@@ -116,6 +120,7 @@ export function QueryEditor({
onRejectProposed={onRejectProposed}
onBlur={onBlur}
topBarInnerContent={topBarInnerContent}
+ extraButton={extraEditorButton}
/>
<QueryEditorVisualization
question={question}
diff --git a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsx b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsx
index fe52fad41a5..797ca252874 100644
--- a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsx
+++ b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsx
@@ -69,6 +69,7 @@ type QueryEditorBodyProps = {
onRejectProposed?: () => void;
onBlur?: () => void;
topBarInnerContent?: ReactNode;
+ extraButton?: ReactNode;
};
export function QueryEditorBody({
@@ -99,6 +100,7 @@ export function QueryEditorBody({
onRejectProposed,
onBlur,
topBarInnerContent,
+ extraButton,
}: QueryEditorBodyProps) {
const [isResizing, setIsResizing] = useState(false);
const reportTimezone = useSetting("report-timezone-long");
@@ -165,6 +167,7 @@ export function QueryEditorBody({
onRejectProposed={onRejectProposed}
onBlur={onBlur}
topBarInnerContent={topBarInnerContent}
+ extraButton={extraButton}
/>
) : (
<ResizableBox