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
improvement: make it possible to auto limit sql queries via environment variable (#1886)
Myles Scolnick621d9087e948
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex 40ccd29109..02b2b6aba1 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -18,11 +18,11 @@ import { ColumnChartContext } from "@/components/data-table/column-summary";import { Logger } from "@/utils/Logger";import { LoadingTable } from "@/components/data-table/loading-table";import { DelayMount } from "@/components/utils/delay-mount";-import {+import type {ColumnHeaderSummary,FieldTypesWithExternalType,} from "@/components/data-table/types";-import {+import type {ColumnFiltersState,OnChangeFn,RowSelectionState,@@ -31,9 +31,9 @@ import {import { TooltipProvider } from "@radix-ui/react-tooltip";import useEvent from "react-use-event-hook";import { Functions } from "@/utils/functions";-import { ConditionSchema, ConditionType } from "./data-frames/schema";+import { ConditionSchema, type ConditionType } from "./data-frames/schema";import {- ColumnFilterValue,+ type ColumnFilterValue,filterToFilterCondition,} from "@/components/data-table/filters";import { Objects } from "@/utils/objects";@@ -51,7 +51,7 @@ interface Data<T> {label: string | null;data: TableData<T>;hasMore: boolean;- totalRows: number;+ totalRows: number | "too_many";pagination: boolean;pageSize: number;selection: "single" | "multi" | null;@@ -87,7 +87,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")label: z.string().nullable(),data: z.union([z.string(), z.array(z.object({}).passthrough())]),hasMore: z.boolean().default(false),- totalRows: z.number(),+ totalRows: z.union([z.number(), z.literal("too_many")]),pagination: z.boolean().default(false),pageSize: z.number().default(10),selection: z.enum(["single", "multi"]).nullable().default(null),@@ -336,7 +336,8 @@ const DataTableComponent = ({data: unknown[];columnSummaries?: ColumnHeaderSummary[];}): JSX.Element => {- const resultsAreClipped = hasMore && totalRows > 0;+ const resultsAreClipped =+ hasMore && (totalRows === "too_many" || totalRows > 0);const chartSpecModel = useMemo(() => {if (!fieldTypes || !data || !columnSummaries) {@@ -397,11 +398,17 @@ const DataTableComponent = ({return (<>- {hasMore && totalRows && (+ {hasMore && typeof totalRows === "number" && (<Banner className="mb-2 rounded">Result clipped. Total rows {prettyNumber(totalRows)}.</Banner>)}+ {/* // HACK: We assume "too_many" is coming from a SQL table */}+ {hasMore && totalRows === "too_many" && (+ <Banner className="mb-2 rounded">+ Result clipped. If no LIMIT is given, we only show the first 300 rows.+ </Banner>+ )}<ColumnChartContext.Provider value={chartSpecModel}><Labeled label={label} align="top" fullWidth={true}><DataTablediff --git a/marimo/__init__.py b/marimo/__init__.pyindex 8aff10cc91..afb98a3f60 100644--- a/marimo/__init__.py+++ b/marimo/__init__.py@@ -112,4 +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 sql+from marimo._sql.sql import sqldiff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.pyindex fa19a3d5c0..3842c1de17 100644--- a/marimo/_plugins/ui/_core/ui_element.py+++ b/marimo/_plugins/ui/_core/ui_element.py@@ -128,6 +128,7 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):raise TypeError("on_change must be a callable or None")# arguments stored in signature order for cloning+ self._component_args = argsself._args = (component_name,initial_value,diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex c510164319..c809c45a68 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -197,7 +197,10 @@ class table(None,]] = None,+ _internal_row_limit: Optional[int] = None,+ _internal_total_rows: Optional[Union[int, Literal["too_many"]]] = None,) -> None:+ # The original data passed inself._data = data# Holds the original dataself._manager = get_table_manager(data)@@ -217,16 +220,24 @@ class table("https://github.com/marimo-team/marimo/issues")- totalRows = self._manager.get_num_rows(force=True) or 0- hasMore = totalRows > TableManager.DEFAULT_ROW_LIMIT- if hasMore:- self._filtered_manager = self._filtered_manager.limit(- TableManager.DEFAULT_ROW_LIMIT+ row_limit = _internal_row_limit or TableManager.DEFAULT_ROW_LIMIT++ total_rows: Union[int, Literal["too_many"]]+ if _internal_total_rows == "too_many":+ total_rows = "too_many"+ else:+ total_rows = (+ _internal_total_rows+ or self._manager.get_num_rows(force=True)+ or 0)+ has_more = total_rows == "too_many" or total_rows > row_limit+ if has_more:+ self._filtered_manager = self._filtered_manager.limit(row_limit)# pagination defaults to True if there are more than 10 rowsif pagination is None:- pagination = totalRows > 10+ pagination = total_rows == "too_many" or total_rows > 10field_types = self._manager.get_field_types()@@ -236,8 +247,8 @@ class table(initial_value=[],args={"data": self._filtered_manager.to_data(),- "has-more": hasMore,- "total-rows": totalRows,+ "has-more": has_more,+ "total-rows": total_rows,"pagination": pagination,"page-size": page_size,"field-types": field_types if field_types else None,diff --git a/marimo/_smoke_tests/sql/limits.py b/marimo/_smoke_tests/sql/limits.pynew file mode 100644index 0000000000..7cf4e605fa--- /dev/null+++ b/marimo/_smoke_tests/sql/limits.py@@ -0,0 +1,137 @@+# Copyright 2024 Marimo. All rights reserved.+import marimo++__generated_with = "0.7.11"+app = marimo.App(width="medium")+++def __():+ import marimo as mo+ return mo,+++def __(mo):+ mo.md(r"""## Small table""")+ return+++def __(mo):+ _df = mo.sql(+ f"""+ CREATE OR REPLACE TABLE small_table AS SELECT * FROM range(1000)+ """+ )+ return+++def __(mo, small_table):+ _df = mo.sql(+ f"""+ SELECT * FROM small_table;+ """+ )+ return+++def __(mo, small_table):+ _df = mo.sql(+ f"""+ SELECT * FROM small_table LIMIT 10;+ """+ )+ return+++def __(mo, small_table):+ _df = mo.sql(+ f"""+ SELECT * FROM small_table LIMIT 1000;+ """+ )+ return+++def __(mo, small_table):+ _df = mo.sql(+ f"""+ SELECT * FROM small_table LIMIT 300;+ """+ )+ return+++def __(mo, small_table):+ _df = mo.sql(+ f"""+ SELECT * FROM small_table LIMIT 301;+ """+ )+ return+++def __(mo, small_table):+ _df = mo.sql(+ f"""+ SELECT * FROM small_table LIMIT 1100;+ """+ )+ return+++def __(mo):+ mo.md(r"""## Large table""")+ return+++def __(mo):+ _df = mo.sql(+ f"""+ CREATE OR REPLACE TABLE large_table AS SELECT * FROM range(30_000);+ """+ )+ return+++def __(large_table, mo):+ _df = mo.sql(+ f"""+ SELECT * FROM large_table;+ """+ )+ return+++def __(large_table, mo):+ _df = mo.sql(+ f"""+ SELECT * FROM large_table LIMIT 25_000;+ """+ )+ return+++def __(large_table, mo):+ _df = mo.sql(+ f"""+ SELECT * FROM large_table LIMIT 20_000;+ """+ )+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_sql/__init__.py b/marimo/_sql/__init__.pydeleted file mode 100644index 00769455d7..0000000000--- a/marimo/_sql/__init__.py+++ /dev/null@@ -1,8 +0,0 @@-# 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.pyindex 5a803e7cc6..80d280b927 100644--- a/marimo/_sql/sql.py+++ b/marimo/_sql/sql.py@@ -1,7 +1,8 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any+import os+from typing import Any, Literal, Optional, castfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._output.rich_help import mddoc@@ -9,8 +10,15 @@ from marimo._plugins.ui._impl import tablefrom marimo._runtime import output+def get_default_result_limit() -> Optional[int]:+ limit = os.environ.get("MARIMO_SQL_DEFAULT_LIMIT")+ return int(limit) if limit is not None else None++@mddoc-def sql(query: str) -> Any:+def sql(+ query: str,+) -> Any:"""Execute a SQL query.@@ -29,18 +37,80 @@ def sql(query: str) -> Any:import duckdb # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501+ relation = duckdb.sql(query=query)++ if not relation:+ return None++ has_limit = _query_includes_limit(query)+ try:+ default_result_limit = get_default_result_limit()+ except OSError:+ default_result_limit = None++ enforce_own_limit = not has_limit and default_result_limit is not None++ if enforce_own_limit:+ relation = relation.limit(+ cast(int, default_result_limit) + 1+ ) # request 1 more++ custom_total_count: Optional[Literal["too_many"]] = None++ df: Anyif DependencyManager.has_polars():- pl_df = duckdb.execute(query=query).pl()- t = table.table(pl_df, selection=None, page_size=5, pagination=True)- output.replace(t)- return pl_df- if DependencyManager.has_pandas():- pd_df = duckdb.execute(query=query).df()- t = table.table(pd_df, selection=None, page_size=5, pagination=True)- output.replace(t)- return pd_df-- raise ModuleNotFoundError(- "pandas or polars is required to execute sql. "- + "You can install them with 'pip install pandas polars'"+ df = relation.pl()+ if enforce_own_limit:+ custom_total_count = (+ "too_many"+ if len(df) > cast(int, default_result_limit)+ else None+ )+ df = df.limit(default_result_limit)+ elif DependencyManager.has_pandas():+ df = relation.df()+ if enforce_own_limit:+ custom_total_count = (+ "too_many"+ if len(df) > cast(int, default_result_limit)+ else None+ )+ df = df.head(default_result_limit)+ else:+ raise ModuleNotFoundError(+ "pandas or polars is required to execute sql. "+ + "You can install them with 'pip install pandas polars'"+ )++ t = table.table(+ df,+ selection=None,+ page_size=5,+ pagination=True,+ _internal_row_limit=default_result_limit+ if custom_total_count == "too_many"+ else None,+ _internal_total_rows=custom_total_count,+ )+ output.replace(t)+ return df+++def _query_includes_limit(query: str) -> bool:+ import duckdb # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501++ try:+ statements = duckdb.extract_statements(query.strip())+ except Exception:+ # May not be valid SQL+ return False++ if not statements:+ return False++ last_statement = statements[-1]++ return last_statement.type == duckdb.StatementType.SELECT and (+ "LIMIT " in last_statement.query.upper()+ or "LIMIT\n" in last_statement.query.upper())diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.pyindex 5e68083dd6..e9a64abd0c 100644--- a/tests/_plugins/ui/_impl/test_table.py+++ b/tests/_plugins/ui/_impl/test_table.py@@ -265,3 +265,45 @@ def test_table_with_too_many_columns_fails():ui.table(data)assert "greater than the maximum allowed columns" in str(e)+++def test_table_with_too_many_rows_gets_clamped():+ data = {"a": list(range(20_002))}+ table = ui.table(data)+ assert table._component_args["pagination"] is True+ assert table._component_args["page-size"] == 10+ assert table._component_args["has-more"] is True+ assert table._component_args["total-rows"] == 20_002+ assert len(table._component_args["data"]) == 20_000+++def test_table_with_too_many_rows_custom_clamp():+ data = {"a": list(range(20_002))}+ table = ui.table(data, _internal_row_limit=30)+ assert table._component_args["pagination"] is True+ assert table._component_args["page-size"] == 10+ assert table._component_args["has-more"] is True+ assert table._component_args["total-rows"] == 20_002+ assert len(table._component_args["data"]) == 30+++def test_table_with_too_many_rows_custom_clamp_and_total():+ data = {"a": list(range(40))}+ table = ui.table(data, _internal_row_limit=30, _internal_total_rows=300)+ assert table._component_args["pagination"] is True+ assert table._component_args["page-size"] == 10+ assert table._component_args["has-more"] is True+ assert table._component_args["total-rows"] == 300+ assert len(table._component_args["data"]) == 30+++def test_table_with_too_many_rows_unknown_total():+ data = {"a": list(range(40))}+ table = ui.table(+ data, _internal_row_limit=30, _internal_total_rows="too_many"+ )+ assert table._component_args["pagination"] is True+ assert table._component_args["page-size"] == 10+ assert table._component_args["has-more"] is True+ assert table._component_args["total-rows"] == "too_many"+ assert len(table._component_args["data"]) == 30diff --git a/tests/_sql/test_sql.py b/tests/_sql/test_sql.pynew file mode 100644index 0000000000..0ea7e40717--- /dev/null+++ b/tests/_sql/test_sql.py@@ -0,0 +1,94 @@+from __future__ import annotations++import os+from unittest.mock import MagicMock, patch++import pytest++from marimo._dependencies.dependencies import DependencyManager+from marimo._plugins import ui+from marimo._sql.sql import _query_includes_limit, sql++HAS_DEPS = DependencyManager.has_duckdb() and DependencyManager.has_polars()++[email protected](not HAS_DEPS, reason="pandas or polars is required")+def test_query_includes_limit():+ assert _query_includes_limit("SELECT * FROM t LIMIT 10") is True+ assert _query_includes_limit("SELECT * FROM t LIMIT\n10") is True+ assert _query_includes_limit("SELECT * FROM t limit 10") is True+ assert _query_includes_limit("SELECT * FROM t limit\n10") is True+ assert _query_includes_limit("SELECT * FROM t") is False+ assert _query_includes_limit("INSERT INTO t VALUES (1, 2, 3)") is False+ assert _query_includes_limit("") is False+ assert (+ _query_includes_limit("SELECT * FROM t; SELECT * FROM t2 LIMIT 5")+ is True+ )+ assert (+ _query_includes_limit("SELECT * FROM t LIMIT 5; SELECT * FROM t2")+ is False+ )+++@patch("marimo._sql.sql.output.replace")[email protected](not HAS_DEPS, reason="pandas or polars is required")+def test_applies_limit(mock_replace: MagicMock) -> None:+ import duckdb++ try:+ os.environ["MARIMO_SQL_DEFAULT_LIMIT"] = "300"+ duckdb.sql("CREATE TABLE t AS SELECT * FROM range(1000)")+ mock_replace.assert_not_called()++ table: ui.table++ # No limit, fallback to 300+ assert len(sql("SELECT * FROM t")) == 300+ mock_replace.assert_called_once()+ table = mock_replace.call_args[0][0]+ assert table._component_args["total-rows"] == "too_many"+ assert table._component_args["pagination"] is True+ assert len(table._data) == 300+ assert table._filtered_manager.get_num_rows() == 300++ # Limit 10+ mock_replace.reset_mock()+ assert len(sql("SELECT * FROM t LIMIT 10")) == 10+ mock_replace.assert_called_once()+ table = mock_replace.call_args[0][0]+ assert table._component_args["total-rows"] == 10+ assert table._component_args["pagination"] is True+ assert len(table._data) == 10+ assert table._filtered_manager.get_num_rows() == 10++ # Limit 400+ mock_replace.reset_mock()+ assert len(sql("SELECT * FROM t LIMIT 400")) == 400+ mock_replace.assert_called_once()+ table = mock_replace.call_args[0][0]+ assert table._component_args["total-rows"] == 400+ assert table._component_args["pagination"] is True+ assert len(table._data) == 400+ assert table._filtered_manager.get_num_rows() == 400++ # Limit above 20_0000 (which is the mo.ui.table cutoff)+ mock_replace.reset_mock()+ duckdb.sql("CREATE TABLE big_table AS SELECT * FROM range(30_000)")+ assert len(sql("SELECT * FROM big_table LIMIT 25_000")) == 25_000+ mock_replace.assert_called_once()+ table = mock_replace.call_args[0][0]+ assert table._component_args["total-rows"] == 25_000+ assert table._component_args["pagination"] is True+ assert len(table._data) == 25_000+ assert (+ table._filtered_manager.get_num_rows() == 20_000+ ) # cutoff by mo.ui.table DEFAULT_ROW_LIMIT+ finally:+ del os.environ["MARIMO_SQL_DEFAULT_LIMIT"]++[email protected](HAS_DEPS, reason="must be missing deps")+def test_sql_raises_error_without_duckdb():+ with pytest.raises(ModuleNotFoundError):+ sql("SELECT * FROM t")