Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: add sql formatting button to sql cells (#4640)

Myles Scolnickd3778c156fd4
diff --git a/frontend/package.json b/frontend/package.json
index d4ca6cd226..99c8e1b2c7 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -135,6 +135,7 @@
"react-virtuoso": "^4.12.6",
"reactflow": "^11.11.4",
"rpc-anywhere": "^1.7.0",
+ "sql-formatter": "^15.6.0",
"string-dedent": "^3.0.1",
"swiper": "^11.2.6",
"tailwind-merge": "^2.6.0",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 92bb56ef2d..07efb6cdaf 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -381,6 +381,9 @@ importers:
rpc-anywhere:
specifier: ^1.7.0
version: 1.7.0
+ sql-formatter:
+ specifier: ^15.6.0
+ version: 15.6.0
string-dedent:
specifier: ^3.0.1
version: 3.0.1
@@ -5060,6 +5063,9 @@ packages:
resolution: {integrity: sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-c68LpLbO+7kP/b1Hr1qs8/BJ09F5khZGTxqxZuhzxpmwJKOgRFHJWIb9/KmqnqHhLdO55aOxFH/EGBvUQbL/RQ==}
+
resolution: {integrity: sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==}
@@ -6693,6 +6699,9 @@ packages:
resolution: {integrity: sha512-tN3dvVHYVz4DhSXinXIk7u9syPYaJvio118uomkovAtWBT+RdbP6Lfh/5Lvo519YMmwBafwlh20IPTXIStscpA==}
+ resolution: {integrity: sha512-iSAJLHYKnX41mKcJKjqvnAN9sf0LMDTXDEvFv+ffuRR9a1MIuXLjMNL6EsnDHSkKLTWNqQQ5uo61P4EbU4NU+Q==}
+
resolution: {integrity: sha512-vpN0s+zLL2ykyyUDh+fayu9Xkor5v/zRD9jhSqjRS1cJTGS0+oakVZzNm5n19JvvEj0you+MXlYTpNxUDQUjkQ==}
@@ -6735,6 +6744,10 @@ packages:
resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==}
+ resolution: {integrity: sha512-+Mc8UaAebFzgV+KpI5n7DasuuQCHA89dmwm7JXw3TV43ukfNQ9DnBH3Mdb2g/I4Fdxc26pwimBWvjIw0UAILSQ==}
+ hasBin: true
+
resolution: {integrity: sha512-6R9fqJ5Zcmf+uYaFgdIHmLwNldn5HbK8L5ybn7Uz+ylX/rnOsSp1AHcvQSrCaFN+qNM1wpymHqD7mVasEOlHGQ==}
engines: {node: '>= 4.4.x'}
@@ -7427,6 +7440,13 @@ packages:
resolution: {integrity: sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA==}
+ resolution: {integrity: sha512-cz93DjNeLY0idrCNOH6PviZGRN9GJhsdm9hpn1YCS879fj4W+x5IFJhhkRZcwVgMmFF7R82UA/7Oh+R8lLZg6A==}
+
+ resolution: {integrity: sha512-80WNmd9DA0tmZrw9qQa62GPPWfuXJknrmVmLcxvq4uZBdYqb1wYoKTmnlGUchvVWe0XiLupYkBoXVOxz3C8DYQ==}
+ engines: {node: '>=0.12'}
+
resolution: {integrity: sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==}
@@ -7797,6 +7817,10 @@ packages:
resolution: {integrity: sha512-U7WjGVG9sH8tvjW5SmGbQuui75FiyjAX72HX15DwBBwF9dNiQZRQAg9nnPhYy+TUnE0+VcrttuvNI8oSxZcocA==}
hasBin: true
+ resolution: {integrity: sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==}
+ engines: {node: '>=0.12'}
+
resolution: {integrity: sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==}
engines: {iojs: '>=1.0.0', node: '>=0.10.0'}
@@ -7973,6 +7997,10 @@ packages:
resolution: {integrity: sha512-rr+VVSXtRhO4OHbXUiAF7xW3Bo9DuuF6C5jH+q/x15j2jniycgKbxU09Hr0WqlSLUs4i4ltHGXqTe7VHclYWyA==}
+ resolution: {integrity: sha512-PFJoCMXx42aoKaSIDhqLBJ/vKHBbwMlFPaW9YFlI99V+VWq2sV31xi3JH/StCovlZ1X5jpqwZMl9vq+X0s6bFw==}
+ hasBin: true
+
resolution: {integrity: sha512-2p2KJZTSqQ/I3+HX42EpYOa2l3f8Erv8MWKsy2I9uf4wA7yFIkXRffYdsx86y6z4vHtV8u7g+pPlr8/4ouAxsQ==}
engines: {node: '>=0.10.0'}
@@ -14717,6 +14745,8 @@ snapshots:
dependencies:
path-type: 4.0.0
+
@@ -16774,6 +16804,8 @@ snapshots:
pkg-types: 1.2.1
ufo: 1.5.4
+
dependencies:
mouse-event: 1.0.5
@@ -16813,6 +16845,13 @@ snapshots:
+ dependencies:
+ commander: 2.20.3
+ moo: 0.5.2
+ railroad-diagrams: 1.0.0
+ randexp: 0.4.6
+
dependencies:
debug: 3.2.7
@@ -17524,6 +17563,13 @@ snapshots:
dependencies:
performance-now: 2.1.0
+
+ dependencies:
+ discontinuous-range: 1.0.0
+ ret: 0.1.15
+
dependencies:
safe-buffer: 5.2.1
@@ -18128,6 +18174,8 @@ snapshots:
path-parse: 1.0.7
supports-preserve-symlinks-flag: 1.0.0
+
@@ -18326,6 +18374,11 @@ snapshots:
+ dependencies:
+ argparse: 2.0.1
+ nearley: 2.20.1
+
dependencies:
asn1: 0.2.6
diff --git a/frontend/src/core/codemirror/__tests__/format.test.ts b/frontend/src/core/codemirror/__tests__/format.test.ts
new file mode 100644
index 0000000000..eae3599454
--- /dev/null
+++ b/frontend/src/core/codemirror/__tests__/format.test.ts
@@ -0,0 +1,224 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { EditorView } from "@codemirror/view";
+import { EditorState } from "@codemirror/state";
+import { python } from "@codemirror/lang-python";
+import type { CellId } from "@/core/cells/ids";
+import { formatEditorViews, formatAll, formatSQL } from "../format";
+import {
+ adaptiveLanguageConfiguration,
+ switchLanguage,
+} from "../language/extension";
+import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";
+import { sendFormat } from "@/core/network/requests";
+import { getNotebook } from "@/core/cells/cells";
+import { notebookCellEditorViews } from "@/core/cells/utils";
+import { getResolvedMarimoConfig } from "@/core/config/config";
+import type { NotebookState } from "@/core/cells/cells";
+import { cellActionsState, type CodemirrorCellActions } from "../cells/state";
+import type { MarimoConfig } from "@/core/network/types";
+import { cellIdState } from "../config/extension";
+
+vi.mock("@/core/network/requests", () => ({
+ sendFormat: vi.fn(),
+}));
+
+vi.mock("@/core/cells/cells", () => ({
+ getNotebook: vi.fn(),
+}));
+
+vi.mock("@/core/cells/utils", () => ({
+ notebookCellEditorViews: vi.fn(),
+}));
+
+vi.mock("@/core/config/config", () => ({
+ getResolvedMarimoConfig: vi.fn(),
+}));
+
+const updateCellCode = vi.fn();
+
+function createEditor(content: string, cellId: CellId) {
+ const state = EditorState.create({
+ doc: content,
+ extensions: [
+ python(),
+ adaptiveLanguageConfiguration({
+ cellId,
+ completionConfig: {
+ activate_on_typing: true,
+ copilot: false,
+ codeium_api_key: null,
+ },
+ hotkeys: new OverridingHotkeyProvider({}),
+ placeholderType: "marimo-import",
+ lspConfig: {},
+ }),
+ cellIdState.of(cellId),
+ cellActionsState.of({
+ updateCellCode,
+ } as unknown as CodemirrorCellActions),
+ ],
+ });
+
+ const view = new EditorView({
+ state,
+ parent: document.body,
+ });
+
+ return view;
+}
+
+const mockConfig = {
+ formatting: { line_length: 88 },
+} as MarimoConfig;
+
+beforeEach(() => {
+ updateCellCode.mockClear();
+});
+
+describe("format", () => {
+ describe("formatEditorViews", () => {
+ it("should format code in editor views", async () => {
+ const cellId1 = "1" as CellId;
+ const cellId2 = "2" as CellId;
+ const views = {
+ [cellId1]: createEditor("import numpy as np", cellId1),
+ [cellId2]: createEditor("import pandas as pd", cellId2),
+ };
+
+ const formattedCode1 = "import numpy as np";
+ const formattedCode2 = "import pandas as pd";
+
+ vi.mocked(sendFormat).mockResolvedValueOnce({
+ codes: {
+ [cellId1]: formattedCode1,
+ [cellId2]: formattedCode2,
+ },
+ });
+
+ vi.mocked(getResolvedMarimoConfig).mockReturnValueOnce(mockConfig);
+
+ await formatEditorViews(views);
+
+ expect(sendFormat).toHaveBeenCalledWith({
+ codes: {
+ [cellId1]: "import numpy as np",
+ [cellId2]: "import pandas as pd",
+ },
+ lineLength: 88,
+ });
+
+ expect(views[cellId1].state.doc.toString()).toBe(formattedCode1);
+ expect(views[cellId2].state.doc.toString()).toBe(formattedCode2);
+ expect(updateCellCode).toHaveBeenCalledWith({
+ cellId: cellId1,
+ code: formattedCode1,
+ formattingChange: true,
+ });
+ expect(updateCellCode).toHaveBeenCalledWith({
+ cellId: cellId2,
+ code: formattedCode2,
+ formattingChange: true,
+ });
+ });
+
+ it("should not update editor if formatted code is same as original", async () => {
+ const cellId = "1" as CellId;
+ const originalCode = "import numpy as np";
+ const views = {
+ [cellId]: createEditor(originalCode, cellId),
+ };
+
+ vi.mocked(sendFormat).mockResolvedValueOnce({
+ codes: {
+ [cellId]: originalCode,
+ },
+ });
+
+ vi.mocked(getResolvedMarimoConfig).mockReturnValueOnce(mockConfig);
+
+ await formatEditorViews(views);
+
+ expect(views[cellId].state.doc.toString()).toBe(originalCode);
+ expect(updateCellCode).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("formatAll", () => {
+ it("should format all cells in notebook", async () => {
+ const cellId1 = "1" as CellId;
+ const cellId2 = "2" as CellId;
+ const views = {
+ [cellId1]: createEditor("import numpy as np", cellId1),
+ [cellId2]: createEditor("import pandas as pd", cellId2),
+ };
+
+ vi.mocked(getNotebook).mockReturnValueOnce({} as NotebookState);
+ vi.mocked(notebookCellEditorViews).mockReturnValueOnce(views);
+ vi.mocked(sendFormat).mockResolvedValueOnce({
+ codes: {
+ [cellId1]: "import numpy as np",
+ [cellId2]: "import pandas as pd",
+ },
+ });
+
+ vi.mocked(getResolvedMarimoConfig).mockReturnValueOnce(mockConfig);
+
+ await formatAll();
+
+ expect(sendFormat).toHaveBeenCalledWith({
+ codes: {
+ [cellId1]: "import numpy as np",
+ [cellId2]: "import pandas as pd",
+ },
+ lineLength: 88,
+ });
+
+ expect(updateCellCode).toHaveBeenCalledWith({
+ cellId: cellId1,
+ code: "import numpy as np",
+ formattingChange: true,
+ });
+ });
+ });
+
+ describe("formatSQL", () => {
+ it("should format SQL code", async () => {
+ const cellId = "1" as CellId;
+ const editor = createEditor("SELECT * FROM table WHERE id = 1", cellId);
+ switchLanguage(editor, "sql");
+
+ await formatSQL(editor);
+
+ // Check that the SQL was formatted
+ expect(editor.state.doc.toString()).toMatchInlineSnapshot(`
+ "SELECT
+ *
+ FROM
+ table
+ WHERE
+ id = 1"
+ `);
+ expect(updateCellCode).toHaveBeenCalledWith({
+ cellId: cellId,
+ code: editor.state.doc.toString(),
+ formattingChange: true,
+ });
+ });
+
+ it("should not format if language adapter is not SQL", async () => {
+ const cellId = "1" as CellId;
+ const editor = createEditor("SELECT * FROM table WHERE id = 1", cellId);
+ switchLanguage(editor, "python");
+
+ await formatSQL(editor);
+
+ // Check that the SQL was not formatted
+ expect(editor.state.doc.toString()).toBe(
+ "SELECT * FROM table WHERE id = 1",
+ );
+ expect(updateCellCode).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/frontend/src/core/codemirror/format.ts b/frontend/src/core/codemirror/format.ts
index 04dd1c4ea9..071c9d3a6d 100644
--- a/frontend/src/core/codemirror/format.ts
+++ b/frontend/src/core/codemirror/format.ts
@@ -13,6 +13,10 @@ import {
import { StateEffect } from "@codemirror/state";
import { getResolvedMarimoConfig } from "../config/config";
import { cellActionsState } from "./cells/state";
+import { languageAdapterState } from "./language/extension";
+import { Logger } from "@/utils/Logger";
+import { cellIdState } from "./config/extension";
+import { getIndentUnit } from "@codemirror/language";
export const formattingChangeEffect = StateEffect.define<boolean>();
@@ -62,3 +66,51 @@ export function formatAll() {
const views = notebookCellEditorViews(getNotebook());
return formatEditorViews(views);
}
+
+/**
+ * Format the SQL code in the editor view.
+ *
+ * This is currently only used by explicitly clicking the format button.
+ * We do not use it for auto-formatting onSave or globally because
+ * SQL formatting is much more opinionated than Python formatting, and we
+ * don't want to tie the two together (just yet).
+ */
+export async function formatSQL(editor: EditorView) {
+ // Lazy import sql-formatter
+ const { formatDialect, duckdb } = await import("sql-formatter");
+
+ // Get language adapter
+ const languageAdapter = editor.state.field(languageAdapterState);
+ const tabWidth = getIndentUnit(editor.state);
+ if (languageAdapter.type !== "sql") {
+ Logger.error("Language adapter is not SQL");
+ return;
+ }
+
+ const codeAsSQL = editor.state.doc.toString();
+ const formattedSQL = formatDialect(codeAsSQL, {
+ dialect: duckdb,
+ tabWidth: tabWidth,
+ useTabs: false,
+ });
+
+ // Update Python in the notebook state
+ const codeAsPython = languageAdapter.transformIn(formattedSQL)[0];
+ const actions = editor.state.facet(cellActionsState);
+ const cellId = editor.state.facet(cellIdState);
+ actions.updateCellCode({
+ cellId,
+ code: codeAsPython,
+ formattingChange: true,
+ });
+
+ // Update editor with formatted SQL
+ editor.dispatch({
+ changes: {
+ from: 0,
+ to: editor.state.doc.length,
+ insert: formattedSQL,
+ },
+ effects: [formattingChangeEffect.of(true)],
+ });
+}
diff --git a/frontend/src/core/codemirror/language/panel.tsx b/frontend/src/core/codemirror/language/panel.tsx
index 4d102d147a..59236995ba 100644
--- a/frontend/src/core/codemirror/language/panel.tsx
+++ b/frontend/src/core/codemirror/language/panel.tsx
@@ -10,7 +10,7 @@ import {
INTERNAL_SQL_ENGINES,
} from "@/core/datasets/data-source-connections";
import { useAtomValue } from "jotai";
-import { AlertCircle, CircleHelpIcon } from "lucide-react";
+import { AlertCircle, CircleHelpIcon, PaintRollerIcon } from "lucide-react";
import {
Select,
SelectContent,
@@ -25,6 +25,11 @@ import { DatabaseLogo } from "@/components/databases/icon";
import { transformDisplayName } from "@/components/databases/display";
import { useNonce } from "@/hooks/useNonce";
import type { DataSourceConnection } from "@/core/kernel/messages";
+import { formatSQL } from "../format";
+import { Button } from "@/components/ui/button";
+import { Tooltip, TooltipProvider } from "@/components/ui/tooltip";
+
+const Divider = () => <div className="h-4 border-r border-border" />;
export const LanguagePanelComponent: React.FC<{
view: EditorView;
@@ -83,27 +88,43 @@ export const LanguagePanelComponent: React.FC<{
languageAdapter={languageAdapter}
onChange={triggerUpdate}
/>
- <label className="flex items-center gap-2 ml-auto">
- <input
- type="checkbox"
- onChange={(e) => {
- languageAdapter.setShowOutput(!e.target.checked);
- triggerUpdate();
- }}
- checked={!languageAdapter.showOutput}
- />
- <span className="select-none">Hide output</span>
- </label>
+ <div className="flex items-center gap-2 ml-auto">
+ <Tooltip content="Format SQL">
+ <Button
+ variant="text"
+ size="icon"
+ onClick={async () => {
+ await formatSQL(view);
+ }}
+ >
+ <PaintRollerIcon className="h-3 w-3" />
+ </Button>
+ </Tooltip>
+ <Divider />
+ <label className="flex items-center gap-2">
+ <input
+ type="checkbox"
+ onChange={(e) => {
+ languageAdapter.setShowOutput(!e.target.checked);
+ triggerUpdate();
+ }}
+ checked={!languageAdapter.showOutput}
+ />
+ <span className="select-none">Hide output</span>
+ </label>
+ </div>
</div>
);
}
return (
- <div className="flex justify-between items-center gap-4 pl-2 pt-2">
- {actions}
- {showDivider && <div className="h-4 border-r border-border" />}
- {languageAdapter.type}
- </div>
+ <TooltipProvider>
+ <div className="flex justify-between items-center gap-4 pl-2 pt-2">
+ {actions}
+ {showDivider && <Divider />}
+ {languageAdapter.type}
+ </div>
+ </TooltipProvider>
);
};
@@ -190,6 +211,7 @@ const SQLEngineSelect: React.FC<SelectProps> = ({
className="flex items-center gap-1"
href={HELP_URL}
target="_blank"
+ rel="noreferrer"
>
<CircleHelpIcon className="h-3 w-3" />
<span>How to add a database connection</span>