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.

improvement: Configurable SQL output type (#4437)

Myles Scolnick7b828c0518d1
diff --git a/docs/guides/working_with_data/sql.md b/docs/guides/working_with_data/sql.md
index 32b4817604..1a097ed750 100644
--- a/docs/guides/working_with_data/sql.md
+++ b/docs/guides/working_with_data/sql.md
@@ -77,6 +77,24 @@ interpolate Python values into the query with `{}`. In particular, this means
your SQL queries can depend on the values of UI elements or other Python values,
and they are fit into marimo's reactive dataflow graph.
+## SQL Output Types
+
+marimo supports different output types for SQL queries, which is particularly useful when working with large datasets. You can configure this in your application configuration in the top right of the marimo editor.
+
+The available options are:
+
+- `native`: Uses DuckDB's native lazy relation (recommended for best performance)
+- `lazy-polars`: Returns a lazy Polars DataFrame
+- `pandas`: Returns a Pandas DataFrame
+- `polars`: Returns an eager Polars DataFrame
+- `auto`: Automatically chooses based on installed packages (first tries `polars` then `pandas`)
+
+For best performance with large datasets, we recommend using `native` to avoid loading the entire result set into memory and to more easily chain SQL cells together. By default, only the first 10 rows are displayed in the UI to prevent memory issues.
+
+??? note "Set a default"
+
+ The default output type is currently `auto`, but we recommend explicitly setting the output type to `native` for best performance with large datasets or `polars` if you need to work with the results in Python code. You can configure this in your application settings.
+
## Reference a local dataframe
You can reference a local dataframe in your SQL cell by using the name of the
diff --git a/frontend/src/components/app-config/app-config-form.tsx b/frontend/src/components/app-config/app-config-form.tsx
index 179cf214c2..027acc40f2 100644
--- a/frontend/src/components/app-config/app-config-form.tsx
+++ b/frontend/src/components/app-config/app-config-form.tsx
@@ -25,7 +25,8 @@ import { useEffect } from "react";
import { Checkbox } from "../ui/checkbox";
import { arrayToggle } from "@/utils/arrays";
import { Kbd } from "../ui/kbd";
-
+import { ExternalLink } from "../ui/links";
+import { toast } from "../ui/use-toast";
export const AppConfigForm: React.FC = () => {
const [config, setConfig] = useAppConfig();
@@ -174,6 +175,51 @@ export const AppConfigForm: React.FC = () => {
</div>
)}
/>
+ <FormField
+ control={form.control}
+ name="sql_output"
+ render={({ field }) => (
+ <div className="flex flex-col gap-y-1">
+ <FormItem
+ className={"flex flex-row items-center space-x-1 space-y-0"}
+ >
+ <FormLabel>SQL Output Type</FormLabel>
+ <FormControl>
+ <NativeSelect
+ data-testid="sql-output-select"
+ onChange={(e) => {
+ field.onChange(e.target.value);
+ toast({
+ title: "Kernel Restart Required",
+ description:
+ "This change requires a kernel restart to take effect.",
+ });
+ }}
+ value={field.value}
+ disabled={field.disabled}
+ className="inline-flex mr-2"
+ >
+ <option value="auto">Auto (Default)</option>
+ <option value="native">Native</option>
+ <option value="polars">Polars</option>
+ <option value="lazy-polars">Lazy Polars</option>
+ <option value="pandas">Pandas</option>
+ </NativeSelect>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ <FormDescription>
+ The Python type returned by a SQL cell. For best performance
+ with large datasets, we recommend using{" "}
+ <Kbd className="inline">native</Kbd>. See the{" "}
+ <ExternalLink href="http://docs.marimo.io/guides/working_with_data/sql">
+ SQL guide
+ </ExternalLink>{" "}
+ for more information.
+ </FormDescription>
+ </div>
+ )}
+ />
<FormField
control={form.control}
name="auto_download"
diff --git a/frontend/src/core/config/__tests__/config-schema.test.ts b/frontend/src/core/config/__tests__/config-schema.test.ts
index c5950f1ed1..230b28d847 100644
--- a/frontend/src/core/config/__tests__/config-schema.test.ts
+++ b/frontend/src/core/config/__tests__/config-schema.test.ts
@@ -15,6 +15,7 @@ test("default AppConfig", () => {
expect(defaultConfig).toMatchInlineSnapshot(`
{
"auto_download": [],
+ "sql_output": "auto",
"width": "medium",
}
`);
@@ -29,6 +30,7 @@ test("another AppConfig", () => {
{
"app_title": null,
"auto_download": [],
+ "sql_output": "auto",
"width": "medium",
}
`);
diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.ts
index 30f2a32739..001f262ec7 100644
--- a/frontend/src/core/config/config-schema.ts
+++ b/frontend/src/core/config/config-schema.ts
@@ -29,6 +29,18 @@ const VALID_APP_WIDTHS = [
"full",
"columns",
] as const;
+
+/**
+ * SQL output formats
+ */
+const VALID_SQL_OUTPUT_FORMATS = [
+ "auto",
+ "native",
+ "polars",
+ "lazy-polars",
+ "pandas",
+] as const;
+
export const UserConfigSchema = z
.object({
completion: z
@@ -168,6 +180,8 @@ export type LSPConfig = UserConfig["language_servers"];
export type DiagnosticsConfig = UserConfig["diagnostics"];
export const AppTitleSchema = z.string();
+export const SqlOutputSchema = z.enum(VALID_SQL_OUTPUT_FORMATS).default("auto");
+
export const AppConfigSchema = z
.object({
width: z
@@ -183,6 +197,7 @@ export const AppConfigSchema = z
css_file: z.string().nullish(),
html_head_file: z.string().nullish(),
auto_download: z.array(z.enum(["html", "markdown", "ipynb"])).default([]),
+ sql_output: SqlOutputSchema,
})
.default({ width: "medium", auto_download: [] });
export type AppConfig = z.infer<typeof AppConfigSchema>;
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index 897b253e91..84c584584c 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -4,7 +4,6 @@ import type { CellId } from "../cells/ids";
export type schemas = components["schemas"];
export type AiCompletionRequest = schemas["AiCompletionRequest"];
-export type AppMetadata = schemas["AppMetadata"];
export type BaseResponse = schemas["BaseResponse"];
export type CellConfig = schemas["CellConfig"];
/**
diff --git a/frontend/src/css/app/codemirror-completions.css b/frontend/src/css/app/codemirror-completions.css
index 4e0539dbcc..2b3dc7b63c 100644
--- a/frontend/src/css/app/codemirror-completions.css
+++ b/frontend/src/css/app/codemirror-completions.css
@@ -28,7 +28,7 @@
padding-top: 1px;
padding-bottom: 1px;
padding-right: 12px;
- @apply text-xs;
+ @apply text-xs font-mono;
}
.cm-completionDetail {
@@ -192,7 +192,7 @@
/* Completion matching text highlight */
.cm-completionMatchedText {
- @apply font-semibold text-primary underline underline-offset-2;
+ @apply text-accent-foreground font-medium underline underline-offset-2;
}
/* Scrollbar styling for autocomplete list */
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index 3ed6440988..4eb283f425 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -153,7 +153,11 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")
totalColumns: z.number(),
hasStableRowId: z.boolean().default(false),
cellStyles: z.record(z.record(z.object({}).passthrough())).optional(),
+ // Whether to load the data lazily.
lazy: z.boolean(),
+ // If lazy, this will preload the first page of data
+ // without user confirmation.
+ preload: z.boolean(),
}),
)
.withFunctions<DataTableFunctions>({
@@ -211,7 +215,10 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")
.renderer((props) => {
return (
<TooltipProvider>
- <LazyDataTableComponent isLazy={props.data.lazy}>
+ <LazyDataTableComponent
+ isLazy={props.data.lazy}
+ preload={props.data.preload}
+ >
<LoadingDataTableComponent
{...props.data}
{...props.functions}
@@ -228,11 +235,13 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")
const LazyDataTableComponent = ({
isLazy: initialIsLazy,
children,
+ preload,
}: {
isLazy: boolean;
children: React.ReactNode;
+ preload: boolean;
}) => {
- const [isLazy, setIsLazy] = useState(initialIsLazy);
+ const [isLazy, setIsLazy] = useState(initialIsLazy && !preload);
if (isLazy) {
return (
@@ -614,8 +623,9 @@ const DataTableComponent = ({
return (
<>
- {/* // HACK: We assume "too_many" is coming from a SQL table */}
- {totalRows === "too_many" && (
+ {/* When the totalRows is "too_many" and the pageSize is the same as the
+ * number of rows, we are likely displaying all the data (could be more, but we don't know the total). */}
+ {totalRows === "too_many" && paginationState.pageSize === data.length && (
<Banner className="mb-1 rounded">
Previewing the first {paginationState.pageSize} rows.
</Banner>
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 81b16d0746..eedb56fed0 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -8,7 +8,7 @@ import inspect
import sys
import threading
from collections.abc import Iterable, Iterator, Mapping
-from dataclasses import asdict, dataclass, field
+from dataclasses import dataclass
from pathlib import Path
from textwrap import dedent
from typing import (
@@ -24,6 +24,7 @@ from typing import (
)
from uuid import uuid4
+from marimo._ast.app_config import _AppConfig
from marimo._types.ids import CellId_t
if sys.version_info < (3, 10):
@@ -43,7 +44,6 @@ from marimo._ast.errors import (
SetupRootError,
UnparsableError,
)
-from marimo._config.config import WidthType
from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.hypertext import Html
from marimo._output.rich_help import mddoc
@@ -76,61 +76,6 @@ Cls: TypeAlias = type
LOGGER = _loggers.marimo_logger()
-@dataclass
-class _AppConfig:
- """Program-specific configuration.
-
- Configuration for frontends or runtimes that is specific to
- a single marimo program.
- """
-
- width: WidthType = "compact"
- app_title: Optional[str] = None
-
- # The file path of the layout file, relative to the app file.
- layout_file: Optional[str] = None
-
- # CSS file, relative to the app file
- css_file: Optional[str] = None
-
- # HTML head file, relative to the app file
- html_head_file: Optional[str] = None
-
- # Whether to automatically download the app as HTML and Markdown
- auto_download: list[Literal["html", "markdown"]] = field(
- default_factory=list
- )
-
- # Experimental top-level cell support
- _toplevel_fn: bool = False
-
- @staticmethod
- def from_untrusted_dict(updates: dict[str, Any]) -> _AppConfig:
- config = _AppConfig()
- for key in updates:
- if hasattr(config, key):
- config.__setattr__(key, updates[key])
- else:
- LOGGER.warning(
- f"Unrecognized key '{key}' in app config. Ignoring."
- )
- return config
-
- def asdict(self) -> dict[str, Any]:
- # Used for experimental hooks which start with _
- return {
- k: v for (k, v) in asdict(self).items() if not k.startswith("_")
- }
-
- def update(self, updates: dict[str, Any]) -> _AppConfig:
- config_dict = asdict(self)
- for key in updates:
- if key in config_dict:
- self.__setattr__(key, updates[key])
-
- return self
-
-
class _Namespace(Mapping[str, object]):
def __init__(
self, dictionary: dict[str, object], owner: Cell | App
diff --git a/marimo/_ast/app_config.py b/marimo/_ast/app_config.py
new file mode 100644
index 0000000000..b627aa2ba5
--- /dev/null
+++ b/marimo/_ast/app_config.py
@@ -0,0 +1,66 @@
+from dataclasses import asdict, dataclass, field
+from typing import Any, Literal, Optional
+
+from marimo import _loggers
+from marimo._config.config import SqlOutputType, WidthType
+
+LOGGER = _loggers.marimo_logger()
+
+
+@dataclass
+class _AppConfig:
+ """Program-specific configuration.
+
+ Configuration for frontends or runtimes that is specific to
+ a single marimo program.
+ """
+
+ width: WidthType = "compact"
+
+ app_title: Optional[str] = None
+
+ # The file path of the layout file, relative to the app file.
+ layout_file: Optional[str] = None
+
+ # CSS file, relative to the app file
+ css_file: Optional[str] = None
+
+ # HTML head file, relative to the app file
+ html_head_file: Optional[str] = None
+
+ # Whether to automatically download the app as HTML and Markdown
+ auto_download: list[Literal["html", "markdown"]] = field(
+ default_factory=list
+ )
+
+ # The type of SQL output to display
+ sql_output: SqlOutputType = "auto"
+
+ # Experimental top-level cell support
+ _toplevel_fn: bool = False
+
+ @staticmethod
+ def from_untrusted_dict(updates: dict[str, Any]) -> "_AppConfig":
+ config = _AppConfig()
+ for key in updates:
+ if hasattr(config, key):
+ config.__setattr__(key, updates[key])
+ else:
+ LOGGER.warning(
+ f"Unrecognized key '{key}' in app config. Ignoring."
+ )
+ return config
+
+ def asdict(self) -> dict[str, Any]:
+ # Used for experimental hooks which start with _
+ return {
+ k: v for (k, v) in asdict(self).items() if not k.startswith("_")
+ }
+
+ def update(self, updates: dict[str, Any]) -> "_AppConfig":
+ config_dict = asdict(self)
+ for key in updates:
+ if key in config_dict:
+ self.__setattr__(key, updates[key])
+
+ return self
diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.py
index 89b7b85349..a1991b3c2f 100644
--- a/marimo/_ast/codegen.py
+++ b/marimo/_ast/codegen.py
@@ -12,7 +12,8 @@ import textwrap
from typing import Any, Literal, Optional, cast
from marimo import __version__
-from marimo._ast.app import App, _AppConfig
+from marimo._ast.app import App
+from marimo._ast.app_config import _AppConfig
from marimo._ast.cell import CellConfig, CellImpl
from marimo._ast.compiler import compile_cell
from marimo._ast.names import DEFAULT_CELL_NAME, SETUP_CELL_NAME
diff --git a/marimo/_cli/convert/markdown.py b/marimo/_cli/convert/markdown.py
index d01b3d4dbd..f5851d783a 100644
--- a/marimo/_cli/convert/markdown.py
+++ b/marimo/_cli/convert/markdown.py
@@ -24,7 +24,8 @@ from pymdownx.superfences import ( # type: ignore
from marimo import _loggers
from marimo._ast import codegen
-from marimo._ast.app import App, InternalApp, _AppConfig
+from marimo._ast.app import App, InternalApp
+from marimo._ast.app_config import _AppConfig
from marimo._ast.cell import Cell, CellConfig
from marimo._ast.compiler import compile_cell
from marimo._ast.names import DEFAULT_CELL_NAME
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index 19493c57c8..df683e273d 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -124,7 +124,6 @@ def _generate_server_api_schema() -> dict[str, Any]:
# dataclass components used in requests/responses
REQUEST_RESPONSES = [
# Sub components
- requests.AppMetadata,
home.MarimoFile,
files.FileInfo,
requests.ExecutionRequest,
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index 9b68cb67cf..1511c12728 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -142,6 +142,7 @@ class RuntimeConfig(TypedDict):
# normal == compact
WidthType = Literal["normal", "compact", "medium", "full", "columns"]
Theme = Literal["light", "dark", "system"]
+SqlOutputType = Literal["polars", "lazy-polars", "pandas", "native", "auto"]
@mddoc
diff --git a/marimo/_convert/utils.py b/marimo/_convert/utils.py
index 57da16a0ae..a561be5dac 100644
--- a/marimo/_convert/utils.py
+++ b/marimo/_convert/utils.py
@@ -4,7 +4,7 @@ from __future__ import annotations
from typing import Optional
from marimo._ast import codegen
-from marimo._ast.app import _AppConfig
+from marimo._ast.app_config import _AppConfig
from marimo._ast.cell import CellConfig
from marimo._ast.names import DEFAULT_CELL_NAME
diff --git a/marimo/_islands/_island_generator.py b/marimo/_islands/_island_generator.py
index 3de241a800..5a37cdb37d 100644
--- a/marimo/_islands/_island_generator.py
+++ b/marimo/_islands/_island_generator.py
@@ -8,7 +8,8 @@ from textwrap import dedent
from typing import TYPE_CHECKING, Optional, Union, cast
from marimo import __version__, _loggers
-from marimo._ast.app import App, InternalApp, _AppConfig
+from marimo._ast.app import App, InternalApp
+from marimo._ast.app_config import _AppConfig
from marimo._ast.cell import Cell, CellConfig
from marimo._ast.compiler import compile_cell
from marimo._messaging.cell_output import CellOutput
diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.py
index 6d3cf579e7..000cafde8d 100644
--- a/marimo/_messaging/ops.py
+++ b/marimo/_messaging/ops.py
@@ -23,7 +23,7 @@ from typing import (
from uuid import uuid4
from marimo import _loggers as loggers
-from marimo._ast.app import _AppConfig
+from marimo._ast.app_config import _AppConfig
from marimo._ast.cell import CellConfig, RuntimeStateType
from marimo._ast.toplevel import TopLevelHints, TopLevelStatus
from marimo._data.models import (
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index 89bf77a49f..961cba629b 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -14,8 +14,7 @@ from typing import (
cast,
)
-import narwhals.stable.v1 as nw
-from narwhals.typing import IntoDataFrame, IntoLazyFrame
+from narwhals.typing import IntoDataFrame
import marimo._output.data.data as mo_data
from marimo import _loggers
@@ -51,11 +50,16 @@ from marimo._plugins.validators import (
validate_page_size,
)
from marimo._runtime.functions import EmptyArgs, Function
-from marimo._utils.narwhals_utils import unwrap_narwhals_dataframe
+from marimo._utils.narwhals_utils import (
+ can_narwhalify_lazyframe,
+ unwrap_narwhals_dataframe,
+)
if TYPE_CHECKING:
from collections.abc import Sequence
+ from narwhals.typing import IntoLazyFrame
+
LOGGER = _loggers.marimo_logger()
@@ -270,7 +274,7 @@ class table(
_name: Final[str] = "marimo-table"
@staticmethod
- def lazy(data: IntoLazyFrame) -> table:
+ def lazy(data: IntoLazyFrame, *, preload: bool = False) -> table:
"""
Create a table from a Polars LazyFrame.
@@ -278,10 +282,18 @@ class table(
Once requested, only the first 10 rows will be loaded.
Pagination and selection are not supported for lazy tables.
+
+ Args:
+ data (IntoLazyFrame): The data to display.
+ preload (bool, optional): Whether to load the first page of data
+ without user confirmation. Defaults to False.
"""
- if not nw.dependencies.is_polars_lazyframe(data):
- raise ValueError("data must be a Polars LazyFrame")
+ if not can_narwhalify_lazyframe(data):
+ raise ValueError(
+ "data must be a Polars LazyFrame or DuckDBRelation. Got: "
+ + type(data).__name__
+ )
return table(
data=data,
@@ -304,6 +316,7 @@ class table(
_internal_summary_row_limit=None,
_internal_total_rows="too_many",
_internal_lazy=True,
+ _internal_preload=preload,
)
def __init__(
@@ -358,6 +371,7 @@ class table(
_internal_summary_row_limit: Optional[int] = None,
_internal_total_rows: Optional[Union[int, Literal["too_many"]]] = None,
_internal_lazy: bool = False,
+ _internal_preload: bool = False,
) -> None:
validate_no_integer_columns(data)
validate_page_size(page_size)
@@ -551,6 +565,7 @@ class table(
"has-stable-row-id": self._has_stable_row_id,
"cell-styles": search_result_styles,
"lazy": _internal_lazy,
+ "preload": _internal_preload,
},
on_change=on_change,
functions=(
diff --git a/marimo/_pyodide/bootstrap.py b/marimo/_pyodide/bootstrap.py
index 57eb4b1022..8ca98e8429 100644
--- a/marimo/_pyodide/bootstrap.py
+++ b/marimo/_pyodide/bootstrap.py
@@ -126,6 +126,7 @@ def create_session(
filename=filename,
cli_args={},
argv=[""],
+ app_config=app.config,
),
user_config,
)
diff --git a/marimo/_runtime/app/kernel_runner.py b/marimo/_runtime/app/kernel_runner.py
index f97f672045..35889ea5e6 100644
--- a/marimo/_runtime/app/kernel_runner.py
+++ b/marimo/_runtime/app/kernel_runner.py
@@ -68,7 +68,11 @@ class AppKernelRunner:
self._kernel = Kernel(
cell_configs={},
app_metadata=AppMetadata(
- {}, ctx.cli_args.to_dict(), argv=ctx.argv, filename=filename
+ {},
+ ctx.cli_args.to_dict(),
+ argv=ctx.argv,
+ filename=filename,
+ app_config=app.config,
),
stream=ctx.stream,
stdout=None,
diff --git a/marimo/_runtime/context/kernel_context.py b/marimo/_runtime/context/kernel_context.py
index 8995e1d03f..dac7683c41 100644
--- a/marimo/_runtime/context/kernel_context.py
+++ b/marimo/_runtime/context/kernel_context.py
@@ -171,6 +171,7 @@ def create_kernel_context(
children=[],
parent=parent,
filename=kernel.app_metadata.filename,
+ app_config=kernel.app_metadata.app_config,
)
diff --git a/marimo/_runtime/context/script_context.py b/marimo/_runtime/context/script_context.py
index cb4ad2a833..1abbe7c852 100644
--- a/marimo/_runtime/context/script_context.py
+++ b/marimo/_runtime/context/script_context.py
@@ -160,5 +160,6 @@ def initialize_script_context(
children=[],
parent=None,
filename=filename,
+ app_config=app.config,
)
initialize_context(runtime_context=runtime_context)
diff --git a/marimo/_runtime/context/types.py b/marimo/_runtime/context/types.py
index 11fae46d98..90296001e5 100644
--- a/marimo/_runtime/context/types.py
+++ b/marimo/_runtime/context/types.py
@@ -12,22 +12,25 @@ from contextlib import contextmanager
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Optional
-from marimo._config.config import MarimoConfig
+from marimo._ast.app_config import _AppConfig
from marimo._messaging.context import HTTP_REQUEST_CTX
-from marimo._messaging.types import Stderr, Stdout
-from marimo._runtime import dataflow
-from marimo._runtime.cell_lifecycle_registry import CellLifecycleRegistry
-from marimo._runtime.functions import FunctionRegistry
-from marimo._runtime.requests import HTTPRequest
if TYPE_CHECKING:
from collections.abc import Iterator
- from marimo._ast.app import AppKernelRunnerRegistry, InternalApp
- from marimo._messaging.types import Stream
+ from marimo._ast.app import (
+ AppKernelRunnerRegistry,
+ InternalApp,
+ )
+ from marimo._config.config import MarimoConfig
+ from marimo._messaging.types import Stderr, Stdout, Stream
from marimo._output.hypertext import Html
from marimo._plugins.ui._core.registry import UIElementRegistry
+ from marimo._runtime import dataflow
+ from marimo._runtime.cell_lifecycle_registry import CellLifecycleRegistry
+ from marimo._runtime.functions import FunctionRegistry
from marimo._runtime.params import CLIArgs, QueryParams
+ from marimo._runtime.requests import HTTPRequest
from marimo._runtime.state import State, StateRegistry
from marimo._runtime.virtual_file import VirtualFileRegistry
from marimo._save.stores import Store
@@ -83,6 +86,7 @@ class RuntimeContext(abc.ABC):
children: list[RuntimeContext]
parent: RuntimeContext | None
filename: str | None
+ app_config: _AppConfig
@property
@abc.abstractmethod
diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.py
index b33a97d0bd..274142870c 100644
--- a/marimo/_runtime/requests.py
+++ b/marimo/_runtime/requests.py
@@ -14,6 +14,7 @@ from typing import (
)
from uuid import uuid4
+from marimo._ast.app_config import _AppConfig
from marimo._config.config import MarimoConfig
from marimo._data.models import DataTableSource
from marimo._types.ids import CellId_t, RequestId, UIElementId
@@ -22,6 +23,7 @@ if TYPE_CHECKING:
from starlette.datastructures import URL
from starlette.requests import HTTPConnection
+
CompletionRequestId = str
T = TypeVar("T")
@@ -234,6 +236,7 @@ class AppMetadata:
query_params: SerializedQueryParams
cli_args: SerializedCLIArgs
+ app_config: _AppConfig
argv: Union[list[str], None] = None
filename: Optional[str] = None
diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.py
index 1cb5669300..a66cdea71c 100644
--- a/marimo/_server/export/__init__.py
+++ b/marimo/_server/export/__init__.py
@@ -291,6 +291,7 @@ async def run_app_until_completion(
filename=file_manager.path,
cli_args=cli_args,
argv=argv,
+ app_config=file_manager.app.config,
),
app_file_manager=file_manager,
config_manager=config_manager,
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index 9b8f83b524..87f17f457b 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -229,7 +229,7 @@ class Exporter:
def export_as_md(self, file_manager: AppFileManager) -> tuple[str, str]:
import yaml
- from marimo._ast.app import _AppConfig
+ from marimo._ast.app_config import _AppConfig
from marimo._ast.cell import Cell
from marimo._ast.compiler import compile_cell
from marimo._cli.convert.markdown import (
diff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.py
index dd18b4d0a6..bc704a0de0 100644
--- a/marimo/_server/file_manager.py
+++ b/marimo/_server/file_manager.py
@@ -9,7 +9,8 @@ from typing import Any, Optional, Union
from marimo import _loggers
from marimo._ast import codegen
-from marimo._ast.app import App, InternalApp, _AppConfig
+from marimo._ast.app import App, InternalApp
+from marimo._ast.app_config import _AppConfig
from marimo._ast.cell import CellConfig
from marimo._config.config import WidthType
from marimo._runtime.layout.layout import (
diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.py
index b08c2e28d8..b3f9d81899 100644
--- a/marimo/_server/sessions.py
+++ b/marimo/_server/sessions.py
@@ -838,6 +838,7 @@ class SessionManager:
filename=app_file_manager.path,
cli_args=self.cli_args,
argv=self.argv,
+ app_config=app_file_manager.app.config,
),
app_file_manager=app_file_manager,
config_manager=self._config_manager,
diff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.py
index bdbcd49b06..e92c997666 100644
--- a/marimo/_server/templates/templates.py
+++ b/marimo/_server/templates/templates.py
@@ -8,7 +8,7 @@ from textwrap import dedent
from typing import Any, Literal, Optional, Union, cast
from marimo import __version__
-from marimo._ast.app import _AppConfig
+from marimo._ast.app_config import _AppConfig
from marimo._ast.cell import CellConfig
from marimo._config.config import MarimoConfig, PartialMarimoConfig
from marimo._messaging.cell_output import CellOutput
diff --git a/marimo/_sql/engines/duckdb.py b/marimo/_sql/engines/duckdb.py
index fc438fdf10..ea140adc07 100644
--- a/marimo/_sql/engines/duckdb.py
+++ b/marimo/_sql/engines/duckdb.py
@@ -51,6 +51,17 @@ class DuckDBEngine(SQLEngine):
if relation is None:
return None
+ sql_output_format = self.sql_output_format()
+ if sql_output_format == "polars":
+ return relation.pl()
+ if sql_output_format == "lazy-polars":
+ return relation.pl().lazy()
+ if sql_output_format == "native":
+ return relation
+ if sql_output_format == "pandas":
+ return relation.df()
+
+ # Auto
if DependencyManager.polars.has():
import polars as pl
diff --git a/marimo/_sql/engines/sqlalchemy.py b/marimo/_sql/engines/sqlalchemy.py
index 448dda7bab..0aaeaf45fa 100644
--- a/marimo/_sql/engines/sqlalchemy.py
+++ b/marimo/_sql/engines/sqlalchemy.py
@@ -59,17 +59,15 @@ class SQLAlchemyEngine(SQLEngine):
return str(self._engine.dialect.name)
def execute(self, query: str) -> Any:
- # Can't use polars.imported() because this is the first time we
- # might come across polars.
- if not (
- DependencyManager.polars.has() or DependencyManager.pandas.has()
- ):
- raise_df_import_error("polars[pyarrow]")
+ sql_output_format = self.sql_output_format()
from sqlalchemy import text
with self._engine.connect() as connection:
result = connection.execute(text(query))
+ if sql_output_format == "native":
+ return result
+
rows = result.fetchall() if result.returns_rows else None
try:
@@ -80,6 +78,21 @@ class SQLAlchemyEngine(SQLEngine):
if rows is None:
return None
+ if sql_output_format == "polars":
+ import polars as pl
+
+ return pl.DataFrame(rows) # type: ignore
+ if sql_output_format == "lazy-polars":
+ import polars as pl
+
+ return pl.DataFrame(rows).lazy() # type: ignore
+ if sql_output_format == "pandas":
+ import pandas as pd
+
+ return pd.DataFrame(rows)
+
+ # Auto
+
if DependencyManager.polars.has():
import polars as pl
@@ -102,6 +115,8 @@ class SQLAlchemyEngine(SQLEngine):
LOGGER.warning("Failed to convert dataframe", exc_info=e)
return None
+ raise_df_import_error("polars[pyarrow]")
+
@staticmethod
def is_compatible(var: Any) -> bool:
if not DependencyManager.sqlalchemy.imported():
diff --git a/marimo/_sql/engines/types.py b/marimo/_sql/engines/types.py
index 28e55338ae..ffea18e1ac 100644
--- a/marimo/_sql/engines/types.py
+++ b/marimo/_sql/engines/types.py
@@ -5,7 +5,14 @@ from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, Literal, Optional, Union
+from marimo._config.config import SqlOutputType
from marimo._data.models import Database, DataTable
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._runtime.context.types import (
+ ContextNotInitializedError,
+ get_context,
+ runtime_context_installed,
+)
ENGINE_REGISTRY: list[type[SQLEngine]] = []
@@ -17,16 +24,39 @@ def register_engine(cls: type[SQLEngine]) -> type[SQLEngine]:
@dataclass
class InferenceConfig(ABC):
- auto_discover_schemas: Union[bool | Literal["auto"]]
- auto_discover_tables: Union[bool | Literal["auto"]]
- auto_discover_columns: Union[bool | Literal["auto"]]
+ auto_discover_schemas: Union[bool, Literal["auto"]]
+ auto_discover_tables: Union[bool, Literal["auto"]]
+ auto_discover_columns: Union[bool, Literal["auto"]]
+
+
+def _validate_sql_output_format(sql_output: SqlOutputType) -> SqlOutputType:
+ if sql_output in ("lazy-polars", "polars"):
+ DependencyManager.polars.require(
+ why="to display SQL results as a Polars DataFrame"
+ )
+ elif sql_output == "pandas":
+ DependencyManager.pandas.require(
+ why="to display SQL results as a Pandas DataFrame"
+ )
+ return sql_output
class SQLEngine(ABC):
"""Protocol for SQL engines that can execute queries."""
+ def sql_output_format(self) -> SqlOutputType:
+ if runtime_context_installed():
+ try:
+ ctx = get_context()
+ return _validate_sql_output_format(ctx.app_config.sql_output)
+ except ContextNotInitializedError:
+ return "auto"
+ return "auto"
+
@abstractmethod
- def __init__(self, connection: Any, engine_name: str) -> None:
+ def __init__(
+ self, connection: Any, engine_name: Optional[str] = None
+ ) -> None:
pass
@property
diff --git a/marimo/_sql/sql.py b/marimo/_sql/sql.py
index 4d9efffc82..7146f78fac 100644
--- a/marimo/_sql/sql.py
+++ b/marimo/_sql/sql.py
@@ -10,6 +10,7 @@ from marimo._runtime.output import replace
from marimo._sql.engines.duckdb import DuckDBEngine
from marimo._sql.engines.types import ENGINE_REGISTRY
from marimo._sql.utils import raise_df_import_error
+from marimo._utils.narwhals_utils import can_narwhalify_lazyframe
def get_default_result_limit() -> Optional[int]:
@@ -23,6 +24,8 @@ if TYPE_CHECKING:
from duckdb import DuckDBPyConnection
from sqlalchemy.engine import Engine as SAEngine
+DEFAULT_PAGE_SIZE = 10
+
@mddoc
def sql(
@@ -108,13 +111,19 @@ def sql(
if output:
from marimo._plugins.ui._impl import table
- t = table.table(
- df,
- selection=None,
- page_size=5,
- pagination=True,
- _internal_total_rows=custom_total_count,
- )
+ if can_narwhalify_lazyframe(df):
+ # For pl.LazyFrame and DuckDBRelation, we only show the first few rows
+ # to avoid loading all the data into memory.
+ # Also preload the first page of data without user confirmation.
+ t = table.table.lazy(df, preload=True)
+ else:
+ t = table.table(
+ df,
+ selection=None,
+ page_size=DEFAULT_PAGE_SIZE,
+ pagination=True,
+ _internal_total_rows=custom_total_count,
+ )
replace(t)
return df
diff --git a/marimo/_utils/narwhals_utils.py b/marimo/_utils/narwhals_utils.py
index c5ef471e5b..5554c1f2a3 100644
--- a/marimo/_utils/narwhals_utils.py
+++ b/marimo/_utils/narwhals_utils.py
@@ -7,6 +7,8 @@ from typing import TYPE_CHECKING, Any
import narwhals.dtypes as nw_dtypes
import narwhals.stable.v1 as nw
+from marimo._dependencies.dependencies import DependencyManager
+
if sys.version_info < (3, 11):
from typing_extensions import TypeGuard
else:
@@ -148,3 +150,20 @@ def unwrap_py_scalar(value: Any) -> Any:
return nw.to_py_scalar(value)
except ValueError:
return value
+
+
+def can_narwhalify_lazyframe(df: Any) -> TypeGuard[Any]:
+ """
+ Check if the given object is a narwhals lazyframe.
+ """
+ if nw.dependencies.is_polars_lazyframe(df):
+ return True
+ if hasattr(nw.dependencies, "is_duckdb_relation"):
+ if nw.dependencies.is_duckdb_relation(df):
+ return True
+ elif DependencyManager.duckdb.has():
+ # Fallback if is_duckdb_relation is not available
+ import duckdb
+
+ return isinstance(df, duckdb.DuckDBPyRelation)
+ return False
diff --git a/openapi/api.yaml b/openapi/api.yaml
index 99a3f301f7..8af1812bbd 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -86,43 +86,6 @@ components:
- description
- name
type: object
- AppMetadata:
- properties:
- argv:
- items:
- type: string
- nullable: true
- type: array
- cliArgs:
- additionalProperties:
- oneOf:
- - type: string
- - type: boolean
- - type: integer
- - type: number
- - items:
- oneOf:
- - type: string
- - type: boolean
- - type: integer
- - type: number
- type: array
- type: object
- filename:
- nullable: true
- type: string
- queryParams:
- additionalProperties:
- oneOf:
- - type: string
- - items:
- type: string
- type: array
- type: object
- required:
- - queryParams
- - cliArgs
- type: object
Banner:
properties:
action:
@@ -1161,6 +1124,14 @@ components:
layout_file:
nullable: true
type: string
+ sql_output:
+ enum:
+ - polars
+ - lazy-polars
+ - pandas
+ - native
+ - auto
+ type: string
width:
enum:
- normal
@@ -1172,6 +1143,7 @@ components:
required:
- width
- auto_download
+ - sql_output
- _toplevel_fn
type: object
capabilities:
@@ -2528,7 +2500,7 @@ components:
type: object
info:
title: marimo API
- version: 0.12.5
+ version: 0.12.6
openapi: 3.1.0
paths:
/@file/{filename_and_length}:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index bf9846739b..906527039d 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -2363,20 +2363,6 @@ export interface components {
/** @enum {string|null} */
variant?: "danger" | null;
};
- AppMetadata: {
- argv?: string[] | null;
- cliArgs: {
- [key: string]:
- | string
- | boolean
- | number
- | (string | boolean | number)[];
- };
- filename?: string | null;
- queryParams: {
- [key: string]: string | string[];
- };
- };
Banner: {
/** @enum {string|null} */
action?: "restart" | null;
@@ -2801,6 +2787,8 @@ export interface components {
html_head_file?: string | null;
layout_file?: string | null;
/** @enum {string} */
+ sql_output: "polars" | "lazy-polars" | "pandas" | "native" | "auto";
+ /** @enum {string} */
width: "normal" | "compact" | "medium" | "full" | "columns";
};
capabilities: {
diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.py
index 70825e28be..db0c0e5be1 100644
--- a/tests/_ast/test_app.py
+++ b/tests/_ast/test_app.py
@@ -8,10 +8,10 @@ from typing import Any, TYPE_CHECKING
import pytest
+from marimo._ast.app_config import _AppConfig
from marimo._ast.app import (
App,
AppKernelRunnerRegistry,
- _AppConfig,
InternalApp,
)
from marimo._ast.errors import (
@@ -363,6 +363,7 @@ class TestApp:
"width": "full",
"layout_file": None,
"auto_download": [],
+ "sql_output": "auto",
}
@staticmethod
@@ -692,6 +693,7 @@ def test_app_config() -> None:
"width": "full",
"layout_file": None,
"auto_download": [],
+ "sql_output": "auto",
}
@@ -708,6 +710,7 @@ def test_app_config_extra_args_ignored() -> None:
"width": "full",
"layout_file": None,
"auto_download": [],
+ "sql_output": "auto",
}
diff --git a/tests/_ast/test_app_config.py b/tests/_ast/test_app_config.py
index 03326f81d3..723bc92644 100644
--- a/tests/_ast/test_app_config.py
+++ b/tests/_ast/test_app_config.py
@@ -4,7 +4,7 @@ from typing import Any
import pytest
-from marimo._ast.app import _AppConfig
+from marimo._ast.app_config import _AppConfig
def test_app_config_default():
@@ -14,6 +14,7 @@ def test_app_config_default():
assert config.css_file is None
assert config.html_head_file is None
assert config.auto_download == []
+ assert config.sql_output == "auto"
def test_app_config_from_untrusted_dict():
@@ -24,6 +25,7 @@ def test_app_config_from_untrusted_dict():
"html_head_file": "head.html",
"auto_download": ["html", "markdown"],
"invalid_key": "should be ignored",
+ "sql_output": "polars",
}
config = _AppConfig.from_untrusted_dict(updates)
assert config.width == "full"
@@ -31,6 +33,7 @@ def test_app_config_from_untrusted_dict():
assert config.css_file == "custom.css"
assert config.html_head_file == "head.html"
assert config.auto_download == ["html", "markdown"]
+ assert config.sql_output == "polars"
assert not hasattr(config, "invalid_key")
@@ -41,6 +44,7 @@ def test_app_config_asdict():
css_file="style.css",
html_head_file="head.html",
auto_download=["html"],
+ sql_output="lazy-polars",
)
config_dict = config.asdict()
assert config_dict == {
@@ -50,21 +54,32 @@ def test_app_config_asdict():
"html_head_file": "head.html",
"auto_download": ["html"],
"layout_file": None,
+ "sql_output": "lazy-polars",
}
def test_app_config_update():
config = _AppConfig()
- updates = {
- "width": "full",
- "app_title": "Updated App",
- "auto_download": ["markdown"],
- }
- updated_config = config.update(updates)
+ assert config.width == "compact"
+ assert config.app_title is None
+ assert config.sql_output == "auto"
+
+ updated_config = config.update(
+ {
+ "width": "full",
+ "app_title": "Test App",
+ "sql_output": "lazy-polars",
+ }
+ )
+ assert updated_config.width == "full"
+ assert updated_config.app_title == "Test App"
+ assert updated_config.sql_output == "lazy-polars"
+
+ # Test updating a single field
+ updated_config = config.update({"app_title": "Updated App"})
assert updated_config.width == "full"
assert updated_config.app_title == "Updated App"
- assert updated_config.auto_download == ["markdown"]
- assert updated_config.css_file is None
+ assert updated_config.sql_output == "lazy-polars"
@pytest.mark.parametrize(
diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.py
index 4fbee9d06e..cd3bc0b863 100644
--- a/tests/_ast/test_codegen.py
+++ b/tests/_ast/test_codegen.py
@@ -14,7 +14,8 @@ import pytest
from marimo import __version__
from marimo._ast import codegen, compiler
-from marimo._ast.app import App, InternalApp, _AppConfig
+from marimo._ast.app import App, InternalApp
+from marimo._ast.app_config import _AppConfig
from marimo._ast.cell import CellConfig
from marimo._ast.names import is_internal_cell_name
diff --git a/tests/_islands/test_island_generator.py b/tests/_islands/test_island_generator.py
index c873889f31..1a31193bca 100644
--- a/tests/_islands/test_island_generator.py
+++ b/tests/_islands/test_island_generator.py
@@ -5,7 +5,7 @@ from typing import TYPE_CHECKING
import pytest
from marimo import __version__
-from marimo._ast.app import _AppConfig
+from marimo._ast.app_config import _AppConfig
from marimo._islands._island_generator import (
MarimoIslandGenerator,
)
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index cad261bb76..8a71ab88ac 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING
import pytest
+from marimo._ast.app_config import _AppConfig
from marimo._config.config import DEFAULT_CONFIG
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.cell_output import CellChannel
@@ -1159,6 +1160,7 @@ class TestExecution:
filename=filename,
cli_args={},
argv=None,
+ app_config=_AppConfig(),
),
enqueue_control_request=lambda _: None,
module=create_main_module(None, None, None),
@@ -1223,6 +1225,7 @@ class TestExecution:
filename=filename,
cli_args={},
argv=None,
+ app_config=_AppConfig(),
),
enqueue_control_request=lambda _: None,
module=create_main_module(None, None, None),
@@ -1249,6 +1252,7 @@ class TestExecution:
filename=filename,
cli_args={},
argv=["foo", "bar"],
+ app_config=_AppConfig(),
),
enqueue_control_request=lambda _: None,
module=create_main_module(None, None, None),
@@ -1281,6 +1285,7 @@ class TestExecution:
filename=filename,
cli_args={},
argv=None,
+ app_config=_AppConfig(),
),
enqueue_control_request=lambda _: None,
module=create_main_module(None, None, None),
@@ -1317,6 +1322,7 @@ class TestExecution:
filename=str(filename),
cli_args={},
argv=None,
+ app_config=_AppConfig(),
),
enqueue_control_request=lambda _: None,
module=create_main_module(None, None, None),
diff --git a/tests/_server/templates/snapshots/export1.txt b/tests/_server/templates/snapshots/export1.txt
index 6893ca2695..b0e1c797c4 100644
--- a/tests/_server/templates/snapshots/export1.txt
+++ b/tests/_server/templates/snapshots/export1.txt
@@ -56,7 +56,7 @@
<marimo-mode data-mode='read' hidden></marimo-mode>
<marimo-version data-version='0.0.0' hidden></marimo-version>
<marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>
- <marimo-app-config data-config='{"width": "compact"}' hidden></marimo-app-config>
+ <marimo-app-config data-config='{"sql_output": "auto", "width": "compact"}' hidden></marimo-app-config>
<marimo-server-token data-token='token' hidden></marimo-server-token>
<title>notebook</title>
<script type="module" crossorigin crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.js""></script>
diff --git a/tests/_server/templates/snapshots/export2.txt b/tests/_server/templates/snapshots/export2.txt
index 379ab51a1f..a0c7e2a0f6 100644
--- a/tests/_server/templates/snapshots/export2.txt
+++ b/tests/_server/templates/snapshots/export2.txt
@@ -56,7 +56,7 @@
<marimo-mode data-mode='read' hidden></marimo-mode>
<marimo-version data-version='0.0.0' hidden></marimo-version>
<marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>
- <marimo-app-config data-config='{"width": "compact"}' hidden></marimo-app-config>
+ <marimo-app-config data-config='{"sql_output": "auto", "width": "compact"}' hidden></marimo-app-config>
<marimo-server-token data-token='token' hidden></marimo-server-token>
<title>marimo</title>
<script type="module" crossorigin crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.js""></script>
diff --git a/tests/_server/templates/snapshots/export3.txt b/tests/_server/templates/snapshots/export3.txt
index c3536f9238..6a49730f1f 100644
--- a/tests/_server/templates/snapshots/export3.txt
+++ b/tests/_server/templates/snapshots/export3.txt
@@ -56,7 +56,7 @@
<marimo-mode data-mode='read' hidden></marimo-mode>
<marimo-version data-version='0.0.0' hidden></marimo-version>
<marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>
- <marimo-app-config data-config='{"width": "compact"}' hidden></marimo-app-config>
+ <marimo-app-config data-config='{"sql_output": "auto", "width": "compact"}' hidden></marimo-app-config>
<marimo-server-token data-token='token' hidden></marimo-server-token>
<title>notebook</title>
<script type="module" crossorigin crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.js""></script>
diff --git a/tests/_server/templates/snapshots/export4.txt b/tests/_server/templates/snapshots/export4.txt
index dd07d607ce..3b94cdfc3f 100644
--- a/tests/_server/templates/snapshots/export4.txt
+++ b/tests/_server/templates/snapshots/export4.txt
@@ -56,7 +56,7 @@
<marimo-mode data-mode='read' hidden></marimo-mode>
<marimo-version data-version='0.0.0' hidden></marimo-version>
<marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>
- <marimo-app-config data-config='{"css_file": "custom.css", "width": "compact"}' hidden></marimo-app-config>
+ <marimo-app-config data-config='{"css_file": "custom.css", "sql_output": "auto", "width": "compact"}' hidden></marimo-app-config>
<marimo-server-token data-token='token' hidden></marimo-server-token>
<title>notebook</title>
<script type="module" crossorigin crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.js""></script>
diff --git a/tests/_server/templates/snapshots/export5.txt b/tests/_server/templates/snapshots/export5.txt
index 762fcd0270..38027d39f3 100644
--- a/tests/_server/templates/snapshots/export5.txt
+++ b/tests/_server/templates/snapshots/export5.txt
@@ -56,7 +56,7 @@
<marimo-mode data-mode='read' hidden></marimo-mode>
<marimo-version data-version='0.0.0' hidden></marimo-version>
<marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>
- <marimo-app-config data-config='{"app_title": "My App", "html_head_file": "head.html", "width": "compact"}' hidden></marimo-app-config>
+ <marimo-app-config data-config='{"app_title": "My App", "html_head_file": "head.html", "sql_output": "auto", "width": "compact"}' hidden></marimo-app-config>
<marimo-server-token data-token='token' hidden></marimo-server-token>
<title>My App</title>
<script type="module" crossorigin crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.js""></script>
diff --git a/tests/_server/templates/snapshots/export6.txt b/tests/_server/templates/snapshots/export6.txt
index ff589a8ec3..9e6c0573b9 100644
--- a/tests/_server/templates/snapshots/export6.txt
+++ b/tests/_server/templates/snapshots/export6.txt
@@ -56,7 +56,7 @@
<marimo-mode data-mode='read' hidden></marimo-mode>
<marimo-version data-version='0.0.0' hidden></marimo-version>
<marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "custom_css": ["custom1.css", "custom2.css"], "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>
- <marimo-app-config data-config='{"width": "compact"}' hidden></marimo-app-config>
+ <marimo-app-config data-config='{"sql_output": "auto", "width": "compact"}' hidden></marimo-app-config>
<marimo-server-token data-token='token' hidden></marimo-server-token>
<title>notebook</title>
<script type="module" crossorigin crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.js""></script>
diff --git a/tests/_server/templates/test_templates.py b/tests/_server/templates/test_templates.py
index 92a1ac984d..d75983650c 100644
--- a/tests/_server/templates/test_templates.py
+++ b/tests/_server/templates/test_templates.py
@@ -7,7 +7,7 @@ import unittest
from pathlib import Path
from typing import Literal
-from marimo._ast.app import _AppConfig
+from marimo._ast.app_config import _AppConfig
from marimo._ast.cell import CellConfig
from marimo._config.config import (
MarimoConfig,
diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.py
index 6887c25101..b5df1b4c4d 100644
--- a/tests/_server/test_sessions.py
+++ b/tests/_server/test_sessions.py
@@ -18,6 +18,7 @@ from unittest.mock import MagicMock
import pytest
from marimo._ast.app import App, InternalApp
+from marimo._ast.app_config import _AppConfig
from marimo._config.manager import (
get_default_config_manager,
)
@@ -52,6 +53,7 @@ app_metadata = AppMetadata(
filename="test.py",
cli_args={},
argv=None,
+ app_config=_AppConfig(),
)
@@ -320,7 +322,9 @@ def test_session_disconnect_reconnect() -> None:
queue_manager,
SessionMode.RUN,
{},
- AppMetadata(query_params={}, cli_args={}, argv=None),
+ AppMetadata(
+ query_params={}, cli_args={}, argv=None, app_config=_AppConfig()
+ ),
get_default_config_manager(current_path=None),
virtual_files_supported=True,
redirect_console_to_browser=False,
diff --git a/tests/_sql/test_duckdb.py b/tests/_sql/test_duckdb.py
index a563575e16..ca586113c1 100644
--- a/tests/_sql/test_duckdb.py
+++ b/tests/_sql/test_duckdb.py
@@ -11,6 +11,7 @@ from marimo._data.models import Database, DataTable, DataTableColumn, Schema
from marimo._dependencies.dependencies import DependencyManager
from marimo._sql.engines.duckdb import DuckDBEngine
from marimo._sql.sql import sql
+from marimo._types.ids import VariableName
HAS_DUCKDB = DependencyManager.duckdb.has()
HAS_PANDAS = DependencyManager.pandas.has()
@@ -54,7 +55,7 @@ def duckdb_connection() -> Generator[duckdb.DuckDBPyConnection, None, None]:
@pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")
def test_duckdb_engine_dialect() -> None:
"""Test DuckDBEngine dialect property."""
- engine = DuckDBEngine(None)
+ engine = DuckDBEngine(None, engine_name=None)
assert engine.dialect == "duckdb"
@@ -69,7 +70,7 @@ def test_duckdb_engine_execute(
import polars as pl
# Test with explicit connection
- engine = DuckDBEngine(duckdb_connection)
+ engine = DuckDBEngine(duckdb_connection, engine_name=None)
result = engine.execute("SELECT * FROM test ORDER BY id")
assert isinstance(result, (pd.DataFrame, pl.DataFrame))
assert len(result) == 4
@@ -79,7 +80,7 @@ expected_databases_with_conn = [
Database(
name="memory",
dialect="duckdb",
- engine="test_duckdb",
+ engine=VariableName("test_duckdb"),
schemas=[
Schema(
name="main",
@@ -91,7 +92,7 @@ expected_databases_with_conn = [
num_rows=None,
num_columns=2,
variable_name=None,
- engine="test_duckdb",
+ engine=VariableName("test_duckdb"),
columns=[
DataTableColumn(
name="id",
@@ -120,7 +121,9 @@ def test_duckdb_engine_get_databases(
) -> None:
"""Test DuckDBEngine get_databases method."""
- engine = DuckDBEngine(duckdb_connection, engine_name="test_duckdb")
+ engine = DuckDBEngine(
+ duckdb_connection, engine_name=VariableName("test_duckdb")
+ )
databases = engine.get_databases(
include_schemas=True, include_tables=True, include_table_details=True
)
@@ -131,7 +134,7 @@ def test_duckdb_engine_get_databases(
@pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")
def test_duckdb_engine_get_databases_no_conn() -> None:
"""Test DuckDBEngine get_databases method."""
- engine = DuckDBEngine()
+ engine = DuckDBEngine(None, engine_name=None)
initial_databases = engine.get_databases(
include_schemas=False,
include_table_details=False,
@@ -172,7 +175,9 @@ def test_get_current_database_schema() -> None:
import duckdb
engine = duckdb.connect(":memory:")
- duckdb_engine = DuckDBEngine(engine)
+ duckdb_engine = DuckDBEngine(
+ engine, engine_name=VariableName("test_duckdb")
+ )
assert duckdb_engine.get_default_database() == "memory"
assert duckdb_engine.get_default_schema() == "main"
@@ -195,9 +200,81 @@ def test_get_current_database_schema() -> None:
def test_duckdb_engine_execute_polars_fallback() -> None:
import pandas as pd
- engine = DuckDBEngine(None)
+ engine = DuckDBEngine(None, engine_name=VariableName("test_duckdb"))
# This dtype is currently not supported by polars
result = engine.execute(
"select to_days(cast((current_date - DATE '2025-01-01') as INTEGER));"
)
assert isinstance(result, pd.DataFrame)
+
+
+ not HAS_DUCKDB or not HAS_POLARS or not HAS_PANDAS,
+ reason="DuckDB, Polars, and Pandas not installed",
+)
+def test_duckdb_engine_sql_output_formats(
+ duckdb_connection: duckdb.DuckDBPyConnection,
+) -> None:
+ """Test DuckDBEngine execute with different SQL output formats."""
+ from unittest import mock
+
+ import pandas as pd
+ import polars as pl
+
+ # Test with polars output format
+ with mock.patch.object(
+ DuckDBEngine, "sql_output_format", return_value="polars"
+ ):
+ engine = DuckDBEngine(
+ duckdb_connection, engine_name=VariableName("test_duckdb")
+ )
+ result = engine.execute("SELECT * FROM test ORDER BY id")
+ assert isinstance(result, pl.DataFrame)
+ assert len(result) == 4
+
+ # Test with lazy-polars output format
+ with mock.patch.object(
+ DuckDBEngine, "sql_output_format", return_value="lazy-polars"
+ ):
+ engine = DuckDBEngine(
+ duckdb_connection, engine_name=VariableName("test_duckdb")
+ )
+ result = engine.execute("SELECT * FROM test ORDER BY id")
+ assert isinstance(result, pl.LazyFrame)
+ assert len(result.collect()) == 4
+
+ # Test with pandas output format
+ with mock.patch.object(
+ DuckDBEngine, "sql_output_format", return_value="pandas"
+ ):
+ engine = DuckDBEngine(
+ duckdb_connection, engine_name=VariableName("test_duckdb")
+ )
+ result = engine.execute("SELECT * FROM test ORDER BY id")
+ assert isinstance(result, pd.DataFrame)
+ assert len(result) == 4
+
+ # Test with native output format
+ with mock.patch.object(
+ DuckDBEngine, "sql_output_format", return_value="native"
+ ):
+ engine = DuckDBEngine(
+ duckdb_connection, engine_name=VariableName("test_duckdb")
+ )
+ result = engine.execute("SELECT * FROM test ORDER BY id")
+ assert not isinstance(
+ result, (pd.DataFrame, pl.DataFrame, pl.LazyFrame)
+ )
+ # DuckDB native result has a different interface than SQLAlchemy
+ assert hasattr(result, "fetchall") or hasattr(result, "fetch_df")
+
+ # Test with auto output format (should use polars if available)
+ with mock.patch.object(
+ DuckDBEngine, "sql_output_format", return_value="auto"
+ ):
+ engine = DuckDBEngine(
+ duckdb_connection, engine_name=VariableName("test_duckdb")
+ )
+ result = engine.execute("SELECT * FROM test ORDER BY id")
+ assert isinstance(result, (pd.DataFrame, pl.DataFrame))
+ assert len(result) == 4
diff --git a/tests/_sql/test_sqlalchemy.py b/tests/_sql/test_sqlalchemy.py
index 9cc95329f7..b4038bde3a 100644
--- a/tests/_sql/test_sqlalchemy.py
+++ b/tests/_sql/test_sqlalchemy.py
@@ -109,7 +109,9 @@ def sqlite_engine_meta() -> sa.Engine:
@pytest.mark.skipif(not HAS_SQLALCHEMY, reason="SQLAlchemy not installed")
def test_sqlalchemy_engine_dialect(sqlite_engine: sa.Engine) -> None:
"""Test SQLAlchemyEngine dialect property."""
- engine = SQLAlchemyEngine(sqlite_engine)
+ engine = SQLAlchemyEngine(
+ sqlite_engine, engine_name=VariableName("test_sqlite")
+ )
assert engine.dialect == "sqlite"
@@ -117,7 +119,7 @@ def test_sqlalchemy_engine_dialect(sqlite_engine: sa.Engine) -> None:
def test_sqlalchemy_invalid_engine() -> None:
"""Test SQLAlchemyEngine with an invalid engine and inspector does not raise errors."""
- engine = SQLAlchemyEngine(connection=None) # type: ignore
+ engine = SQLAlchemyEngine(connection=None, engine_name=None) # type: ignore
assert engine.inspector is None
assert engine.default_database is None
assert engine.default_schema is None
@@ -578,7 +580,9 @@ def test_sqlalchemy_engine_execute(sqlite_engine: sa.Engine) -> None:
import pandas as pd
import polars as pl
- engine = SQLAlchemyEngine(sqlite_engine)
+ engine = SQLAlchemyEngine(
+ sqlite_engine, engine_name=VariableName("test_sqlite")
+ )
result = engine.execute("SELECT * FROM test ORDER BY id")
assert isinstance(result, (pd.DataFrame, pl.DataFrame))
assert len(result) == 4
@@ -587,11 +591,86 @@ def test_sqlalchemy_engine_execute(sqlite_engine: sa.Engine) -> None:
@pytest.mark.skipif(not HAS_SQLALCHEMY, reason="SQLAlchemy not installed")
def test_sqlalchemy_get_database_name(sqlite_engine: sa.Engine) -> None:
"""Test SQLAlchemyEngine get_database_name."""
- engine = SQLAlchemyEngine(sqlite_engine)
+ engine = SQLAlchemyEngine(
+ sqlite_engine, engine_name=VariableName("test_sqlite")
+ )
assert engine.get_default_database() == ":memory:"
import sqlalchemy as sa
# Test with no database name
- engine = SQLAlchemyEngine(sa.create_engine("sqlite:///"))
+ engine = SQLAlchemyEngine(
+ sa.create_engine("sqlite:///"), engine_name=VariableName("test_sqlite")
+ )
assert engine.get_default_database() == ""
+
+
+ not HAS_SQLALCHEMY or not HAS_POLARS or not HAS_PANDAS,
+ reason="SQLAlchemy, Polars, and Pandas not installed",
+)
+def test_sqlalchemy_engine_sql_output_formats(
+ sqlite_engine: sa.Engine,
+) -> None:
+ """Test SQLAlchemyEngine execute with different SQL output formats."""
+ from unittest import mock
+
+ import pandas as pd
+ import polars as pl
+
+ # Test with polars output format
+ with mock.patch.object(
+ SQLAlchemyEngine, "sql_output_format", return_value="polars"
+ ):
+ engine = SQLAlchemyEngine(
+ sqlite_engine, engine_name=VariableName("test_sqlite")
+ )
+ result = engine.execute("SELECT * FROM test ORDER BY id")
+ assert isinstance(result, pl.DataFrame)
+ assert len(result) == 4
+
+ # Test with lazy-polars output format
+ with mock.patch.object(
+ SQLAlchemyEngine, "sql_output_format", return_value="lazy-polars"
+ ):
+ engine = SQLAlchemyEngine(
+ sqlite_engine, engine_name=VariableName("test_sqlite")
+ )
+ result = engine.execute("SELECT * FROM test ORDER BY id")
+ assert isinstance(result, pl.LazyFrame)
+ assert len(result.collect()) == 4
+
+ # Test with pandas output format
+ with mock.patch.object(
+ SQLAlchemyEngine, "sql_output_format", return_value="pandas"
+ ):
+ engine = SQLAlchemyEngine(
+ sqlite_engine, engine_name=VariableName("test_sqlite")
+ )
+ result = engine.execute("SELECT * FROM test ORDER BY id")
+ assert isinstance(result, pd.DataFrame)
+ assert len(result) == 4
+
+ # Test with native output format
+ with mock.patch.object(
+ SQLAlchemyEngine, "sql_output_format", return_value="native"
+ ):
+ engine = SQLAlchemyEngine(
+ sqlite_engine, engine_name=VariableName("test_sqlite")
+ )
+ result = engine.execute("SELECT * FROM test ORDER BY id")
+ assert not isinstance(
+ result, (pd.DataFrame, pl.DataFrame, pl.LazyFrame)
+ )
+ assert hasattr(result, "fetchall")
+
+ # Test with auto output format (should use polars if available)
+ with mock.patch.object(
+ SQLAlchemyEngine, "sql_output_format", return_value="auto"
+ ):
+ engine = SQLAlchemyEngine(
+ sqlite_engine, engine_name=VariableName("test_sqlite")
+ )
+ result = engine.execute("SELECT * FROM test ORDER BY id")
+ assert isinstance(result, (pd.DataFrame, pl.DataFrame))
+ assert len(result) == 4
diff --git a/tests/_utils/test_narwhals_utils.py b/tests/_utils/test_narwhals_utils.py
index 89c32572f7..4cab08343c 100644
--- a/tests/_utils/test_narwhals_utils.py
+++ b/tests/_utils/test_narwhals_utils.py
@@ -10,6 +10,7 @@ from marimo._utils.narwhals_utils import (
assert_narwhals_dataframe,
assert_narwhals_series,
can_narwhalify,
+ can_narwhalify_lazyframe,
dataframe_to_csv,
empty_df,
is_narwhals_integer_type,
@@ -123,3 +124,27 @@ def test_unwrap_py_scalar():
# Test non-scalar values are returned as-is
complex_obj = {"a": 1}
assert unwrap_py_scalar(complex_obj) == complex_obj
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_can_narwhalify_lazyframe():
+ import duckdb
+ import polars as pl
+
+ # Test with a LazyFrame
+ lazy_df = pl.DataFrame({"a": [1, 2, 3]}).lazy()
+ assert can_narwhalify_lazyframe(lazy_df) is True
+
+ # Test with a regular DataFrame
+ df = pl.DataFrame({"a": [1, 2, 3]})
+ assert can_narwhalify_lazyframe(df) is False
+
+ # Test with non-polars objects
+ assert can_narwhalify_lazyframe({"a": [1, 2, 3]}) is False
+ assert can_narwhalify_lazyframe([1, 2, 3]) is False
+ assert can_narwhalify_lazyframe(None) is False
+
+ # Test with duckdb relation
+ con = duckdb.connect(":memory:")
+ rel = con.sql("SELECT 1")
+ assert can_narwhalify_lazyframe(rel) is True
diff --git a/tests/conftest.py b/tests/conftest.py
index a38e4b87e4..a8256c1f99 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -14,6 +14,7 @@ import pytest
from _pytest import runner
from marimo._ast.app import App, CellManager
+from marimo._ast.app_config import _AppConfig
from marimo._config.config import DEFAULT_CONFIG
from marimo._messaging.mimetypes import ConsoleMimeType
from marimo._messaging.ops import CellOp, MessageOperation
@@ -167,6 +168,7 @@ class MockedKernel:
filename=None,
cli_args={},
argv=None,
+ app_config=_AppConfig(),
),
debugger_override=MarimoPdb(stdout=self.stdout, stdin=self.stdin),
enqueue_control_request=lambda _: None,