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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: sql support (#1709)
Myles Scolnick2f4315ca892f
diff --git a/docs/guides/ai_completion.md b/docs/guides/ai_completion.mdindex 1d831c88b8..06e3e17dc3 100644--- a/docs/guides/ai_completion.md+++ b/docs/guides/ai_completion.md@@ -53,8 +53,8 @@ This feature is currently experimental and is not enabled by default. To enable[ai.open_ai]# Get your API key from https://platform.openai.com/account/api-keysapi_key = "sk-..."-# Choose a model, we recommend "gpt-3.5-turbo"-model = "gpt-3.5-turbo"+# Choose a model, we recommend "gpt-4-turbo"+model = "gpt-4-turbo"# Change the base_url if you are using a different OpenAI-compatible APIbase_url = "https://api.openai.com"```diff --git a/examples/ai/openai.py b/examples/ai/openai.pyindex 9abbb33745..3aafa2e695 100644--- a/examples/ai/openai.py+++ b/examples/ai/openai.py@@ -40,7 +40,7 @@ def __(content, item, mo, openai, openaikey):result = Noneif item.value:response = openai.ChatCompletion.create(- model="gpt-3.5-turbo",+ model="gpt-4-turbo",messages=[{"role": "system",@@ -62,7 +62,7 @@ def __(content, item, mo, openai, openaikey):result = Noneif item.value:response = openai.ChatCompletion.create(- model="gpt-3.5-turbo",+ model="gpt-4-turbo",messages=[{"role": "system",@@ -103,7 +103,7 @@ def __(mo, openai, superhero):if superhero.value:catchphraseResponse = openai.ChatCompletion.create(- model="gpt-3.5-turbo",+ model="gpt-4-turbo",messages=[{"role": "system", "content": "You are a creative assistant."},{diff --git a/frontend/package.json b/frontend/package.jsonindex 909b6673e6..47c878d1e7 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -17,6 +17,7 @@"@codemirror/commands": "^6.6.0","@codemirror/lang-markdown": "^6.2.5","@codemirror/lang-python": "^6.1.6",+ "@codemirror/lang-sql": "^6.7.0","@codemirror/language": "^6.10.2","@codemirror/language-data": "^6.5.1","@codemirror/lint": "^6.8.1",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex d5870a232f..d9496923ff 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -17,12 +17,15 @@ dependencies:'@codemirror/lang-python':specifier: ^6.1.6version: 6.1.6(@codemirror/[email protected])+ '@codemirror/lang-sql':+ specifier: ^6.7.0+ version: 6.7.0(@codemirror/[email protected])'@codemirror/language':specifier: ^6.10.2version: 6.10.2'@codemirror/language-data':specifier: ^6.5.1- version: 6.5.1(@codemirror/[email protected])(@lezer/[email protected])+ version: 6.5.1(@codemirror/[email protected])'@codemirror/lint':specifier: ^6.8.1version: 6.8.1@@ -2199,17 +2202,17 @@ packages:- '@codemirror/view'dev: false- resolution: {integrity: sha512-5Gq7fYtT/5HbNyIG7a8vYaqOYQU3JbgtBe3+derkrFUXRVcjkf8WVgz++PIbMFAQsOFMDdDR+uiNM8ZRRuXH+w==}+ /@codemirror/[email protected](@codemirror/[email protected]):+ resolution: {integrity: sha512-KMXp6rtyPYz6RaElvkh/77ClEAoQoHRPZo0zutRRialeFs/B/X8YaUJBCnAV2zqyeJPLZ4hgo48mG8TKoNXfZA==}dependencies:'@codemirror/autocomplete': 6.16.3(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])'@codemirror/language': 6.10.2'@codemirror/state': 6.4.1+ '@lezer/common': 1.2.1'@lezer/highlight': 1.2.0'@lezer/lr': 1.4.1transitivePeerDependencies:- '@codemirror/view'- - '@lezer/common'dev: false/@codemirror/[email protected]:@@ -2255,7 +2258,7 @@ packages:- '@codemirror/view'dev: false+ /@codemirror/[email protected](@codemirror/[email protected]):resolution: {integrity: sha512-0sWxeUSNlBr6OmkqybUTImADFUP0M3P0IiSde4nc24bz/6jIYzqYSgkOSLS+CBIoW1vU8Q9KUWXscBXeoMVC9w==}dependencies:'@codemirror/lang-angular': 0.1.2@@ -2273,7 +2276,7 @@ packages:'@codemirror/lang-python': 6.1.6(@codemirror/[email protected])'@codemirror/lang-rust': 6.0.1'@codemirror/lang-sass': 6.0.2(@codemirror/[email protected])- '@codemirror/lang-sql': 6.5.4(@codemirror/[email protected])(@lezer/[email protected])+ '@codemirror/lang-sql': 6.7.0(@codemirror/[email protected])'@codemirror/lang-vue': 0.1.2'@codemirror/lang-wast': 6.0.1'@codemirror/lang-xml': 6.0.2(@codemirror/[email protected])@@ -2282,7 +2285,6 @@ packages:'@codemirror/legacy-modes': 6.4.0transitivePeerDependencies:- '@codemirror/view'- - '@lezer/common'dev: false/@codemirror/[email protected]:@@ -9503,11 +9505,11 @@ packages:'@codemirror/lang-python': 6.1.6(@codemirror/[email protected])'@codemirror/lang-rust': 6.0.1'@codemirror/lang-sass': 6.0.2(@codemirror/[email protected])- '@codemirror/lang-sql': 6.5.4(@codemirror/[email protected])(@lezer/[email protected])+ '@codemirror/lang-sql': 6.7.0(@codemirror/[email protected])'@codemirror/lang-vue': 0.1.2'@codemirror/lang-wast': 6.0.1'@codemirror/lang-xml': 6.0.2(@codemirror/[email protected])- '@codemirror/language-data': 6.5.1(@codemirror/[email protected])(@lezer/[email protected])+ '@codemirror/language-data': 6.5.1(@codemirror/[email protected])'@codemirror/legacy-modes': 6.4.0'@nextjournal/lang-clojure': 1.0.0'@replit/codemirror-lang-csharp': 6.2.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsxindex 26bc074b97..19542f3aec 100644--- a/frontend/src/components/app-config/user-config-form.tsx+++ b/frontend/src/components/app-config/user-config-form.tsx@@ -558,7 +558,7 @@ export const UserConfigForm: React.FC = () => {<Inputdata-testid="ai-model-input"className="m-0 inline-flex"- placeholder="gpt-3.5-turbo"+ placeholder="gpt-4-turbo"{...field}/></FormControl>diff --git a/frontend/src/components/editor/actions/useCellActionButton.tsx b/frontend/src/components/editor/actions/useCellActionButton.tsxindex eaf84b42b7..86ad8b8e61 100644--- a/frontend/src/components/editor/actions/useCellActionButton.tsx+++ b/frontend/src/components/editor/actions/useCellActionButton.tsx@@ -1,12 +1,12 @@/* Copyright 2024 Marimo. All rights reserved. */import { downloadCellOutput } from "@/components/export/export-output-button";import { Switch } from "@/components/ui/switch";+import { formatEditorViews } from "@/core/codemirror/format";import {- canToggleMarkdown,- formatEditorViews,- getEditorViewMode,- toggleMarkdown,-} from "@/core/codemirror/format";+ canToggleToLanguage,+ getCurrentLanguageAdapter,+ toggleToLanguage,+} from "@/core/codemirror/language/commands";import {hasOnlyOneCellAtom,useCellActions,@@ -28,6 +28,7 @@ import {EyeIcon,EyeOffIcon,SparklesIcon,+ DatabaseIcon,} from "lucide-react";import type { ActionButton } from "./types";import { MultiIcon } from "@/components/icons/multi-icon";@@ -201,26 +202,45 @@ export function useCellActionButtons({ cell }: Props) {},},{- icon:- getEditorViewMode(editorView) === "python" ? (- <MarkdownIcon />- ) : (- <PythonIcon />- ),- label:- getEditorViewMode(editorView) === "python"- ? "View as Markdown"- : "View as Python",+ icon: <MarkdownIcon />,+ label: "View as Markdown",hotkey: "cell.viewAsMarkdown",- hidden:- !canToggleMarkdown(editorView) &&- getEditorViewMode(editorView) !== "markdown",+ hidden: !canToggleToLanguage(editorView, "markdown"),+ handle: () => {+ if (!editorView) {+ return;+ }+ maybeAddMarimoImport(autoInstantiate, createCell);++ toggleToLanguage(editorView, "markdown");+ },+ },+ {+ icon: <DatabaseIcon size={13} strokeWidth={1.5} />,+ label: "View as SQL",+ hidden: !canToggleToLanguage(editorView, "sql"),+ handle: () => {+ if (!editorView) {+ return;+ }+ toggleToLanguage(editorView, "sql");+ },+ },+ {+ icon: <PythonIcon />,+ label: "View as Python",+ // If we're in markdown mode, we should use the markdown hotkey+ hotkey:+ getCurrentLanguageAdapter(editorView) === "markdown"+ ? "cell.viewAsMarkdown"+ : undefined,+ hidden: !canToggleToLanguage(editorView, "python"),handle: () => {if (!editorView) {return;}maybeAddMarimoImport(autoInstantiate, createCell);- toggleMarkdown(cellId, editorView, updateCellCode);+ toggleToLanguage(editorView, "python");},},{diff --git a/frontend/src/components/editor/cell/code/ai-completion-editor.tsx b/frontend/src/components/editor/cell/code/ai-completion-editor.tsxindex 0e0487b5b3..2edf41d904 100644--- a/frontend/src/components/editor/cell/code/ai-completion-editor.tsx+++ b/frontend/src/components/editor/cell/code/ai-completion-editor.tsx@@ -20,12 +20,14 @@ import { Checkbox } from "@/components/ui/checkbox";import { getCodes } from "@/core/codemirror/copilot/getCodes";import { useTheme } from "@/theme/useTheme";import { asURL } from "@/utils/url";+import { LanguageAdapterType } from "@/core/codemirror/language/types";const Original = CodeMirrorMerge.Original;const Modified = CodeMirrorMerge.Modified;interface Props {currentCode: string;+ currentLanguageAdapter: LanguageAdapterType | undefined;onChange: (code: string) => void;declineChange: () => void;acceptChange: (rightHandCode: string) => void;@@ -40,6 +42,7 @@ const baseExtensions = [customPythonLanguageSupport(), EditorView.lineWrapping];export const AiCompletionEditor: React.FC<Props> = ({onChange,+ currentLanguageAdapter,currentCode,declineChange,acceptChange,@@ -65,6 +68,7 @@ export const AiCompletionEditor: React.FC<Props> = ({body: {includeOtherCode: includeOtherCells ? getCodes(currentCode) : "",code: currentCode,+ language: currentLanguageAdapter,},onError: (error) => {toast({diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex 8132f690a1..5d07944479 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -18,13 +18,12 @@ import type { CellRuntimeState, CellData } from "@/core/cells/types";import type { UserConfig } from "@/core/config/config-schema";import type { Theme } from "@/theme/useTheme";import {- LanguageAdapters,getInitialLanguageAdapter,languageAdapterState,reconfigureLanguageEffect,switchLanguage,} from "@/core/codemirror/language/extension";-import { LanguageToggle } from "./language-toggle";+import { LanguageToggles } from "./language-toggle";import { cn } from "@/utils/cn";import { saveCellConfig } from "@/core/network/requests";import { HideCodeButton } from "../../code/readonly-python-code";@@ -33,7 +32,7 @@ import { useAtom, useAtomValue, useSetAtom } from "jotai";import { aiCompletionCellAtom } from "@/core/ai/state";import { mergeRefs } from "@/utils/mergeRefs";import { lastFocusedCellIdAtom } from "@/core/cells/focus";-import type { LanguageAdapter } from "@/core/codemirror/language/types";+import type { LanguageAdapterType } from "@/core/codemirror/language/types";import { autoInstantiateAtom } from "@/core/config/config";import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";@@ -86,12 +85,8 @@ const CellEditorInternal = ({editorViewRef,hidden,}: CellEditorProps) => {- const [canUseMarkdown, setCanUseMarkdown] = useState(() => {- return LanguageAdapters.markdown().isSupported(code);- });const [aiCompletionCell, setAiCompletionCell] = useAtom(aiCompletionCellAtom);- const [languageAdapter, setLanguageAdapter] =- useState<LanguageAdapter["type"]>();+ const [languageAdapter, setLanguageAdapter] = useState<LanguageAdapterType>();const setLastFocusedCellId = useSetAtom(lastFocusedCellIdAtom);// DOM node where the editorView will be mountedconst editorViewParentRef = useRef<HTMLDivElement>(null);@@ -196,13 +191,7 @@ const CellEditorInternal = ({return {update(view) {- const code = view.state.doc.toString();const languageAdapter = view.state.field(languageAdapterState);- // If its not markdown, set if we can use markdown- if (languageAdapter.type !== "markdown") {- setCanUseMarkdown(LanguageAdapters.markdown().isSupported(code));- }-// Set the language adaptersetLanguageAdapter(languageAdapter.type);},@@ -342,7 +331,8 @@ const CellEditorInternal = ({return (<AiCompletionEditorenabled={aiCompletionCell === cellId}- currentCode={code}+ currentCode={editorViewRef.current?.state.doc.toString() ?? code}+ currentLanguageAdapter={languageAdapter}declineChange={() => {setAiCompletionCell(null);editorViewRef.current?.focus();@@ -372,13 +362,13 @@ const CellEditorInternal = ({className="relative w-full"onFocus={() => setLastFocusedCellId(cellId)}>- {canUseMarkdown && !hidden && (- <div className="absolute top-1 right-1">- <LanguageToggle+ {!hidden && (+ <div className="absolute top-1 right-5">+ <LanguageToggles+ code={code}editorView={editorViewRef.current}- languageAdapter={languageAdapter}- canUseMarkdown={canUseMarkdown}- onAfterToggleMarkdown={afterToggleMarkdown}+ currentLanguageAdapter={languageAdapter}+ onAfterToggle={afterToggleMarkdown}/></div>)}diff --git a/frontend/src/components/editor/cell/code/language-toggle.tsx b/frontend/src/components/editor/cell/code/language-toggle.tsxindex 25bf059342..c35d4779df 100644--- a/frontend/src/components/editor/cell/code/language-toggle.tsx+++ b/frontend/src/components/editor/cell/code/language-toggle.tsx@@ -5,52 +5,136 @@ import type React from "react";import { MarkdownIcon, PythonIcon } from "./icons";import { Button } from "@/components/ui/button";import { Tooltip } from "@/components/ui/tooltip";-import { startCase } from "lodash-es";import type { LanguageAdapter } from "@/core/codemirror/language/types";+import { DatabaseIcon } from "lucide-react";+import { useMemo } from "react";+import { MarkdownLanguageAdapter } from "@/core/codemirror/language/markdown";+import { SQLLanguageAdapter } from "@/core/codemirror/language/sql";+import { Functions } from "@/utils/functions";++interface LanguageTogglesProps {+ editorView: EditorView | null;+ code: string;+ currentLanguageAdapter: LanguageAdapter["type"] | undefined;+ onAfterToggle: () => void;+}++export const LanguageToggles: React.FC<LanguageTogglesProps> = ({+ editorView,+ code,+ currentLanguageAdapter,+ onAfterToggle,+}) => {+ const canUseMarkdown = useMemo(+ () => new MarkdownLanguageAdapter().isSupported(code),+ [code],+ );+ const canUseSQL = useMemo(+ () => new SQLLanguageAdapter().isSupported(code),+ [code],+ );++ return (+ <div className="absolute right-2 top-0 z-20 flex hover-action">+ <LanguageToggle+ editorView={editorView}+ currentLanguageAdapter={currentLanguageAdapter}+ // Prefer showing markdown over SQL when both are supported+ canSwitchToLanguage={+ canUseSQL && currentLanguageAdapter === "python" && !canUseMarkdown+ }+ icon={+ <DatabaseIcon+ color={"var(--sky-11)"}+ strokeWidth={2.5}+ className="w-4 h-4"+ />+ }+ toType="sql"+ displayName="SQL"+ onAfterToggle={onAfterToggle}+ />+ <LanguageToggle+ editorView={editorView}+ currentLanguageAdapter={currentLanguageAdapter}+ canSwitchToLanguage={+ canUseMarkdown && currentLanguageAdapter === "python"+ }+ icon={+ <MarkdownIcon+ fill={"var(--sky-11)"}+ color="black"+ className="w-4 h-4"+ />+ }+ toType="markdown"+ displayName="Markdown"+ onAfterToggle={onAfterToggle}+ />+ <LanguageToggle+ editorView={editorView}+ currentLanguageAdapter={currentLanguageAdapter}+ canSwitchToLanguage={true}+ icon={+ <PythonIcon+ fill={"var(--sky-11)"}+ color="black"+ className="w-4 h-4"+ />+ }+ toType="python"+ displayName="Python"+ onAfterToggle={Functions.NOOP}+ />+ </div>+ );+};interface Props {+ className?: string;editorView: EditorView | null;- canUseMarkdown: boolean;- languageAdapter: LanguageAdapter["type"] | undefined;- onAfterToggleMarkdown: () => void;+ canSwitchToLanguage: boolean;+ currentLanguageAdapter: LanguageAdapter["type"] | undefined;+ toType: LanguageAdapter["type"];+ displayName: string;+ icon: React.ReactNode;+ onAfterToggle: () => void;}export const LanguageToggle: React.FC<Props> = ({editorView,- languageAdapter,- canUseMarkdown,- onAfterToggleMarkdown,+ currentLanguageAdapter,+ canSwitchToLanguage,+ icon,+ toType,+ displayName,+ onAfterToggle,}) => {- if (!canUseMarkdown && languageAdapter !== "markdown") {+ if (!canSwitchToLanguage) {return null;}- const otherLanguage = languageAdapter === "markdown" ? "python" : "markdown";- const Icon = languageAdapter === "markdown" ? PythonIcon : MarkdownIcon;+ if (currentLanguageAdapter === toType) {+ return null;+ }return (- <div className="absolute top-0 right-5 z-20 hover-action">- <Tooltip content={`View as ${startCase(otherLanguage)}`}>- <Button- data-testid="language-toggle-button"- variant="text"- size="xs"- className="opacity-80"- >- <Icon- className="cursor-pointer"- fill={"var(--sky-11)"}- fontSize={20}- onClick={() => {- if (!editorView) {- return;- }- switchLanguage(editorView, otherLanguage);- onAfterToggleMarkdown();- }}- />- </Button>- </Tooltip>- </div>+ <Tooltip content={`View as ${displayName}`}>+ <Button+ data-testid="language-toggle-button"+ variant="text"+ size="xs"+ className="opacity-80 px-1"+ onClick={() => {+ if (!editorView) {+ return;+ }+ switchLanguage(editorView, toType);+ onAfterToggle();+ }}+ >+ {icon}+ </Button>+ </Tooltip>);};diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsxindex 0b8baa1542..1c547336df 100644--- a/frontend/src/components/editor/renderers/CellArray.tsx+++ b/frontend/src/components/editor/renderers/CellArray.tsx@@ -24,13 +24,23 @@ import { PackageAlert } from "@/components/editor/package-alert";import { useDeleteCellCallback } from "../cell/useDeleteCell";import { cn } from "@/utils/cn";import { Button } from "@/components/ui/button";-import { SparklesIcon, SquareCodeIcon, SquareMIcon } from "lucide-react";+import {+ DatabaseIcon,+ SparklesIcon,+ SquareCodeIcon,+ SquareMIcon,+} from "lucide-react";import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";import { aiEnabledAtom, autoInstantiateAtom } from "@/core/config/config";import { useAtomValue } from "jotai";import { useBoolean } from "@/hooks/useBoolean";import { AddCellWithAI } from "../ai/add-cell-with-ai";import { Milliseconds } from "@/utils/time";+import { SQLLanguageAdapter } from "@/core/codemirror/language/sql";+import { MarkdownLanguageAdapter } from "@/core/codemirror/language/markdown";+import { capabilitiesAtom } from "@/core/config/capabilities";+import { Tooltip } from "@/components/ui/tooltip";+import { Kbd } from "@/components/ui/kbd";interface CellArrayProps {notebook: NotebookState;@@ -157,6 +167,7 @@ const AddCellButtons: React.FC = () => {const autoInstantiate = useAtomValue(autoInstantiateAtom);const [isAiButtonOpen, isAiButtonOpenActions] = useBoolean(false);const aiEnabled = useAtomValue(aiEnabledAtom);+ const sqlCapabilities = useAtomValue(capabilitiesAtom).sql;const buttonClass = cn("mb-0 rounded-none px-4 sm:px-8 md:px-10 lg:px-16 tracking-wide",@@ -189,24 +200,60 @@ const AddCellButtons: React.FC = () => {createNewCell({cellId: "__end__",before: false,- code: 'mo.md(rf"""\n""")',+ code: new MarkdownLanguageAdapter().defaultCode,});}}><SquareMIcon className="mr-2 size-4" />Markdown</Button>- {aiEnabled && (+ <Tooltip+ content={+ sqlCapabilities ? null : (+ <span>+ Requires duckdb:{" "}+ <Kbd className="inline">pip install duckdb</Kbd>+ </span>+ )+ }+ delayDuration={100}+ asChild={false}+ >+ <Button+ className={buttonClass}+ variant="text"+ size="sm"+ disabled={!sqlCapabilities}+ onClick={() => {+ maybeAddMarimoImport(autoInstantiate, createNewCell);++ createNewCell({+ cellId: "__end__",+ before: false,+ code: new SQLLanguageAdapter().defaultCode,+ });+ }}+ >+ <DatabaseIcon className="mr-2 size-4" />+ SQL+ </Button>+ </Tooltip>+ <Tooltip+ content={aiEnabled ? null : <span>Enable via settings</span>}+ delayDuration={100}+ asChild={false}+ ><ButtonclassName={buttonClass}variant="text"size="sm"+ disabled={!aiEnabled}onClick={isAiButtonOpenActions.toggle}><SparklesIcon className="mr-2 size-4" />Generate with AI</Button>- )}+ </Tooltip></>);};diff --git a/frontend/src/components/ui/tooltip.tsx b/frontend/src/components/ui/tooltip.tsxindex b59cd17764..0c449deb66 100644--- a/frontend/src/components/ui/tooltip.tsx+++ b/frontend/src/components/ui/tooltip.tsx@@ -46,20 +46,26 @@ const Tooltip: React.FC<tabIndex,side,...rootProps-}) => (- <TooltipRoot disableHoverableContent={true} {...rootProps}>- <TooltipTrigger asChild={asChild} tabIndex={tabIndex}>- {children}- </TooltipTrigger>- {usePortal ? (- <TooltipPrimitive.TooltipPortal>+}) => {+ if (content == null || content === "") {+ return children;+ }++ return (+ <TooltipRoot disableHoverableContent={true} {...rootProps}>+ <TooltipTrigger asChild={asChild} tabIndex={tabIndex}>+ {children}+ </TooltipTrigger>+ {usePortal ? (+ <TooltipPrimitive.TooltipPortal>+ <TooltipContent side={side}>{content}</TooltipContent>+ </TooltipPrimitive.TooltipPortal>+ ) : (<TooltipContent side={side}>{content}</TooltipContent>- </TooltipPrimitive.TooltipPortal>- ) : (- <TooltipContent side={side}>{content}</TooltipContent>- )}- </TooltipRoot>-);+ )}+ </TooltipRoot>+ );+};export {Tooltip,diff --git a/frontend/src/core/codemirror/copilot/extension.ts b/frontend/src/core/codemirror/copilot/extension.tsindex e9465d1cea..474fc33752 100644--- a/frontend/src/core/codemirror/copilot/extension.ts+++ b/frontend/src/core/codemirror/copilot/extension.ts@@ -87,6 +87,7 @@ export const copilotBundle = (config: CompletionConfig): Extension => {position: position,},});+return response.completions.map((c) => c.displayText)[0] ?? "";},}),diff --git a/frontend/src/core/codemirror/extensions.ts b/frontend/src/core/codemirror/extensions.tsindex bb8de0d251..260785090a 100644--- a/frontend/src/core/codemirror/extensions.ts+++ b/frontend/src/core/codemirror/extensions.ts@@ -1,7 +1,8 @@/* Copyright 2024 Marimo. All rights reserved. */import { EditorView, keymap } from "@codemirror/view";import type { CellId } from "../cells/ids";-import { formatEditorViews, toggleMarkdown } from "./format";+import { formatEditorViews } from "./format";+import { toggleToLanguage } from "./language/commands";import { smartScrollIntoView } from "../../utils/scroll";import { HotkeyProvider } from "@/core/hotkeys/hotkeys";import { invariant } from "@/utils/invariant";@@ -29,7 +30,7 @@ export function formatKeymapExtension(key: hotkeys.getHotkey("cell.viewAsMarkdown").key,preventDefault: true,run: (ev) => {- const response = toggleMarkdown(cellId, ev, updateCellCode);+ const response = toggleToLanguage(ev, "markdown");if (response === "markdown") {afterToggleMarkdown();}diff --git a/frontend/src/core/codemirror/format.ts b/frontend/src/core/codemirror/format.tsindex 099a1180e8..09f3f2d950 100644--- a/frontend/src/core/codemirror/format.ts+++ b/frontend/src/core/codemirror/format.ts@@ -12,12 +12,6 @@ import {} from "./language/utils";import { StateEffect } from "@codemirror/state";import { getUserConfig } from "../config/config";-import {- LanguageAdapters,- languageAdapterState,- switchLanguage,-} from "./language/extension";-import type { LanguageAdapter } from "./language/types";export const formattingChangeEffect = StateEffect.define<boolean>();@@ -65,52 +59,3 @@ export function formatAll(updateCellCode: CellActions["updateCellCode"]) {const views = notebookCellEditorViews(getNotebook());return formatEditorViews(views, updateCellCode);}--export function getEditorViewMode(- editorView: EditorView | null,-): LanguageAdapter["type"] {- if (!editorView) {- return "python";- }- return editorView.state.field(languageAdapterState).type;-}--export function canToggleMarkdown(editorView: EditorView | null) {- if (!editorView || getEditorViewMode(editorView) === "markdown") {- return false;- }- return (- LanguageAdapters.markdown().isSupported(- getEditorCodeAsPython(editorView),- ) || getEditorCodeAsPython(editorView).trim() === ""- );-}--export function toggleMarkdown(- cellId: CellId,- editorView: EditorView,- updateCellCode: CellActions["updateCellCode"],-): "python" | "markdown" | false {- // If already in markdown mode, switch to python- if (getEditorViewMode(editorView) === "markdown") {- switchLanguage(editorView, "python");- return "python";- }-- if (!canToggleMarkdown(editorView)) {- return false;- }-- if (getEditorCodeAsPython(editorView).trim() === "") {- const blankMd = 'mo.md(rf"")';- updateCellCode({- cellId,- code: blankMd,- formattingChange: true,- });- updateEditorCodeFromPython(editorView, blankMd);- }-- switchLanguage(editorView, "markdown");- return "markdown";-}diff --git a/frontend/src/core/codemirror/language/LanguageAdapters.ts b/frontend/src/core/codemirror/language/LanguageAdapters.tsnew file mode 100644index 0000000000..d79c920d4f--- /dev/null+++ b/frontend/src/core/codemirror/language/LanguageAdapters.ts@@ -0,0 +1,18 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { LanguageAdapter, LanguageAdapterType } from "./types";+import { PythonLanguageAdapter } from "./python";+import { MarkdownLanguageAdapter } from "./markdown";+import { SQLLanguageAdapter } from "./sql";++export const LanguageAdapters: Record<+ LanguageAdapterType,+ () => LanguageAdapter+> = {+ python: () => new PythonLanguageAdapter(),+ markdown: () => new MarkdownLanguageAdapter(),+ sql: () => new SQLLanguageAdapter(),+};++export function getLanguageAdapters() {+ return Object.values(LanguageAdapters).map((la) => la());+}diff --git a/frontend/src/core/codemirror/language/__tests__/extension.test.ts b/frontend/src/core/codemirror/language/__tests__/extension.test.tsnew file mode 100644index 0000000000..8ccc26747f--- /dev/null+++ b/frontend/src/core/codemirror/language/__tests__/extension.test.ts@@ -0,0 +1,57 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { beforeAll, describe, expect, it } from "vitest";+import {+ adaptiveLanguageConfiguration,+ getInitialLanguageAdapter,+} from "../extension";+import { EditorState } from "@codemirror/state";+import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";+import { MovementCallbacks } from "../../cells/extensions";+import { store } from "@/core/state/jotai";+import { capabilitiesAtom } from "@/core/config/capabilities";++function createState(content: string) {+ const state = EditorState.create({+ doc: content,+ extensions: [+ adaptiveLanguageConfiguration({+ completionConfig: {+ copilot: false,+ activate_on_typing: true,+ },+ hotkeys: new OverridingHotkeyProvider({}),+ enableAI: true,+ showPlaceholder: true,+ cellMovementCallbacks: {} as MovementCallbacks,+ }),+ ],+ });++ return state;+}++describe("getInitialLanguageAdapter", () => {+ beforeAll(() => {+ store.set(capabilitiesAtom, {+ sql: true,+ });+ });++ it("should return python", () => {+ let state = createState("def f():\n return 1");+ expect(getInitialLanguageAdapter(state).type).toBe("python");++ state = createState("");+ expect(getInitialLanguageAdapter(state).type).toBe("python");+ });++ it("should return markdown", () => {+ const state = createState("mo.md('hello')");+ expect(getInitialLanguageAdapter(state).type).toBe("markdown");+ });++ it("should return sql", () => {+ const state = createState("df = mo.sql('hello')");+ expect(getInitialLanguageAdapter(state).type).toBe("sql");+ });+});diff --git a/frontend/src/core/codemirror/language/__tests__/markdown.test.ts b/frontend/src/core/codemirror/language/__tests__/markdown.test.tsindex 0831f39e12..c87fd66f61 100644--- a/frontend/src/core/codemirror/language/__tests__/markdown.test.ts+++ b/frontend/src/core/codemirror/language/__tests__/markdown.test.ts@@ -6,6 +6,19 @@ const adapter = new MarkdownLanguageAdapter();describe("MarkdownLanguageAdapter", () => {describe("transformIn", () => {+ it("empty", () => {+ const [innerCode, offset] = adapter.transformIn("");+ expect(innerCode).toBe("");+ expect(offset).toBe(0);+ const out = adapter.transformOut(innerCode);+ expect(out).toMatchInlineSnapshot(`+ [+ "mo.md(r"")",+ 8,+ ]+ `);+ });+it("should extract inner Markdown from triple double-quoted strings", () => {const pythonCode = 'mo.md("""# Markdown Title\n\nSome content here.""")';const [innerCode, offset] = adapter.transformIn(pythonCode);@@ -43,34 +56,34 @@ describe("MarkdownLanguageAdapter", () => {it("should unescape code blocks", () => {// f"""- const pythonCode = 'mo.md(f"""This is some \\"""content\\"""!""")';+ const pythonCode = String.raw`mo.md(f"""This is some \"""content\"""!""")`;const [innerCode, offset] = adapter.transformIn(pythonCode);expect(innerCode).toBe(`This is some """content"""!`);expect(offset).toBe(10);// """- const pythonCode2 = 'mo.md("""This is some \\"""content\\"""!""")';+ const pythonCode2 = String.raw`mo.md("""This is some \"""content\"""!""")`;const [innerCode2, offset2] = adapter.transformIn(pythonCode2);expect(innerCode2).toBe(`This is some """content"""!`);expect(offset2).toBe(9);// "- const pythonCode3 = 'mo.md("This is some \\"content\\"!")';+ const pythonCode3 = String.raw`mo.md("This is some \"content\"!")`;const [innerCode3, offset3] = adapter.transformIn(pythonCode3);expect(innerCode3).toBe(`This is some "content"!`);expect(offset3).toBe(7);// '- const pythonCode4 = "mo.md('This is some \\'content\\'!')";+ const pythonCode4 = String.raw`mo.md('This is some \'content\'!')`;const [innerCode4, offset4] = adapter.transformIn(pythonCode4);expect(innerCode4).toBe(`This is some 'content'!`);expect(offset4).toBe(7);});it("should handle strings with escaped quotes", () => {- const pythonCode = 'mo.md("""Markdown with an escaped \\"quote\\"""")';+ const pythonCode = String.raw`mo.md("""Markdown with an escaped \"quote\"""")`;const [innerCode, offset] = adapter.transformIn(pythonCode);- expect(innerCode).toBe('Markdown with an escaped \\"quote\\"');+ expect(innerCode).toBe(String.raw`Markdown with an escaped \"quote\"`);expect(offset).toBe('mo.md("""'.length);});@@ -140,7 +153,9 @@ describe("MarkdownLanguageAdapter", () => {it("should preserve escaped characters", () => {const pythonCode = `mo.md(r"$\\nu = \\mathllap{}\\cdot\\mathllap{\\alpha}$")`;const [innerCode, offset] = adapter.transformIn(pythonCode);- expect(innerCode).toBe("$\\nu = \\mathllap{}\\cdot\\mathllap{\\alpha}$");+ expect(innerCode).toBe(+ String.raw`$\nu = \mathllap{}\cdot\mathllap{\alpha}$`,+ );expect(offset).toBe(8);});});@@ -204,7 +219,7 @@ describe("MarkdownLanguageAdapter", () => {});it("should preserve r strings", () => {- const code = "$\\nu = \\mathllap{}\\cdot\\mathllap{\\alpha}$";+ const code = String.raw`$\nu = \mathllap{}\cdot\mathllap{\alpha}$`;adapter.lastQuotePrefix = "r";const [wrappedCode, offset] = adapter.transformOut(code);const pythonCode = `mo.md(r"$\\nu = \\mathllap{}\\cdot\\mathllap{\\alpha}$")`;diff --git a/frontend/src/core/codemirror/language/__tests__/sql.test.ts b/frontend/src/core/codemirror/language/__tests__/sql.test.tsnew file mode 100644index 0000000000..8387d5be23--- /dev/null+++ b/frontend/src/core/codemirror/language/__tests__/sql.test.ts@@ -0,0 +1,137 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { expect, describe, it, beforeAll } from "vitest";+import { SQLLanguageAdapter } from "../sql";+import { store } from "@/core/state/jotai";+import { capabilitiesAtom } from "@/core/config/capabilities";++const adapter = new SQLLanguageAdapter();++describe("SQLLanguageAdapter", () => {+ beforeAll(() => {+ store.set(capabilitiesAtom, {+ sql: true,+ });+ });++ describe("transformIn", () => {+ it("empty", () => {+ const [innerCode, offset] = adapter.transformIn("");+ expect(innerCode).toBe("");+ expect(offset).toBe(0);+ const out = adapter.transformOut(innerCode);+ expect(out).toMatchInlineSnapshot(`+ [+ "_df = mo.sql(+ f"""++ """+ )",+ 24,+ ]+ `);+ });++ it("should extract inner SQL from triple double-quoted strings", () => {+ const pythonCode = '_df = mo.sql("""select * from {df}""")';+ const [innerCode, offset] = adapter.transformIn(pythonCode);+ expect(innerCode).toBe("select * from {df}");+ expect(adapter.dataframeName).toBe("_df");+ expect(offset).toBe(16);+ });++ it("should handle single double-quoted strings", () => {+ const pythonCode = 'next_df = mo.sql("select * from {df}")';+ const [innerCode, offset] = adapter.transformIn(pythonCode);+ expect(innerCode).toBe("select * from {df}");+ expect(adapter.dataframeName).toBe("next_df");+ expect(offset).toBe(18);+ });++ it("should handle triple single-quoted strings", () => {+ const pythonCode = "next_df = mo.sql('''select * \nfrom {df}''')";+ const [innerCode, offset] = adapter.transformIn(pythonCode);+ expect(innerCode).toBe("select * \nfrom {df}");+ expect(offset).toBe(20);+ });++ it("should throw if no sql is detected", () => {+ const pythonCode = 'next_df = print("Hello, World!")';+ expect(() =>+ adapter.transformIn(pythonCode),+ ).toThrowErrorMatchingInlineSnapshot(`[Error: Not supported]`);+ });++ it("should handle an empty string", () => {+ const pythonCode = 'next_df = mo.sql("")';+ const [innerCode, offset] = adapter.transformIn(pythonCode);+ expect(innerCode).toBe("");+ expect(offset).toBe(0);+ });++ it("simple sql", () => {+ const pythonCode = 'next_df = mo.sql("select * from {df}")';+ const [innerCode, offset] = adapter.transformIn(pythonCode);+ expect(innerCode).toBe("select * from {df}");+ expect(offset).toBe(18);+ });++ it("should trim strings with leading and trailing whitespace", () => {+ const pythonCode = 'next_df = mo.sql(""" \nselect * from {df}\n """)';+ const [innerCode, offset] = adapter.transformIn(pythonCode);+ expect(innerCode).toBe("select * from {df}");+ expect(offset).toBe(20);+ });++ it("should handle space around the f-strings", () => {+ const pythonCode = 'next_df = mo.sql(\n\t"""\nselect * from {df}\n"""\n)';+ const [innerCode, offset] = adapter.transformIn(pythonCode);+ expect(innerCode).toBe("select * from {df}");+ expect(offset).toBe(22);+ });+ });++ describe("transformOut", () => {+ it("should wrap SQL code with triple double-quoted string format", () => {+ const code = "select * from {df}";+ adapter.lastQuotePrefix = "";+ adapter.dataframeName = "my_df";+ const [wrappedCode, offset] = adapter.transformOut(code);+ expect(wrappedCode).toMatchInlineSnapshot(`+ "my_df = mo.sql(+ f"""+ select * from {df}+ """+ )"+ `);+ expect(offset).toBe(26);+ });+ });++ describe("isSupported", () => {+ it("should return true for supported sql string formats", () => {+ expect(+ adapter.isSupported('df2 = mo.sql("""select * from {df}""")'),+ ).toBe(true);+ expect(adapter.isSupported("my_df = mo.sql('')")).toBe(true);+ expect(adapter.isSupported('df = mo.sql("")')).toBe(true);+ expect(adapter.isSupported(new SQLLanguageAdapter().defaultCode)).toBe(+ true,+ );+ });++ it("should return false for unsupported string formats", () => {+ expect(adapter.isSupported('print("Hello, World!")')).toBe(false);+ expect(adapter.isSupported("mo.sql()")).toBe(false);+ expect(adapter.isSupported("mo.sql('')")).toBe(false);+ expect(adapter.isSupported('mo.sql("")')).toBe(false);+ expect(adapter.isSupported("_df = mo.sql()")).toBe(false);+ expect(adapter.isSupported('df := mo.sql("")')).toBe(false);+ });++ it("should return false sequences that look like sql but are not", () => {+ const once = 'df = mo.sql("""select * from {df}""")';+ const pythonCode = [once, once].join("\n");+ expect(adapter.isSupported(pythonCode)).toBe(false);+ });+ });+});diff --git a/frontend/src/core/codemirror/language/__tests__/utils.test.ts b/frontend/src/core/codemirror/language/__tests__/utils.test.tsindex 0e057f2a26..e0cc947c51 100644--- a/frontend/src/core/codemirror/language/__tests__/utils.test.ts+++ b/frontend/src/core/codemirror/language/__tests__/utils.test.ts@@ -43,6 +43,12 @@ describe("getEditorCodeAsPython", () => {const result = getEditorCodeAsPython(mockEditor, 0, 5);expect(result).toEqual("print");});++ it("should return a slice of the editor text when one position is specified", () => {+ const mockEditor = createEditor("print('Hello, World!')");+ const result = getEditorCodeAsPython(mockEditor, 5);+ expect(result).toEqual("('Hello, World!')");+ });});describe("updateEditorCodeFromPython", () => {diff --git a/frontend/src/core/codemirror/language/commands.ts b/frontend/src/core/codemirror/language/commands.tsnew file mode 100644index 0000000000..ce563c6973--- /dev/null+++ b/frontend/src/core/codemirror/language/commands.ts@@ -0,0 +1,49 @@+/* Copyright 2024 Marimo. All rights reserved. */++import type { EditorView } from "@codemirror/view";+import { getEditorCodeAsPython } from "./utils";+import { languageAdapterState, switchLanguage } from "./extension";+import { LanguageAdapters } from "./LanguageAdapters";+import type { LanguageAdapterType } from "./types";++/**+ * Get the current mode of the editor view.+ */+export function getCurrentLanguageAdapter(+ editorView: EditorView | null,+): LanguageAdapterType {+ if (!editorView) {+ return "python";+ }+ return editorView.state.field(languageAdapterState).type;+}++/**+ *+ */+export function canToggleToLanguage(+ editorView: EditorView | null,+ language: LanguageAdapterType,+): boolean {+ if (!editorView || getCurrentLanguageAdapter(editorView) === language) {+ return false;+ }++ return LanguageAdapters[language]().isSupported(+ getEditorCodeAsPython(editorView),+ );+}++export function toggleToLanguage(+ editorView: EditorView,+ language: LanguageAdapterType,+): LanguageAdapterType | false {+ // Check if the language can be toggled+ if (!canToggleToLanguage(editorView, language)) {+ return false;+ }++ switchLanguage(editorView, language);++ return language;+}diff --git a/frontend/src/core/codemirror/language/extension.ts b/frontend/src/core/codemirror/language/extension.tsindex 33fa95f65e..1709e1791c 100644--- a/frontend/src/core/codemirror/language/extension.ts+++ b/frontend/src/core/codemirror/language/extension.ts@@ -6,9 +6,7 @@ import {StateField,} from "@codemirror/state";import { LanguageAdapter } from "./types";-import { PythonLanguageAdapter } from "./python";import { EditorView, Panel, keymap, showPanel } from "@codemirror/view";-import { MarkdownLanguageAdapter } from "./markdown";import { clamp } from "@/utils/math";import { CompletionConfig } from "@/core/config/config-schema";import {@@ -23,22 +21,19 @@ import { formattingChangeEffect } from "../format";import { getEditorCodeAsPython } from "./utils";import { HotkeyProvider } from "@/core/hotkeys/hotkeys";import { CodeMirrorSetupOpts } from "../cm";+import { getLanguageAdapters, LanguageAdapters } from "./LanguageAdapters";+import { createPanel } from "../react-dom/createPanel";+import { LanguagePanelComponent } from "./panel";-export const LanguageAdapters: Record<- LanguageAdapter["type"],- () => LanguageAdapter-> = {- python: () => new PythonLanguageAdapter(),- markdown: () => new MarkdownLanguageAdapter(),-};--const LANGUAGES: LanguageAdapter[] = [- LanguageAdapters.python(),- LanguageAdapters.markdown(),-];-+/**+ * Compartment to keep track of the current language and extension.+ * When the language changes, the extensions inside the compartment will be updated.+ */const languageCompartment = new Compartment();+/**+ * State effect to set the language adapter.+ */const setLanguageAdapter = StateEffect.define<LanguageAdapter>();/**@@ -56,17 +51,22 @@ export const languageAdapterState = StateField.define<LanguageAdapter>({}return value;},+ // Only show the panel if the language is not pythonprovide: (field) =>- showPanel.from(field, (value) =>- value.type === "python" ? null : createLanguagePanel,- ),+ showPanel.from(field, (value) => {+ if (value.type === "python") {+ return null;+ }+ return createLanguagePanel;+ }),});// Keymap to toggle between languages-function languageToggle(completionConfig: CompletionConfig) {+function languageToggle() {+ const languages = getLanguageAdapters();// Cycle through the language to find the next one that supports the codeconst findNextLanguage = (code: string, index: number): LanguageAdapter => {- const language = LANGUAGES[index % LANGUAGES.length];+ const language = languages[index % languages.length];if (language.isSupported(code)) {return language;}@@ -81,7 +81,7 @@ function languageToggle(completionConfig: CompletionConfig) {run: (cm) => {// Find the next languageconst currentLanguage = cm.state.field(languageAdapterState);- const currentLanguageIndex = LANGUAGES.findIndex(+ const currentLanguageIndex = languages.findIndex((l) => l.type === currentLanguage.type,);const code = cm.state.doc.toString();@@ -151,17 +151,7 @@ function updateLanguageAdapterAndCode(}function createLanguagePanel(view: EditorView): Panel {- const dom = document.createElement("div");- dom.textContent = view.state.field(languageAdapterState).type;- dom.style.padding = "0.2rem 0.5rem";- dom.style.display = "flex";- dom.style.justifyContent = "flex-end";- return {- dom,- update(update) {- dom.textContent = update.state.field(languageAdapterState).type;- },- };+ return createPanel(view, LanguagePanelComponent);}/**@@ -198,7 +188,7 @@ export function adaptiveLanguageConfiguration(placeholderState.of(placeholderType),movementCallbacksState.of(cellMovementCallbacks),// Language adapter- languageToggle(completionConfig),+ languageToggle(),languageCompartment.of(LanguageAdapters.python().getExtension(completionConfig,@@ -211,16 +201,22 @@ export function adaptiveLanguageConfiguration(];}+/**+ * Get the best language given the editors current code.+ */export function getInitialLanguageAdapter(state: EditorView["state"]) {- const doc = getEditorCodeAsPython({ state });+ const doc = getEditorCodeAsPython({ state }).trim();// Empty doc defaults to Python- if (!doc.trim()) {+ if (!doc) {return LanguageAdapters.python();}if (LanguageAdapters.markdown().isSupported(doc)) {return LanguageAdapters.markdown();}+ if (LanguageAdapters.sql().isSupported(doc)) {+ return LanguageAdapters.sql();+ }return LanguageAdapters.python();}@@ -236,6 +232,13 @@ export function switchLanguage(updateLanguageAdapterAndCode(view, newLanguage());}+/**+ * Reconfigure the editor view with+ * the new language extensions.+ *+ * This is used when the language changes+ * (e.g. switching from markdown to python).+ */export function reconfigureLanguageEffect(view: EditorView,completionConfig: CompletionConfig,diff --git a/frontend/src/core/codemirror/language/markdown.ts b/frontend/src/core/codemirror/language/markdown.tsindex 21a9bc57bb..17bad5b0f1 100644--- a/frontend/src/core/codemirror/language/markdown.ts+++ b/frontend/src/core/codemirror/language/markdown.ts@@ -6,7 +6,6 @@ import { languages } from "@codemirror/language-data";import { parseMixed } from "@lezer/common";import { python, pythonLanguage } from "@codemirror/lang-python";import dedent from "string-dedent";-import { logNever } from "@/utils/assertNever";import {Completion,CompletionSource,@@ -16,9 +15,12 @@ import { once } from "lodash-es";import { enhancedMarkdownExtension } from "../markdown/extension";import { CompletionConfig } from "@/core/config/config-schema";import { HotkeyProvider } from "@/core/hotkeys/hotkeys";--const prefixKinds = ["", "f", "r", "fr", "rf"] as const;-type PrefixKind = (typeof prefixKinds)[number];+import { indentOneTab } from "./utils/indentOneTab";+import {+ QuotePrefixKind,+ QUOTE_PREFIX_KINDS,+ splitQuotePrefix,+} from "./utils/quotes";const quoteKinds = [['"""', '"""'],@@ -27,7 +29,7 @@ const quoteKinds = [["'", "'"],];// explode into all combinations-const pairs = prefixKinds.flatMap((prefix) =>+const pairs = QUOTE_PREFIX_KINDS.flatMap((prefix) =>quoteKinds.map(([start, end]) => [prefix + start, end]),);@@ -44,15 +46,24 @@ const regexes = pairs.map(* Language adapter for Markdown.*/export class MarkdownLanguageAdapter implements LanguageAdapter {- type = "markdown" as const;+ readonly type = "markdown";+ readonly defaultCode = 'mo.md(r"""\n""")';- lastQuotePrefix: PrefixKind = "";+ lastQuotePrefix: QuotePrefixKind = "";transformIn(pythonCode: string): [string, number] {if (!this.isSupported(pythonCode)) {throw new Error("Not supported");}+ pythonCode = pythonCode.trim();++ // empty string+ if (pythonCode === "") {+ this.lastQuotePrefix = "r";+ return ["", 0];+ }+for (const [start, regex] of regexes) {const match = pythonCode.match(regex);if (match) {@@ -74,12 +85,11 @@ export class MarkdownLanguageAdapter implements LanguageAdapter {transformOut(code: string): [string, number] {// Get the quote type from the last transformIn- // const prefix = upgradePrefixKind(this.lastQuotePrefix, code);const prefix = this.lastQuotePrefix;const isOneLine = !code.includes("\n");if (isOneLine) {- const escapedCode = code.replaceAll('"', '\\"');+ const escapedCode = code.replaceAll('"', String.raw`\"`);const start = `mo.md(${prefix}"`;const end = `")`;return [start + escapedCode + end, start.length];@@ -87,7 +97,7 @@ export class MarkdownLanguageAdapter implements LanguageAdapter {// Multiline codeconst start = `mo.md(\n ${prefix}"""\n`;- const escapedCode = code.replaceAll('"""', '\\"""');+ const escapedCode = code.replaceAll('"""', String.raw`\"""`);const end = `\n """\n)`;return [start + indentOneTab(escapedCode) + end, start.length + 1];}@@ -160,52 +170,6 @@ export class MarkdownLanguageAdapter implements LanguageAdapter {}}-// Remove the f, r, fr, rf prefixes from the quote-function splitQuotePrefix(quote: string): [PrefixKind, string] {- // start with the longest prefix- const prefixKindsByLength = [...prefixKinds].sort(- (a, b) => b.length - a.length,- );- for (const prefix of prefixKindsByLength) {- if (quote.startsWith(prefix)) {- return [prefix, quote.slice(prefix.length)];- }- }- return ["", quote];-}--export function upgradePrefixKind(kind: PrefixKind, code: string): PrefixKind {- const containsSubstitution = code.includes("{") && code.includes("}");-- // If there is no substitution, keep the same prefix- if (!containsSubstitution) {- return kind;- }-- // If there is a substitution, upgrade to an f-string- switch (kind) {- case "":- return "f";- case "r":- return "rf";- case "f":- case "rf":- case "fr":- return kind;- default:- logNever(kind);- return "f";- }-}--// Indent each line by one tab-function indentOneTab(code: string): string {- return code- .split("\n")- .map((line) => (line.trim() === "" ? line : ` ${line}`))- .join("\n");-}-const emojiCompletionSource: CompletionSource = async (context) => {// Check if the cursor is at a position where an emoji can be insertedif (!context.explicit && !context.matchBefore(/:\w*$/)) {diff --git a/frontend/src/core/codemirror/language/panel.tsx b/frontend/src/core/codemirror/language/panel.tsxnew file mode 100644index 0000000000..44d0e1e479--- /dev/null+++ b/frontend/src/core/codemirror/language/panel.tsx@@ -0,0 +1,47 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { EditorView } from "@codemirror/view";+import { languageAdapterState } from "./extension";+import { SQLLanguageAdapter } from "./sql";+import { normalizeName } from "@/core/cells/names";++export const LanguagePanelComponent: React.FC<{+ view: EditorView;+}> = ({ view }) => {+ const languageAdapter = view.state.field(languageAdapterState);+ let actions: React.ReactNode = <div />;++ if (languageAdapter instanceof SQLLanguageAdapter) {+ actions = (+ <div className="flex gap-2">+ Output variable:{" "}+ <input+ defaultValue={languageAdapter.dataframeName}+ onChange={(e) => (languageAdapter.dataframeName = e.target.value)}+ onBlur={(e) => {+ // Normalize the name to a valid variable name+ const name = normalizeName(e.target.value);+ languageAdapter.dataframeName = name;+ e.target.value = name;++ // Send noop update code event, which will trigger an update to the new output variable name+ view.dispatch({+ changes: {+ from: 0,+ to: view.state.doc.length,+ insert: view.state.doc.toString(),+ },+ });+ }}+ className="w-20 border border-border rounded px-1 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"+ />+ </div>+ );+ }++ return (+ <div className="flex justify-between px-2 pt-2">+ {actions}+ {languageAdapter.type}+ </div>+ );+};diff --git a/frontend/src/core/codemirror/language/python.ts b/frontend/src/core/codemirror/language/python.tsindex c2a9255822..f394a35caa 100644--- a/frontend/src/core/codemirror/language/python.ts+++ b/frontend/src/core/codemirror/language/python.ts@@ -26,7 +26,8 @@ import { MovementCallbacks } from "../cells/extensions";* Language adapter for Python.*/export class PythonLanguageAdapter implements LanguageAdapter {- type = "python" as const;+ readonly type = "python";+ readonly defaultCode = "";transformIn(code: string): [string, number] {return [code, 0];diff --git a/frontend/src/core/codemirror/language/sql.ts b/frontend/src/core/codemirror/language/sql.tsnew file mode 100644index 0000000000..21826639cf--- /dev/null+++ b/frontend/src/core/codemirror/language/sql.ts@@ -0,0 +1,148 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { Extension } from "@codemirror/state";+import { LanguageAdapter } from "./types";+import { sql, StandardSQL, schemaCompletionSource } from "@codemirror/lang-sql";+import dedent from "string-dedent";+import { CompletionConfig } from "@/core/config/config-schema";+import { HotkeyProvider } from "@/core/hotkeys/hotkeys";+import { indentOneTab } from "./utils/indentOneTab";+import { autocompletion, CompletionSource } from "@codemirror/autocomplete";+import { store } from "@/core/state/jotai";+import { datasetsAtom } from "@/core/datasets/state";+import {+ QUOTE_PREFIX_KINDS,+ QuotePrefixKind,+ splitQuotePrefix,+ upgradePrefixKind,+} from "./utils/quotes";+import { capabilitiesAtom } from "@/core/config/capabilities";++const quoteKinds = [+ ['"""', '"""'],+ ["'''", "'''"],+ ["'", "'"],+ ['"', '"'],+];++// explode into all combinations+// only f is supported+const pairs = QUOTE_PREFIX_KINDS.flatMap((prefix) =>+ quoteKinds.map(([start, end]) => [prefix + start, end]),+);++const regexes = pairs.map(+ ([start, end]) =>+ // df = mo.sql( space + start + capture + space + end)+ [+ start,+ new RegExp(+ `^(?<dataframe>\\w*)\\s*=\\s*mo\\.sql\\(\\s*${start}(?<sql>.*)${end}\\s*\\)$`,+ "s",+ ),+ ] as const,+);++/**+ * Language adapter for SQL.+ */+export class SQLLanguageAdapter implements LanguageAdapter {+ readonly type = "sql";+ readonly defaultCode = `_df = mo.sql(f"""select * from """)`;++ dataframeName = "_df";+ lastQuotePrefix: QuotePrefixKind = "f";++ transformIn(pythonCode: string): [string, number] {+ if (!this.isSupported(pythonCode)) {+ throw new Error("Not supported");+ }++ pythonCode = pythonCode.trim();++ // Handle empty strings+ if (pythonCode === "") {+ this.lastQuotePrefix = "f";+ return ["", 0];+ }++ for (const [start, regex] of regexes) {+ const match = pythonCode.match(regex);+ if (match) {+ const dataframe = match.groups?.dataframe || this.dataframeName;+ const innerCode = match.groups?.sql || "";++ const [quotePrefix, quoteType] = splitQuotePrefix(start);+ // store the quote prefix for later when we transform out+ this.lastQuotePrefix = quotePrefix;+ this.dataframeName = dataframe;+ const unescapedCode = innerCode.replaceAll(`\\${quoteType}`, quoteType);++ const offset = pythonCode.indexOf(innerCode);+ // string-dedent expects the first and last line to be empty / contain only whitespace, so we pad with \n+ return [dedent(`\n${unescapedCode}\n`).trim(), offset];+ }+ }++ return [pythonCode, 0];+ }++ transformOut(code: string): [string, number] {+ // Get the quote type from the last transformIn+ const prefix = upgradePrefixKind(this.lastQuotePrefix, code);++ // Multiline code+ const start = `${this.dataframeName} = mo.sql(\n ${prefix}"""\n`;+ const escapedCode = code.replaceAll('"""', String.raw`\"""`);+ const end = `\n """\n)`;+ return [start + indentOneTab(escapedCode) + end, start.length + 1];+ }++ isSupported(pythonCode: string): boolean {+ const sqlCapabilities = store.get(capabilitiesAtom).sql;+ if (!sqlCapabilities) {+ return false;+ }++ if (pythonCode.trim() === "") {+ return true;+ }++ // not 2 mo.sql calls+ if (pythonCode.split("mo.sql").length > 2) {+ return false;+ }++ return regexes.some(([, regex]) => regex.test(pythonCode));+ }++ getExtension(+ _completionConfig: CompletionConfig,+ _hotkeys: HotkeyProvider,+ ): Extension[] {+ return [+ sql({+ dialect: StandardSQL,+ }),+ autocompletion({+ activateOnTyping: true,+ }),+ StandardSQL.language.data.of({+ autocomplete: tablesCompletionSource(),+ }),+ ];+ }+}++function tablesCompletionSource(): CompletionSource {+ return (ctx) => {+ const schema: Record<string, string[]> = {};+ const datasets = store.get(datasetsAtom);+ for (const table of datasets.tables) {+ schema[table.name] = table.columns.map((column) => column.name);+ }++ return schemaCompletionSource({+ schema,+ })(ctx);+ };+}diff --git a/frontend/src/core/codemirror/language/types.ts b/frontend/src/core/codemirror/language/types.tsindex 4340c8c53c..b7d84d5867 100644--- a/frontend/src/core/codemirror/language/types.ts+++ b/frontend/src/core/codemirror/language/types.ts@@ -11,7 +11,8 @@ import { MovementCallbacks } from "../cells/extensions";* you're writing Markdown, but it will actually be transformed into Python.*/export interface LanguageAdapter {- type: "python" | "markdown";+ readonly type: LanguageAdapterType;+ readonly defaultCode: string;transformIn(code: string): [string, number];transformOut(code: string): [string, number];isSupported(code: string): boolean;@@ -22,3 +23,5 @@ export interface LanguageAdapter {movementCallbacks: MovementCallbacks,): Extension[];}++export type LanguageAdapterType = "python" | "markdown" | "sql";diff --git a/frontend/src/core/codemirror/language/utils/indentOneTab.ts b/frontend/src/core/codemirror/language/utils/indentOneTab.tsnew file mode 100644index 0000000000..8108ac4833--- /dev/null+++ b/frontend/src/core/codemirror/language/utils/indentOneTab.ts@@ -0,0 +1,9 @@+/* Copyright 2024 Marimo. All rights reserved. */++// Indent each line by one tab+export function indentOneTab(code: string): string {+ return code+ .split("\n")+ .map((line) => (line.trim() === "" ? line : ` ${line}`))+ .join("\n");+}diff --git a/frontend/src/core/codemirror/language/utils/quotes.ts b/frontend/src/core/codemirror/language/utils/quotes.tsnew file mode 100644index 0000000000..8d181dbda8--- /dev/null+++ b/frontend/src/core/codemirror/language/utils/quotes.ts@@ -0,0 +1,47 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { logNever } from "@/utils/assertNever";++export const QUOTE_PREFIX_KINDS = ["", "f", "r", "fr", "rf"] as const;+export type QuotePrefixKind = (typeof QUOTE_PREFIX_KINDS)[number];++// Remove the f, r, fr, rf prefixes from the quote+export function splitQuotePrefix(quote: string): [QuotePrefixKind, string] {+ // start with the longest prefix+ const prefixKindsByLength = [...QUOTE_PREFIX_KINDS].sort(+ (a, b) => b.length - a.length,+ );+ for (const prefix of prefixKindsByLength) {+ if (quote.startsWith(prefix)) {+ return [prefix, quote.slice(prefix.length)];+ }+ }+ return ["", quote];+}++export function upgradePrefixKind(+ kind: QuotePrefixKind,+ code: string,+): QuotePrefixKind {+ const containsSubstitution = code.includes("{") && code.includes("}");++ // If there is no substitution, keep the same prefix+ if (!containsSubstitution) {+ return kind;+ }++ // If there is a substitution, upgrade to an f-string+ switch (kind) {+ case "":+ return "f";+ case "r":+ return "rf";+ case "f":+ case "rf":+ case "fr":+ return kind;+ default:+ logNever(kind);+ return "f";+ }+}diff --git a/frontend/src/core/codemirror/react-dom/createPanel.tsx b/frontend/src/core/codemirror/react-dom/createPanel.tsxnew file mode 100644index 0000000000..3ebae76c30--- /dev/null+++ b/frontend/src/core/codemirror/react-dom/createPanel.tsx@@ -0,0 +1,25 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { EditorView, Panel } from "@codemirror/view";+import { Root, createRoot } from "react-dom/client";++export function createPanel(+ view: EditorView,+ Component: React.ComponentType<{ view: EditorView }>,+): Panel {+ const dom = document.createElement("div");+ let root: Root | undefined;++ return {+ dom,+ mount() {+ root = createRoot(dom);+ root.render(<Component view={view} />);+ },+ update() {+ root?.render(<Component view={view} />);+ },+ destroy() {+ root?.unmount();+ },+ };+}diff --git a/frontend/src/core/config/capabilities.ts b/frontend/src/core/config/capabilities.tsnew file mode 100644index 0000000000..d9e6b41e47--- /dev/null+++ b/frontend/src/core/config/capabilities.ts@@ -0,0 +1,7 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { atom } from "jotai";+import { Capabilities } from "../kernel/messages";++export const capabilitiesAtom = atom<Capabilities>({+ sql: false,+});diff --git a/frontend/src/core/datasets/state.ts b/frontend/src/core/datasets/state.tsindex 422744df12..b51c251721 100644--- a/frontend/src/core/datasets/state.ts+++ b/frontend/src/core/datasets/state.ts@@ -112,6 +112,8 @@ export function useDatasetsActions() {return useActions();}+export { datasetsAtom };+export const exportedForTesting = {reducer,createActions,diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.tsindex b74d0dd1e5..460be88427 100644--- a/frontend/src/core/islands/main.ts+++ b/frontend/src/core/islands/main.ts@@ -82,6 +82,7 @@ export async function initialize() {setCells: actions.setCells,setLayoutData: Functions.NOOP,setAppConfig: Functions.NOOP,+ setCapabilities: Functions.NOOP,onError: Logger.error,});// Define the custom element for the marimo-island tag.diff --git a/frontend/src/core/kernel/handlers.ts b/frontend/src/core/kernel/handlers.tsindex 0ec7f307ef..0b489ff650 100644--- a/frontend/src/core/kernel/handlers.ts+++ b/frontend/src/core/kernel/handlers.ts@@ -4,7 +4,7 @@ import { Objects } from "@/utils/objects";import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";import { LayoutData, LayoutState, initialLayoutState } from "../layout/layout";import { sendInstantiate } from "../network/requests";-import { CellMessage, OperationMessageData } from "./messages";+import { Capabilities, CellMessage, OperationMessageData } from "./messages";import { LayoutType } from "@/components/editor/renderers/types";import { AppConfig } from "../config/config-schema";import { CellData, createCell } from "../cells/types";@@ -20,12 +20,19 @@ export function handleKernelReady(layoutView: LayoutType;data: LayoutData;}) => void;+ setCapabilities: (capabilities: Capabilities) => void;setAppConfig: (config: AppConfig) => void;onError: (error: Error) => void;},) {- const { autoInstantiate, setCells, setLayoutData, onError, setAppConfig } =- opts;+ const {+ autoInstantiate,+ setCells,+ setLayoutData,+ onError,+ setAppConfig,+ setCapabilities,+ } = opts;const {codes,@@ -38,6 +45,7 @@ export function handleKernelReady(last_executed_code,last_execution_time = {},app_config,+ capabilities,} = data;const lastExecutedCode = last_executed_code || {};const lastExecutionTime = last_execution_time || {};@@ -81,6 +89,7 @@ export function handleKernelReady(setAppConfig({...app_config,} as AppConfig);+ setCapabilities(capabilities);// If resumed, we don't need to instantiate the UI elements,// and we should read in th existing values from the kernel.diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.tsindex df6a38d22c..d2a8c703fe 100644--- a/frontend/src/core/kernel/messages.ts+++ b/frontend/src/core/kernel/messages.ts@@ -32,3 +32,5 @@ export type OperationMessageData<T extends OperationMessageType> = Omit<Extract<schemas["MessageOperation"], { name: T }>,"name">;++export type Capabilities = OperationMessageData<"kernel-ready">["capabilities"];diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex 2ae8e4c07d..6893094118 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -37,6 +37,7 @@ import { VariableName } from "../variables/types";import { CellId } from "../cells/ids";import { kioskModeAtom } from "../mode";import { focusAndScrollCellOutputIntoView } from "../cells/scrollCellIntoView";+import { capabilitiesAtom } from "../config/capabilities";/*** WebSocket that connects to the Marimo kernel and handles incoming messages.@@ -61,6 +62,7 @@ export function useMarimoWebSocket(opts: {const { addBanner } = useBannersActions();const { addPackageAlert } = useAlertActions();const setKioskMode = useSetAtom(kioskModeAtom);+ const setCapabilities = useSetAtom(capabilitiesAtom);const handleMessage = (e: MessageEvent<JsonString<OperationMessage>>) => {const msg = jsonParseWithSpecialChar(e.data);@@ -74,6 +76,7 @@ export function useMarimoWebSocket(opts: {setCells,setLayoutData,setAppConfig,+ setCapabilities,onError: showBoundary,});setKioskMode(msg.data.kiosk);diff --git a/marimo/__init__.py b/marimo/__init__.pyindex af012d4482..ddd4f99469 100644--- a/marimo/__init__.py+++ b/marimo/__init__.py@@ -14,6 +14,8 @@ marimo is designed to be:5. fun"""+from __future__ import annotations+__all__ = ["App","Cell",@@ -58,6 +60,7 @@ __all__ = ["state","status","stop",+ "sql","style","tabs","tree",@@ -109,3 +112,4 @@ from marimo._runtime.control_flow import MarimoStopError, stopfrom marimo._runtime.runtime import cli_args, defs, query_params, refsfrom marimo._runtime.state import statefrom marimo._server.asgi import create_asgi_app+from marimo._sql import sqldiff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.pyindex 70e1eaf87c..908a93c8e8 100644--- a/marimo/_ast/visitor.py+++ b/marimo/_ast/visitor.py@@ -7,6 +7,7 @@ from dataclasses import dataclass, fieldfrom typing import Literal, Optionalfrom uuid import uuid4+from marimo._dependencies.dependencies import DependencyManagerfrom marimo._utils.variables import is_localName = str@@ -337,6 +338,39 @@ class ScopedVisitor(ast.NodeVisitor):VariableData(kind="function", required_refs=refs),)+ def visit_Call(self, node: ast.Call) -> None:+ # If the call name is sql and has one argument, and the argument is+ # a string literal, then it's likely to be a SQL query.+ # It must also come from the `mo` module.+ if (+ isinstance(node.func, ast.Attribute)+ and isinstance(node.func.value, ast.Name)+ and (node.func.value.id == "mo" or node.func.value.id == "marimo")+ and node.func.attr == "sql"+ and len(node.args) == 1+ ):+ first_arg = node.args[0]+ sql: Optional[str] = None+ if isinstance(first_arg, ast.Constant):+ sql = first_arg.s+ elif isinstance(first_arg, ast.JoinedStr):+ sql = normalize_sql_f_string(first_arg)++ if isinstance(sql, str) and DependencyManager.has_duckdb() and sql:+ import duckdb # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501++ # Add all tables in the query to the ref scope+ try:+ tables = duckdb.get_table_names(sql)+ for table in tables:+ self._add_ref(table, deleted=False)+ except (duckdb.ParserException, duckdb.InvalidInputException):+ # The user's sql query may have a syntax error+ pass++ # Visit arguments, keyword args, etc.+ self.generic_visit(node)+def visit_Lambda(self, node: ast.Lambda) -> None:# Inject the dummy name `_lambda` into ref scope to denote there's a# callable that might require additional refs.@@ -614,3 +648,18 @@ class ScopedVisitor(ast.NodeVisitor):kind="variable", required_refs=self.ref_stack[-1]),)+++def normalize_sql_f_string(node: ast.JoinedStr) -> str:+ def print_part(part: ast.expr) -> str:+ if isinstance(part, ast.FormattedValue):+ return print_part(part.value)+ elif isinstance(part, ast.JoinedStr):+ return normalize_sql_f_string(part)+ elif isinstance(part, ast.Constant):+ return str(part.s)+ else:+ # Just add '_' as a placeholder for {...} expressions+ return "'_'"++ return "".join(print_part(part) for part in node.values)diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.pyindex e912030a19..b95610990e 100644--- a/marimo/_dependencies/dependencies.py+++ b/marimo/_dependencies/dependencies.py@@ -67,6 +67,21 @@ class DependencyManager:+ "You can install it with 'pip install altair'") from None+ @staticmethod+ def require_duckdb(why: str) -> None:+ """+ Raise an ModuleNotFoundError if duckdb is not installed.++ Args:+ why: A string of the form "for <reason>" that will be appended++ """+ if not DependencyManager.has_duckdb():+ raise ModuleNotFoundError(+ f"duckdb is required {why}. "+ + "You can install it with 'pip install duckdb'"+ ) from None+@staticmethoddef require_pillow(why: str) -> None:"""@@ -147,6 +162,11 @@ class DependencyManager:"""Return True if altair is installed."""return importlib.util.find_spec("altair") is not None+ @staticmethod+ def has_duckdb() -> bool:+ """Return True if duckdb is installed."""+ return importlib.util.find_spec("duckdb") is not None+@staticmethoddef has_pillow() -> bool:"""Return True if pillow is installed."""diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex 869177a9a2..3f10d969c2 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -28,6 +28,7 @@ from marimo import _loggers as loggersfrom marimo._ast.app import _AppConfigfrom marimo._ast.cell import CellConfig, CellId_t, CellStatusTypefrom marimo._data.models import ColumnSummary, DataTable+from marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.cell_output import CellChannel, CellOutputfrom marimo._messaging.completion_option import CompletionOptionfrom marimo._messaging.errors import Error@@ -321,6 +322,14 @@ class CompletedRun(Op):name: ClassVar[str] = "completed-run"+@dataclass+class KernelCapabilities:+ sql: bool = False++ def __post_init__(self) -> None:+ self.sql = DependencyManager.has_duckdb()++@dataclassclass KernelReady(Op):"""Kernel is ready for execution."""@@ -343,6 +352,8 @@ class KernelReady(Op):app_config: _AppConfig# Whether the kernel is kiosk modekiosk: bool+ # Kernel capabilities+ capabilities: KernelCapabilities@dataclassdiff --git a/marimo/_pyodide/bootstrap.py b/marimo/_pyodide/bootstrap.pyindex 8c4ee27e3c..3e6859105b 100644--- a/marimo/_pyodide/bootstrap.py+++ b/marimo/_pyodide/bootstrap.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport jsonfrom typing import TYPE_CHECKING, Callable-from marimo._messaging.ops import KernelReady, serialize+from marimo._messaging.ops import KernelCapabilities, KernelReady, serializefrom marimo._plugins.core.json_encoder import WebComponentEncoderfrom marimo._runtime.requests import (AppMetadata,@@ -80,6 +80,7 @@ def create_session(last_execution_time={},app_config=app.config,kiosk=False,+ capabilities=KernelCapabilities(),)),)diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.pyindex f41bdac644..3f404b33ff 100644--- a/marimo/_server/api/endpoints/ai.py+++ b/marimo/_server/api/endpoints/ai.py@@ -16,6 +16,7 @@ from marimo._server.models.completion import (AiCompletionRequest,)from marimo._server.router import APIRouter+from marimo._utils.assert_never import assert_neverif TYPE_CHECKING:from openai import OpenAI, Stream # type: ignore[import-not-found]@@ -69,28 +70,65 @@ def get_openai_client(config: MarimoConfig) -> "OpenAI":def get_model(config: MarimoConfig) -> str:model: str = (- config.get("ai", {}).get("open_ai", {}).get("model", "gpt-3.5-turbo")+ config.get("ai", {}).get("open_ai", {}).get("model", "gpt-4-turbo"))if not model:- model = "gpt-3.5-turbo"+ model = "gpt-4-turbo"return modeldef make_stream_response(response: Stream[ChatCompletionChunk],) -> Generator[str, None, None]:+ original_content = ""+ buffer: str = ""+ in_code_fence = False# If it starts or ends with markdown, remove itfor chunk in response:content = chunk.choices[0].delta.content- if content:- if content.startswith("```python"):- yield content[9:]- if content.startswith("```"):- yield content[4:]- elif content.endswith("```"):- yield content[:-3]- else:- yield content or ""+ if not content:+ continue++ buffer += content+ original_content += content+ first_newline = buffer.find("\n")++ # Open code-fence, with no newline+ # wait for the next newline+ if (+ buffer.startswith("```")+ and first_newline == -1+ and not in_code_fence+ ):+ continue++ if (+ buffer.startswith("```")+ and first_newline > 0+ and not in_code_fence+ ):+ # And also ends with ```+ if buffer.endswith("```"):+ yield buffer[first_newline + 1 : -3]+ buffer = ""+ in_code_fence = False+ continue++ yield buffer[first_newline + 1 :]+ buffer = ""+ in_code_fence = True+ continue++ if buffer.endswith("```") and in_code_fence:+ yield buffer[:-3]+ buffer = ""+ in_code_fence = False+ continue++ yield buffer+ buffer = ""++ LOGGER.debug(f"Completion content: {original_content}")@router.post("/completion")@@ -122,17 +160,30 @@ async def ai_completion(body = await parse_request(request, cls=AiCompletionRequest)client = get_openai_client(config)- system_prompt = (- "You are a helpful assistant that can answer questions "- "about python code. You can only output python code. "- "1. Do not describe the code, just write the code."- "2. Do not output markdown or backticks."- "3. When using matplotlib to show plots,"- "use plt.gca() instead of plt.show()."- "4. If an import already exists, do not import it again."- "5. If a variable is already defined, use another name, or"- "make it private by adding an underscore at the beginning."- )+ if body.language == "python":+ system_prompt = (+ "You are a helpful assistant that can answer questions "+ "about python code. You can only output python code. "+ "1. Do not describe the code, just write the code."+ "2. Do not output markdown or backticks."+ "3. When using matplotlib to show plots,"+ "use plt.gca() instead of plt.show()."+ "4. If an import already exists, do not import it again."+ "5. If a variable is already defined, use another name, or"+ "make it private by adding an underscore at the beginning."+ )+ elif body.language == "markdown":+ system_prompt = (+ "You are a helpful assistant that can answer questions "+ "about markdown. You can only output markdown."+ )+ elif body.language == "sql":+ system_prompt = (+ "You are a helpful assistant that can answer questions "+ "about sql. You can only output sql."+ )+ else:+ assert_never(body.language)prompt = body.promptif body.include_other_code:diff --git a/marimo/_server/api/endpoints/ws.py b/marimo/_server/api/endpoints/ws.pyindex 323ba8935b..abea49fa0c 100644--- a/marimo/_server/api/endpoints/ws.py+++ b/marimo/_server/api/endpoints/ws.py@@ -15,6 +15,7 @@ from marimo._messaging.ops import (Banner,CompletionResult,FocusCell,+ KernelCapabilities,KernelReady,MessageOperation,Reconnected,@@ -198,6 +199,7 @@ class WebsocketHandler(SessionConsumer):last_execution_time=last_execution_time,app_config=app.config,kiosk=kiosk,+ capabilities=KernelCapabilities(),)),)diff --git a/marimo/_server/models/completion.py b/marimo/_server/models/completion.pyindex 61e380e0fb..cbc70b4359 100644--- a/marimo/_server/models/completion.py+++ b/marimo/_server/models/completion.py@@ -1,5 +1,8 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+from dataclasses import dataclass+from typing import Literal@dataclass@@ -7,3 +10,4 @@ class AiCompletionRequest:prompt: strinclude_other_code: strcode: str+ language: Literal["python", "markdown", "sql"] = "python"diff --git a/marimo/_smoke_tests/sql.py b/marimo/_smoke_tests/sql.pynew file mode 100644index 0000000000..642020fe3c--- /dev/null+++ b/marimo/_smoke_tests/sql.py@@ -0,0 +1,170 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.6.25"+app = marimo.App(width="medium")+++def __():+ import altair as alt+ from vega_datasets import data+ import duckdb+ import marimo as mo+ return alt, data, duckdb, mo++[email protected](hide_code=True)+def __(mo):+ mo.md("## Cars")+ return+++def __(data, mo):+ # Create a slider with the range of car cylinders+ cars = data.cars()+ cylinders = mo.ui.slider.from_series(cars["Cylinders"])+ cylinders+ return cars, cylinders+++def __(cars, cylinders, mo):+ df = mo.sql(+ f"""+ SELECT "Name", "Miles_per_Gallon", "Cylinders", "Horsepower"+ FROM cars+ WHERE "Cylinders" = {cylinders.value}+ """+ )+ return df,+++def __(alt, df, mo):+ # Chart the filtered cars+ mo.ui.altair_chart(+ alt.Chart(df)+ .mark_point()+ .encode(x="Miles_per_Gallon", y="Horsepower")+ .properties(height=200)+ )+ return++[email protected](hide_code=True)+def __(mo):+ mo.md("## Airports")+ return+++def __(data):+ airports = data.airports()+ return airports,+++def __(airports, mo):+ less_airports = mo.sql(+ f"""+ select * from airports limit 2+ """+ )+ return less_airports,+++def __(less_airports):+ len(less_airports)+ return+++def __(mo):+ mo.md("## Google Sheets")+ return+++def __():+ sheet = "https://docs.google.com/spreadsheets/export?format=csv&id=1GuEPkwjdICgJ31Ji3iUoarirZNDbPxQj_kf7fd4h4Ro"+ return sheet,+++def __(mo, sheet):+ job_types = mo.sql(+ f"""+ SELECT DISTINCT current_job_title+ FROM read_csv_auto('{sheet}', normalize_names=True)+ """+ )+ return job_types,+++def __(job_types, mo):+ job_title = mo.ui.dropdown.from_series(job_types["current_job_title"])+ job_title+ return job_title,+++def __(job_title, mo, sheet):+ _df = mo.sql(+ f"""+ SELECT *+ FROM read_csv_auto('{sheet}', normalize_names=True)+ WHERE current_job_title == '{job_title.value}'+ """+ )+ return++[email protected](hide_code=True)+def __(mo):+ mo.md("Debug")+ return++[email protected](hide_code=True)+def __(duckdb):+ duckdb.get_table_names(+ f"""+ SELECT "Name", "Miles_per_Gallon", "Cylinders", "Horsepower"+ FROM cars+ """+ )+ return++[email protected](hide_code=True)+def __(duckdb, job_title, sheet):+ duckdb.get_table_names(+ f"""+ SELECT *+ FROM read_csv_auto('{sheet}', normalize_names=True)+ WHERE current_job_title == '{job_title.value}'+ """+ )+ return+++def __(cars, mo):+ grouped_cars_by_origin = mo.sql(+ """+ SELECT "Origin", COUNT(*) AS "Count"+ FROM cars+ GROUP BY "Origin"+ LIMIT 100+ """+ )+ return grouped_cars_by_origin,+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_sql/__init__.py b/marimo/_sql/__init__.pynew file mode 100644index 0000000000..00769455d7--- /dev/null+++ b/marimo/_sql/__init__.py@@ -0,0 +1,8 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++__all__ = [+ "sql",+]++from marimo._sql.sql import sqldiff --git a/marimo/_sql/sql.py b/marimo/_sql/sql.pynew file mode 100644index 0000000000..81a67a9373--- /dev/null+++ b/marimo/_sql/sql.py@@ -0,0 +1,46 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from typing import Any++from marimo._dependencies.dependencies import DependencyManager+from marimo._output.rich_help import mddoc+from marimo._plugins.ui._impl import table+from marimo._runtime import output+++@mddoc+def sql(query: str) -> Any:+ """+ Execute a SQL query.++ This uses duckdb to execute the query. Any dataframes in the global+ namespace can be used inside the query.++ The result of the query is displayed in the UI.++ Args:+ query: The SQL query to execute.++ Returns:+ The result of the query.+ """+ DependencyManager.require_duckdb("to execute sql")++ import duckdb # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501++ if DependencyManager.has_polars():+ df = duckdb.execute(query=query).pl()+ t = table.table(df, selection=None, page_size=5, pagination=True)+ output.replace(t)+ return df+ if DependencyManager.has_pandas():+ df = duckdb.execute(query=query).df()+ t = table.table(df, selection=None, page_size=5, pagination=True)+ output.replace(t)+ return df++ raise ModuleNotFoundError(+ "pandas or polars is required to execute sql. "+ + "You can install them with 'pip install pandas polars'"+ )diff --git a/openapi/api.yaml b/openapi/api.yamlindex ad31917f72..73354d2a6a 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -808,6 +808,13 @@ components:required:- widthtype: object+ capabilities:+ properties:+ sql:+ type: boolean+ required:+ - sql+ type: objectcell_ids:items:type: string@@ -879,6 +886,7 @@ components:- resumed- app_config- kiosk+ - capabilities- nametype: objectMIME:@@ -1672,7 +1680,7 @@ components:type: objectinfo:title: marimo API- version: 0.6.24+ version: 0.6.25openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex 90a20e9997..24c4b8ef9a 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -1060,6 +1060,9 @@ export interface components {/** @enum {string} */width: "normal" | "compact" | "medium" | "full";};+ capabilities: {+ sql: boolean;+ };cell_ids: string[];codes: string[];configs: components["schemas"]["CellConfig"][];diff --git a/tests/_ast/test_visitor.py b/tests/_ast/test_visitor.pyindex 9754293bcd..9f110a2032 100644--- a/tests/_ast/test_visitor.py+++ b/tests/_ast/test_visitor.py@@ -7,7 +7,12 @@ from inspect import cleandocimport pytestfrom marimo._ast import visitor-from marimo._ast.visitor import ImportData, VariableData+from marimo._ast.visitor import (+ ImportData,+ VariableData,+ normalize_sql_f_string,+)+from marimo._dependencies.dependencies import DependencyManagerdef test_assign_simple() -> None:@@ -858,3 +863,115 @@ def test_private_ref_requirement_caught() -> None:kind="function", required_refs={"X", "x", private}),}+++HAS_DEPS = DependencyManager.has_duckdb()++[email protected](not HAS_DEPS, reason="Requires duckdb")+def test_sql_statement() -> None:+ code = "\n".join(+ [+ "df = mo.sql('select * from cars')",+ ]+ )+ v = visitor.ScopedVisitor()+ mod = ast.parse(code)+ v.visit(mod)+ assert v.defs == set(["df"])+ assert v.refs == set(["cars", "mo"])++[email protected](not HAS_DEPS, reason="Requires duckdb")+def test_sql_statement_with_marimo_sql() -> None:+ code = "\n".join(+ [+ "df = marimo.sql('select * from cars')",+ ]+ )+ v = visitor.ScopedVisitor()+ mod = ast.parse(code)+ v.visit(mod)+ assert v.defs == set(["df"])+ assert v.refs == set(["cars", "marimo"])++[email protected](not HAS_DEPS, reason="Requires duckdb")+def test_sql_statement_with_f_string() -> None:+ code = "\n".join(+ [+ "df = mo.sql(f'select * from cars where name = {name}')",+ ]+ )+ v = visitor.ScopedVisitor()+ mod = ast.parse(code)+ v.visit(mod)+ assert v.defs == set(["df"])+ assert v.refs == set(["cars", "mo", "name"])++[email protected](not HAS_DEPS, reason="Requires duckdb")+def test_sql_statement_with_rf_string() -> None:+ code = "\n".join(+ [+ "df = mo.sql(rf'select * from cars where name = {name}')",+ ]+ )+ v = visitor.ScopedVisitor()+ mod = ast.parse(code)+ v.visit(mod)+ assert v.defs == set(["df"])+ assert v.refs == set(["cars", "mo", "name"])+++def test_print_f_string() -> None:+ import ast++ joined_str = ast.parse("f'select * from cars where name = {name}'")+ assert (+ normalize_sql_f_string(joined_str.body[0].value) # type: ignore+ == "select * from cars where name = '_'"+ )++[email protected](not HAS_DEPS, reason="Requires duckdb")+def test_sql_empty_statement() -> None:+ code = "\n".join(+ [+ "mo.sql('')",+ ]+ )+ v = visitor.ScopedVisitor()+ mod = ast.parse(code)+ v.visit(mod)+ assert v.defs == set([])+ assert v.refs == set(["mo"])++[email protected](not HAS_DEPS, reason="Requires duckdb")+def test_sql_multiple_tables() -> None:+ code = "\n".join(+ [+ "df = mo.sql('select * from cars left join"+ " cars2 on cars.id = cars2.id')",+ ]+ )+ v = visitor.ScopedVisitor()+ mod = ast.parse(code)+ v.visit(mod)+ assert v.defs == set(["df"])+ assert v.refs == set(["cars", "cars2", "mo"])++[email protected](not HAS_DEPS, reason="Requires duckdb")+def test_sql_from_another_module() -> None:+ code = "\n".join(+ [+ "df = lib.sql('select * from cars')",+ ]+ )+ v = visitor.ScopedVisitor()+ mod = ast.parse(code)+ v.visit(mod)+ assert v.defs == set(["df"])+ assert v.refs == set(["lib"])diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.pyindex 038998182c..44bd4c70e2 100644--- a/tests/_server/api/endpoints/test_ai.py+++ b/tests/_server/api/endpoints/test_ai.py@@ -1,6 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import unittestfrom contextlib import contextmanagerfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, List@@ -10,6 +11,7 @@ import pytestfrom marimo._config.manager import UserConfigManagerfrom marimo._dependencies.dependencies import DependencyManager+from marimo._server.api.endpoints.ai import make_stream_responsefrom tests._server.conftest import get_user_config_managerfrom tests._server.mocks import token_header, with_session@@ -267,3 +269,83 @@ def no_openai_config(config: UserConfigManager):yieldfinally:config.save_config(prev_config)+++class TestStreamResponse(unittest.TestCase):+ def simulate_stream(self, contents: List[str]) -> Any:+ class MockContent:+ def __init__(self, content: str) -> None:+ self.content = content++ class MockDelta:+ def __init__(self, content: str) -> None:+ self.delta = MockContent(content)++ class MockChunk:+ def __init__(self, content: str) -> None:+ self.choices = [MockDelta(content)]++ for content in contents:+ yield MockChunk(content)++ def test_no_code_fence(self):+ response = self.simulate_stream(["Hello, world!"])+ result = list(make_stream_response(response))+ assert result == ["Hello, world!"]++ def test_single_complete_code_fence(self):+ response = self.simulate_stream(+ ["```python\nprint('Hello, world!')\n```"]+ )+ result = list(make_stream_response(response))+ assert result == ["print('Hello, world!')\n"]++ def test_code_fence_across_chunks(self):+ response = self.simulate_stream(+ [+ "```python\nprint('Hello,",+ " world!')\n```",+ ]+ )+ result = list(make_stream_response(response))+ assert result == [+ "print('Hello,",+ " world!')\n",+ ]++ def test_code_fence_across_more_chunks(self):+ response = self.simulate_stream(+ [+ "```",+ "python",+ "\nprint('Hello,",+ " world!')\n",+ "```",+ ]+ )+ result = list(make_stream_response(response))+ assert result == ["print('Hello,", " world!')\n", ""]++ def test_multiple_code_fences(self):+ response = self.simulate_stream(+ [+ "```python\nprint('Hello',",+ " 'world!')\n```",+ "No code here",+ "```sql\nSELECT * FROM users;\n```",+ ]+ )+ result = list(make_stream_response(response))+ assert result == [+ "print('Hello',",+ " 'world!')\n",+ "No code here",+ "SELECT * FROM users;\n",+ ]++ def test_nested_code_fences(self):+ response = self.simulate_stream(+ ["```python\nprint('```nested```')\n```"]+ )+ result = list(make_stream_response(response))+ assert result == ["print('```nested```')\n"]diff --git a/tests/_server/api/endpoints/test_kiosk.py b/tests/_server/api/endpoints/test_kiosk.pyindex 989ca51316..5a98878c1c 100644--- a/tests/_server/api/endpoints/test_kiosk.py+++ b/tests/_server/api/endpoints/test_kiosk.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Any, Optional+from marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.ops import KernelReadyfrom marimo._utils.parse_dataclass import parse_rawfrom tests._server.mocks import token_header@@ -26,6 +27,9 @@ def create_response("kiosk": False,"configs": [{"disabled": False, "hide_code": False}],"app_config": {"width": "full"},+ "capabilities": {+ "sql": DependencyManager.has_duckdb(),+ },}response.update(partial_response)return response@@ -53,6 +57,7 @@ def assert_kernel_ready_response(assert data.configs == expected.configsassert data.app_config == expected.app_configassert data.kiosk == expected.kiosk+ assert data.capabilities == expected.capabilitiesdef assert_parse_ready_response(raw_data: dict[str, Any]) -> None:diff --git a/tests/_server/api/endpoints/test_resume_session.py b/tests/_server/api/endpoints/test_resume_session.pyindex cd328f26ff..673b81f61e 100644--- a/tests/_server/api/endpoints/test_resume_session.py+++ b/tests/_server/api/endpoints/test_resume_session.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport timefrom typing import TYPE_CHECKING, Any, Optional+from marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.ops import CellOp, KernelReadyfrom marimo._server.sessions import Sessionfrom marimo._utils.parse_dataclass import parse_raw@@ -29,6 +30,9 @@ def create_response("kiosk": False,"configs": [{"disabled": False, "hide_code": False}],"app_config": {"width": "full"},+ "capabilities": {+ "sql": DependencyManager.has_duckdb(),+ },}response.update(partial_response)return response@@ -60,6 +64,7 @@ def assert_kernel_ready_response(assert data.configs == expected.configsassert data.app_config == expected.app_configassert data.last_execution_time == expected.last_execution_time+ assert data.capabilities == expected.capabilitiesdef get_session(client: TestClient, session_id: str) -> Optional[Session]:diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.pyindex 179d09f281..847e9a2d11 100644--- a/tests/_server/api/endpoints/test_ws.py+++ b/tests/_server/api/endpoints/test_ws.py@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Any, Optionalimport pytestfrom starlette.websockets import WebSocketDisconnect+from marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.ops import KernelReadyfrom marimo._server.api.endpoints.ws import WebSocketCodesfrom marimo._server.model import SessionMode@@ -34,6 +35,9 @@ def create_response("kiosk": False,"configs": [{"disabled": False, "hide_code": False}],"app_config": {"width": "full"},+ "capabilities": {+ "sql": DependencyManager.has_duckdb(),+ },}response.update(partial_response)return response@@ -60,6 +64,7 @@ def assert_kernel_ready_response(assert data.configs == expected.configsassert data.app_config == expected.app_configassert data.kiosk == expected.kiosk+ assert data.capabilities == expected.capabilitiesdef assert_parse_ready_response(raw_data: dict[str, Any]) -> None:@@ -164,7 +169,7 @@ async def test_file_watcher_calls_reload(client: TestClient) -> None:unsubscribe = session_manager.start_file_watcher()filename = session_manager.file_router.get_unique_file_key()assert filename- with open(filename, "a") as f: # noqa: ASYNC101+ with open(filename, "a") as f: # noqa: ASYNC101 ASYNC230f.write("\n# test")f.close()assert session_manager.watcher