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.

fix: duckdb querying dataframes with engines (#3642)

Myles Scolnick14bf70b68d7c
diff --git a/marimo/_data/sql_summaries.py b/marimo/_data/sql_summaries.py
index 801cbdbb55..4de7c60f74 100644
--- a/marimo/_data/sql_summaries.py
+++ b/marimo/_data/sql_summaries.py
@@ -5,7 +5,7 @@ from typing import List, Tuple
from marimo._data.get_datasets import _db_type_to_data_type
from marimo._data.models import ColumnSummary, DataType
-from marimo._sql.sql import wrapped_sql
+from marimo._sql.utils import wrapped_sql
def get_sql_summary(
@@ -66,7 +66,9 @@ def get_sql_summary(
FROM {table_name}
""" # noqa: E501
- stats_result: Tuple[int, ...] | None = wrapped_sql(stats_query).fetchone()
+ stats_result: Tuple[int, ...] | None = wrapped_sql(
+ stats_query, connection=None
+ ).fetchone()
if stats_result is None:
raise ValueError(
f"Column {column_name} not found in table {table_name}"
@@ -142,7 +144,7 @@ def get_column_type(table_name: str, column_name: str) -> DataType:
"""
column_info_result: Tuple[str] | None = wrapped_sql(
- column_info_query
+ column_info_query, connection=None
).fetchone()
if column_info_result is None:
raise ValueError(
diff --git a/marimo/_sql/engines.py b/marimo/_sql/engines.py
index ba977d7d52..69ff5ea4d1 100644
--- a/marimo/_sql/engines.py
+++ b/marimo/_sql/engines.py
@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Any, Optional
from marimo._dependencies.dependencies import DependencyManager
from marimo._sql.types import SQLEngine
+from marimo._sql.utils import wrapped_sql
if TYPE_CHECKING:
import duckdb
@@ -36,12 +37,7 @@ class DuckDBEngine(SQLEngine):
return "duckdb"
def execute(self, query: str) -> Any:
- import duckdb
-
- if self._connection is None:
- relation = duckdb.sql(query)
- else:
- relation = self._connection.sql(query)
+ relation = wrapped_sql(query, self._connection)
# Invalid / empty query
if relation is None:
diff --git a/marimo/_sql/sql.py b/marimo/_sql/sql.py
index dfb06dba80..c38ba67ee3 100644
--- a/marimo/_sql/sql.py
+++ b/marimo/_sql/sql.py
@@ -6,17 +6,12 @@ from typing import TYPE_CHECKING, Any, Literal, Optional, cast
from marimo._dependencies.dependencies import DependencyManager
from marimo._output.rich_help import mddoc
-from marimo._runtime.context.types import (
- ContextNotInitializedError,
- get_context,
-)
from marimo._runtime.output import replace
from marimo._sql.engines import (
DuckDBEngine,
SQLAlchemyEngine,
raise_df_import_error,
)
-from marimo._sql.types import SQLEngine
def get_default_result_limit() -> Optional[int]:
@@ -70,7 +65,7 @@ def sql(
"Unsupported engine. Must be a SQLAlchemy engine or DuckDB connection."
)
- df = _execute_query(query, sql_engine)
+ df = sql_engine.execute(query)
if df is None:
return None
@@ -136,39 +131,3 @@ def _query_includes_limit(query: str) -> bool:
# Look for any LIMIT clause in the SELECT statement
return last_expr.find(Limit) is not None
-
-
-def _execute_query(query: str, engine: SQLEngine) -> Any:
- # In Python globals() are scoped to modules; since this function
- # is in a different module than user code, globals() doesn't return
- # the kernel globals, it just returns this module's global namespace.
- #
- # However, duckdb needs access to the kernel's globals. For this reason,
- # we manually exec duckdb and provide it with the kernel's globals.
- try:
- ctx = get_context()
- except ContextNotInitializedError:
- return engine.execute(query)
- else:
- return eval(
- "engine.execute(query)",
- ctx.globals,
- {"query": query, "engine": engine},
- )
-
-
-def wrapped_sql(query: str) -> "duckdb.DuckDBPyRelation":
- import duckdb
-
- # Same as above, but for plain duckdb
- try:
- ctx = get_context()
- except ContextNotInitializedError:
- relation = duckdb.sql(query=query)
- else:
- relation = eval(
- "duckdb.sql(query=query)",
- ctx.globals,
- {"query": query, "duckdb": duckdb},
- )
- return relation
diff --git a/marimo/_sql/utils.py b/marimo/_sql/utils.py
new file mode 100644
index 0000000000..5193544ae9
--- /dev/null
+++ b/marimo/_sql/utils.py
@@ -0,0 +1,42 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Optional, cast
+
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._runtime.context.types import (
+ ContextNotInitializedError,
+ get_context,
+)
+
+if TYPE_CHECKING:
+ import duckdb
+
+
+def wrapped_sql(
+ query: str,
+ connection: Optional[duckdb.DuckDBPyConnection],
+) -> "duckdb.DuckDBPyRelation":
+ DependencyManager.duckdb.require("to execute sql")
+
+ # In Python globals() are scoped to modules; since this function
+ # is in a different module than user code, globals() doesn't return
+ # the kernel globals, it just returns this module's global namespace.
+ #
+ # However, duckdb needs access to the kernel's globals. For this reason,
+ # we manually exec duckdb and provide it with the kernel's globals.
+ if connection is None:
+ import duckdb
+
+ connection = cast(duckdb.DuckDBPyConnection, duckdb)
+
+ try:
+ ctx = get_context()
+ except ContextNotInitializedError:
+ relation = connection.sql(query=query)
+ else:
+ relation = eval(
+ "connection.sql(query=query)",
+ ctx.globals,
+ {"query": query, "connection": connection},
+ )
+ return relation
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 3b8c4e136e..b87daebbe9 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -2497,6 +2497,43 @@ class TestSQL:
# cell 1 should re-run but will fail to find t1
assert "df" not in k.globals
+ async def test_sql_query_as_local_df(self, k: Kernel) -> None:
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="0",
+ code="import marimo as mo; import polars as pl",
+ ),
+ ExecutionRequest(
+ cell_id="1",
+ code="source_df = pl.DataFrame({'val': [42]})",
+ ),
+ ExecutionRequest(
+ cell_id="2",
+ code="df = mo.sql('SELECT * FROM source_df')",
+ ),
+ ]
+ )
+ assert not k.errors
+ assert k.globals["df"].to_dict(as_series=False) == {"val": [42]}
+
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="3",
+ code="""
+import duckdb
+conn = duckdb.connect()""",
+ ),
+ ExecutionRequest(
+ cell_id="4",
+ code="df2 = mo.sql('SELECT * FROM source_df', engine=conn)",
+ ),
+ ]
+ )
+ assert not k.errors
+ assert k.globals["df2"].to_dict(as_series=False) == {"val": [42]}
+
class TestStateTransitions:
async def test_statuses_not_repeated_ok_run(
diff --git a/tests/_sql/test_engines.py b/tests/_sql/test_engines.py
index 05c6267d46..027352ea80 100644
--- a/tests/_sql/test_engines.py
+++ b/tests/_sql/test_engines.py
@@ -13,7 +13,7 @@ from marimo._sql.engines import (
SQLAlchemyEngine,
raise_df_import_error,
)
-from marimo._sql.sql import _execute_query, sql
+from marimo._sql.sql import sql
HAS_DUCKDB = DependencyManager.duckdb.has()
HAS_SQLALCHEMY = DependencyManager.sqlalchemy.has()
@@ -116,7 +116,7 @@ def test_duckdb_engine_execute(
# Test with explicit connection
engine = DuckDBEngine(duckdb_connection)
- result = _execute_query("SELECT * FROM test ORDER BY id", engine)
+ result = engine.execute("SELECT * FROM test ORDER BY id")
assert isinstance(result, (pd.DataFrame, pl.DataFrame))
assert len(result) == 4
@@ -131,7 +131,7 @@ def test_sqlalchemy_engine_execute(sqlite_engine: sa.Engine) -> None:
import polars as pl
engine = SQLAlchemyEngine(sqlite_engine)
- result = _execute_query("SELECT * FROM test ORDER BY id", engine)
+ result = engine.execute("SELECT * FROM test ORDER BY id")
assert isinstance(result, (pd.DataFrame, pl.DataFrame))
assert len(result) == 4