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.

refactor so that sql engines uses the same logic for returning df (#5991)

Shahmir Varqha320894818235
diff --git a/marimo/_sql/engines/clickhouse.py b/marimo/_sql/engines/clickhouse.py
index 3a0ad04d36..41fdb7b859 100644
--- a/marimo/_sql/engines/clickhouse.py
+++ b/marimo/_sql/engines/clickhouse.py
@@ -19,7 +19,7 @@ from marimo._sql.engines.types import (
InferenceConfig,
SQLConnection,
)
-from marimo._sql.utils import raise_df_import_error, sql_type_to_data_type
+from marimo._sql.utils import convert_to_output, sql_type_to_data_type
from marimo._types.ids import VariableName
LOGGER = _loggers.marimo_logger()
@@ -28,6 +28,9 @@ if TYPE_CHECKING:
from chdb.state.sqlitelike import Connection as ChdbConnection # type: ignore # noqa: I001
from clickhouse_connect.driver.client import Client as ClickhouseClient # type: ignore
+ import pandas as pd
+ import polars as pl
+
WHY_PANDAS_REQUIRED = (
"required to convert Clickhouse results to a DataFrame. "
@@ -77,43 +80,29 @@ class ClickhouseEmbedded(SQLConnection[Optional["ChdbConnection"]]):
sql_output_format, rows, col_names
)
+ def convert_to_polars() -> pl.DataFrame:
+ import polars as pl
+
+ arrow_result = chdb.query(query, output_format="Arrow")
+ return pl.read_ipc(arrow_result.bytes()) # type: ignore
+
+ def convert_to_lazy_polars() -> pl.LazyFrame:
+ import polars as pl
+
+ arrow_result = chdb.query(query, output_format="Arrow")
+ return pl.scan_ipc(arrow_result.bytes()) # type: ignore
+
# Handle connectionless execution
# Although this connection method isn't exposed to the user, it's still good to handle
# Maybe we want to move all queries to connectionless execution, but the API is still evolving
try:
- if sql_output_format == "native":
- return chdb.query(query, output_format="Native")
- elif sql_output_format == "polars":
- import polars as pl
-
- arrow_result = chdb.query(query, output_format="Arrow")
- return pl.read_ipc(arrow_result.bytes())
- elif sql_output_format == "lazy-polars":
- import polars as pl
-
- arrow_result = chdb.query(query, output_format="Arrow")
- return pl.scan_ipc(arrow_result.bytes()) # type: ignore
- elif sql_output_format == "pandas":
- return chdb.query(query, output_format="Dataframe")
- else: # Auto
- if DependencyManager.polars.has():
- import polars as pl
-
- try:
- arrow_result = chdb.query(query, output_format="Arrow")
- return pl.read_ipc(arrow_result.bytes())
- except (
- pl.exceptions.PanicException,
- pl.exceptions.ComputeError,
- ):
- LOGGER.exception(
- "Failed to convert to polars, fallback to pandas"
- )
-
- if DependencyManager.pandas.has():
- return chdb.query(query, output_format="Dataframe")
-
- raise_df_import_error("pandas")
+ return convert_to_output(
+ sql_output_format=sql_output_format,
+ to_polars=convert_to_polars,
+ to_pandas=chdb.query(query, output_format="Dataframe"),
+ to_lazy_polars=convert_to_lazy_polars,
+ to_native=lambda: chdb.query(query, output_format="Native"),
+ )
except Exception:
LOGGER.exception("Failed to execute query")
@@ -126,40 +115,27 @@ class ClickhouseEmbedded(SQLConnection[Optional["ChdbConnection"]]):
col_names: list[str],
) -> Any:
# For polars, orient the rows since each tuple represents a column
- if output_format == "polars":
+ def convert_to_polars() -> pl.DataFrame:
import polars as pl
return pl.DataFrame(rows, schema=col_names, orient="row")
- elif output_format == "lazy-polars":
+
+ def convert_to_lazy_polars() -> pl.LazyFrame:
import polars as pl
return pl.LazyFrame(rows, schema=col_names, orient="row")
- elif output_format == "pandas":
+
+ def convert_to_pandas() -> pd.DataFrame:
import pandas as pd
return pd.DataFrame(rows, columns=col_names)
- elif output_format == "auto":
- # Try polars first if available
- if DependencyManager.polars.has():
- import polars as pl
-
- try:
- return pl.DataFrame(rows, schema=col_names, orient="row")
- except (
- pl.exceptions.PanicException,
- pl.exceptions.ComputeError,
- ):
- LOGGER.exception(
- "Failed to convert to polars, falling back to pandas"
- )
-
- # Fall back to pandas
- if DependencyManager.pandas.has():
- import pandas as pd
-
- return pd.DataFrame(rows, columns=col_names)
- raise_df_import_error("pandas")
+ return convert_to_output(
+ sql_output_format=output_format,
+ to_polars=convert_to_polars,
+ to_lazy_polars=convert_to_lazy_polars,
+ to_pandas=convert_to_pandas,
+ )
# TODO: Implement the following functionalities
def get_databases(
@@ -239,47 +215,31 @@ class ClickhouseServer(SQLConnection[Optional["ClickhouseClient"]]):
sql_type = classify_sql_statement(query)
if sql_type == "DDL" or sql_type == "DML":
# TODO: Return the result of the command instead of an empty list
- result = self._connection.command(query)
+ self._connection.command(query)
return []
sql_output_format = self.sql_output_format()
- if sql_output_format == "native":
- return self._connection.query(query)
- elif sql_output_format == "polars":
- import polars as pl
- arrow_result = self._connection.query_arrow(query)
- return pl.from_arrow(arrow_result)
- elif sql_output_format == "lazy-polars":
- import polars as pl
-
- arrow_result = self._connection.query_arrow(query)
- return pl.from_arrow(arrow_result).lazy() # type: ignore
- elif sql_output_format == "pandas":
- return self._connection.query_df(query)
+ def convert_to_polars() -> Union[pl.DataFrame, pl.Series]:
+ if self._connection is None:
+ raise ValueError("Connection is not set")
- # Auto
- if DependencyManager.polars.has():
import polars as pl
- try:
- arrow_result = self._connection.query_arrow(query)
- return pl.from_arrow(arrow_result)
- except (pl.exceptions.PanicException, pl.exceptions.ComputeError):
- LOGGER.info(
- "Failed to convert to polars, falling back to pandas"
- )
+ arrow_result = self._connection.query_arrow(query)
+ return pl.from_arrow(arrow_result)
- if DependencyManager.pandas.has():
- import pandas as pd
+ def convert_to_pandas() -> pd.DataFrame:
+ if self._connection is None:
+ raise ValueError("Connection is not set")
- # If wrapped with try/catch, an error may not be caught
- result = self._connection.query_df(query)
- if isinstance(result, pd.DataFrame):
- return result
- return None
+ return self._connection.query_df(query) # type: ignore
- raise_df_import_error("polars[pyarrow]")
+ return convert_to_output(
+ sql_output_format=sql_output_format,
+ to_polars=convert_to_polars,
+ to_pandas=convert_to_pandas,
+ )
@staticmethod
def is_compatible(var: Any) -> bool:
diff --git a/marimo/_sql/engines/dbapi.py b/marimo/_sql/engines/dbapi.py
index a1467db8c5..e4a0219803 100644
--- a/marimo/_sql/engines/dbapi.py
+++ b/marimo/_sql/engines/dbapi.py
@@ -4,15 +4,17 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Any, Optional, Protocol
from marimo import _loggers
-from marimo._dependencies.dependencies import DependencyManager
from marimo._sql.engines.types import QueryEngine
-from marimo._sql.utils import raise_df_import_error
+from marimo._sql.utils import convert_to_output
LOGGER = _loggers.marimo_logger()
if TYPE_CHECKING:
from collections.abc import Sequence
+ import pandas as pd
+ import polars as pl
+
class DBAPIConnection(Protocol):
def cursor(self) -> Any: ...
@@ -65,7 +67,7 @@ class DBAPIEngine(QueryEngine[DBAPIConnection]):
else:
columns = []
- def convert_to_polars(rows: list[tuple[Any, ...]]) -> pl.DataFrame:
+ def convert_to_polars() -> pl.DataFrame:
import polars as pl
data: dict[str, list[Any]] = {col: [] for col in columns}
@@ -74,41 +76,16 @@ class DBAPIEngine(QueryEngine[DBAPIConnection]):
data[col].append(row[i])
return pl.DataFrame(data)
- if sql_output_format == "polars":
- return convert_to_polars(rows)
-
- if sql_output_format == "lazy-polars":
- return convert_to_polars(rows).lazy()
-
- if sql_output_format == "pandas":
+ def convert_to_pandas() -> pd.DataFrame:
import pandas as pd
return pd.DataFrame(rows, columns=columns)
- # Auto
- if DependencyManager.polars.has():
- import polars as pl
-
- try:
- return convert_to_polars(rows)
- except (
- pl.exceptions.PanicException,
- pl.exceptions.ComputeError,
- ):
- LOGGER.info(
- "Failed to convert to polars, falling back to pandas"
- )
-
- if DependencyManager.pandas.has():
- import pandas as pd
-
- try:
- return pd.DataFrame(rows, columns=columns)
- except Exception as e:
- LOGGER.warning("Failed to convert dataframe", exc_info=e)
- return None
-
- raise_df_import_error("polars[pyarrow]")
+ return convert_to_output(
+ sql_output_format=sql_output_format,
+ to_polars=convert_to_polars,
+ to_pandas=convert_to_pandas,
+ )
finally:
if should_close:
cursor.close()
diff --git a/marimo/_sql/engines/duckdb.py b/marimo/_sql/engines/duckdb.py
index bf6d824b1c..38b28cf409 100644
--- a/marimo/_sql/engines/duckdb.py
+++ b/marimo/_sql/engines/duckdb.py
@@ -8,7 +8,7 @@ from marimo._data.get_datasets import get_databases_from_duckdb
from marimo._data.models import Database, DataTable
from marimo._dependencies.dependencies import DependencyManager
from marimo._sql.engines.types import InferenceConfig, SQLConnection
-from marimo._sql.utils import raise_df_import_error, wrapped_sql
+from marimo._sql.utils import convert_to_output, wrapped_sql
from marimo._types.ids import VariableName
LOGGER = _loggers.marimo_logger()
@@ -46,36 +46,13 @@ class DuckDBEngine(SQLConnection[Optional["duckdb.DuckDBPyConnection"]]):
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
-
- try:
- return relation.pl()
- except (
- pl.exceptions.PanicException,
- pl.exceptions.ComputeError,
- ) as e:
- LOGGER.warning("Failed to convert to polars. Reason: %s.", e)
- DependencyManager.pandas.require("to convert this data")
-
- if DependencyManager.pandas.has():
- try:
- return relation.df()
- except Exception as e:
- LOGGER.warning("Failed to convert dataframe", exc_info=e)
- return None
-
- raise_df_import_error("polars[pyarrow]")
+
+ return convert_to_output(
+ sql_output_format=sql_output_format,
+ to_polars=lambda: relation.pl(),
+ to_pandas=lambda: relation.df(),
+ to_native=lambda: relation,
+ )
@staticmethod
def is_compatible(var: Any) -> bool:
diff --git a/marimo/_sql/engines/ibis.py b/marimo/_sql/engines/ibis.py
index 379d3ed534..6358beba99 100644
--- a/marimo/_sql/engines/ibis.py
+++ b/marimo/_sql/engines/ibis.py
@@ -13,7 +13,7 @@ from marimo._data.models import (
)
from marimo._dependencies.dependencies import DependencyManager
from marimo._sql.engines.types import InferenceConfig, SQLConnection
-from marimo._sql.utils import raise_df_import_error
+from marimo._sql.utils import convert_to_output
from marimo._types.ids import VariableName
if TYPE_CHECKING:
@@ -60,42 +60,12 @@ class IbisEngine(SQLConnection["SQLBackend"]):
sql_output_format = self.sql_output_format()
- if sql_output_format == "native":
- return query_expr # ibis.expr.types.Table; lazy
-
- if sql_output_format == "polars":
- return query_expr.to_polars()
-
- if sql_output_format == "lazy-polars":
- import polars as pl
-
- return pl.DataFrame(query_expr.to_polars()).lazy() # type: ignore
-
- if sql_output_format == "pandas":
- return query_expr.to_pandas()
-
- # Auto
- if DependencyManager.polars.has():
- import polars as pl
-
- try:
- return query_expr.to_polars()
- except (
- pl.exceptions.PanicException,
- pl.exceptions.ComputeError,
- ):
- LOGGER.info(
- "Failed to convert to polars, falling back to pandas"
- )
-
- if DependencyManager.pandas.has():
- try:
- return query_expr.to_pandas()
- except Exception as e:
- LOGGER.warning("Failed to convert dataframe", exc_info=e)
- return None
-
- raise_df_import_error("polars[pyarrow]")
+ return convert_to_output(
+ sql_output_format=sql_output_format,
+ to_polars=lambda: query_expr.to_polars(),
+ to_pandas=lambda: query_expr.to_pandas(),
+ to_native=lambda: query_expr,
+ )
@staticmethod
def is_compatible(var: Any) -> bool:
diff --git a/marimo/_sql/engines/sqlalchemy.py b/marimo/_sql/engines/sqlalchemy.py
index ec90d915a1..762a284b36 100644
--- a/marimo/_sql/engines/sqlalchemy.py
+++ b/marimo/_sql/engines/sqlalchemy.py
@@ -14,12 +14,14 @@ from marimo._data.models import (
)
from marimo._dependencies.dependencies import DependencyManager
from marimo._sql.engines.types import InferenceConfig, SQLConnection
-from marimo._sql.utils import raise_df_import_error, sql_type_to_data_type
+from marimo._sql.utils import convert_to_output, sql_type_to_data_type
from marimo._types.ids import VariableName
LOGGER = _loggers.marimo_logger()
if TYPE_CHECKING:
+ import pandas as pd
+ import polars as pl
from sqlalchemy import Engine, Inspector
from sqlalchemy.engine.cursor import CursorResult
from sqlalchemy.sql.type_api import TypeEngine
@@ -74,43 +76,21 @@ class SQLAlchemyEngine(SQLConnection["Engine"]):
if rows is None:
return None
- if sql_output_format == "polars":
+ def convert_to_polars() -> pl.DataFrame:
import polars as pl
- return pl.DataFrame(rows) # type: ignore
- if sql_output_format == "lazy-polars":
- import polars as pl
+ return pl.DataFrame(rows)
- return pl.DataFrame(rows).lazy() # type: ignore
- if sql_output_format == "pandas":
+ def convert_to_pandas() -> pd.DataFrame:
import pandas as pd
return pd.DataFrame(rows)
- # Auto
-
- if DependencyManager.polars.has():
- import polars as pl
-
- try:
- return pl.DataFrame(rows) # type: ignore
- except (
- pl.exceptions.PanicException,
- pl.exceptions.ComputeError,
- ) as e:
- LOGGER.warning(f"Failed to convert to polars. Reason: {e}")
- DependencyManager.pandas.require("to convert this data")
-
- if DependencyManager.pandas.has():
- import pandas as pd
-
- try:
- return pd.DataFrame(rows)
- except Exception as e:
- LOGGER.warning("Failed to convert dataframe", exc_info=e)
- return None
-
- raise_df_import_error("polars[pyarrow]")
+ return convert_to_output(
+ sql_output_format=sql_output_format,
+ to_polars=convert_to_polars,
+ to_pandas=convert_to_pandas,
+ )
@staticmethod
def is_compatible(var: Any) -> bool:
diff --git a/marimo/_sql/utils.py b/marimo/_sql/utils.py
index 0e0b0a5a11..e1499497c2 100644
--- a/marimo/_sql/utils.py
+++ b/marimo/_sql/utils.py
@@ -1,8 +1,10 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from typing import TYPE_CHECKING, Optional, cast
+from typing import TYPE_CHECKING, Any, Callable, Optional, Union, cast
+from marimo import _loggers
+from marimo._config.config import SqlOutputType
from marimo._data.models import DataType
from marimo._dependencies.dependencies import DependencyManager
from marimo._runtime.context.types import (
@@ -12,9 +14,12 @@ from marimo._runtime.context.types import (
if TYPE_CHECKING:
import duckdb
+ import pandas as pd
import polars as pl
from polars._typing import ConnectionOrCursor
+LOGGER = _loggers.marimo_logger()
+
def wrapped_sql(
query: str,
@@ -70,6 +75,80 @@ def try_convert_to_polars(
return None, e
+def convert_to_output(
+ *,
+ sql_output_format: SqlOutputType,
+ to_polars: Callable[[], Union[pl.DataFrame, pl.Series]],
+ to_pandas: Callable[[], pd.DataFrame],
+ to_native: Optional[Callable[[], Any]] = None,
+ to_lazy_polars: Optional[Callable[[], pl.LazyFrame]] = None,
+) -> Any:
+ """Convert a result to the specified output format.
+
+ Args:
+ result (Any): The result to convert.
+ sql_output_format (SqlOutputType): The output format to convert to.
+ to_polars (Callable[[], Any]): A function to convert the result to polars.
+ to_pandas (Callable[[], Any]): A function to convert the result to pandas.
+ to_native (Callable[[], Any]): A function to convert the result to native.
+ to_lazy_polars (Optional[Callable[[], Any]]): A function to convert the result to lazy polars.
+ If not present, will use to_polars().lazy()
+
+ Returns:
+ Any: The converted result.
+ """
+ if sql_output_format == "native":
+ if to_native is None:
+ raise ValueError("to_native is required for native output format")
+ return to_native()
+
+ if sql_output_format in ("polars", "lazy-polars"):
+ if not DependencyManager.polars.has():
+ raise_df_import_error("polars[pyarrow]")
+
+ if sql_output_format == "polars":
+ return to_polars()
+
+ if sql_output_format == "lazy-polars":
+ import polars as pl
+
+ if to_lazy_polars is not None:
+ return to_lazy_polars()
+
+ # Default handling, we convert to polars and then to lazy polars
+ result = to_polars()
+ if isinstance(result, pl.Series):
+ return result.to_frame().lazy()
+ return result.lazy()
+
+ if sql_output_format == "pandas":
+ if not DependencyManager.pandas.has():
+ raise_df_import_error("pandas")
+ return to_pandas()
+
+ # Auto
+ if DependencyManager.polars.has():
+ import polars as pl
+
+ try:
+ return to_polars()
+ except (
+ pl.exceptions.PanicException,
+ pl.exceptions.ComputeError,
+ ):
+ LOGGER.info("Failed to convert to polars, falling back to pandas")
+ DependencyManager.pandas.require("to convert this data")
+
+ if DependencyManager.pandas.has():
+ try:
+ return to_pandas()
+ except Exception as e:
+ LOGGER.warning("Failed to convert dataframe", exc_info=e)
+ return None
+
+ raise_df_import_error("polars[pyarrow]")
+
+
def raise_df_import_error(pkg: str) -> None:
raise ModuleNotFoundError(
"pandas or polars is required to execute sql. "
diff --git a/tests/_sql/test_engine_utils.py b/tests/_sql/test_engine_utils.py
new file mode 100644
index 0000000000..7dbf658b9b
--- /dev/null
+++ b/tests/_sql/test_engine_utils.py
@@ -0,0 +1,429 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Literal
+from unittest.mock import Mock, patch
+
+import pytest
+
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._sql.utils import convert_to_output
+
+native_result = {"data": "native_result"}
+polars_result = {"data": "polars_result"}
+pandas_result = {"data": "pandas_result"}
+lazy_polars_result = {"data": "lazy_polars_result"}
+
+
+MockFunctions = Literal[
+ "to_native", "to_polars", "to_pandas", "to_lazy_polars"
+]
+MockFnDict = dict[MockFunctions, Mock]
+
+
+def mock_functions() -> MockFnDict:
+ """Returns a dictionary of mock conversion functions keyed by their names."""
+ return {
+ "to_native": Mock(return_value=native_result),
+ "to_polars": Mock(return_value=polars_result),
+ "to_pandas": Mock(return_value=pandas_result),
+ "to_lazy_polars": Mock(return_value=lazy_polars_result),
+ }
+
+
+def assert_only_one_called(
+ mock_functions: MockFnDict, function_name: MockFunctions
+) -> None:
+ """Assert that only the specified mock function was called."""
+ for name, mock_fn in mock_functions.items():
+ if name == function_name:
+ mock_fn.assert_called_once()
+ else:
+ mock_fn.assert_not_called()
+
+
+def assert_multiple_called_once(
+ mock_functions: MockFnDict, expected_called: list[MockFunctions]
+) -> None:
+ """Assert that only the specified mock functions were called once each."""
+ for name, mock_fn in mock_functions.items():
+ if name in expected_called:
+ mock_fn.assert_called_once()
+ else:
+ mock_fn.assert_not_called()
+
+
+class TestNativeOutputFormat:
+ """Test native output format scenarios."""
+
+ def test_with_to_native(self, mock_functions: MockFnDict) -> None:
+ """Test native output format when to_native is provided."""
+ result = convert_to_output(
+ sql_output_format="native",
+ to_polars=mock_functions["to_polars"],
+ to_pandas=mock_functions["to_pandas"],
+ to_native=mock_functions["to_native"],
+ )
+
+ assert result == native_result
+ assert_only_one_called(mock_functions, "to_native")
+
+ def test_without_to_native(self, mock_functions: MockFnDict) -> None:
+ """Test native output format when to_native is not provided."""
+ with pytest.raises(
+ ValueError, match="to_native is required for native output format"
+ ):
+ convert_to_output(
+ sql_output_format="native",
+ to_polars=mock_functions["to_polars"],
+ to_pandas=mock_functions["to_pandas"],
+ )
+
+
+class TestPolarsOutputFormat:
+ """Test polars output format scenarios."""
+
+ @pytest.mark.skipif(
+ not DependencyManager.polars.has(),
+ reason="Polars is not installed",
+ )
+ def test_polars_format(self, mock_functions: MockFnDict) -> None:
+ """Test polars output format."""
+ result = convert_to_output(
+ sql_output_format="polars",
+ to_polars=mock_functions["to_polars"],
+ to_pandas=mock_functions["to_pandas"],
+ )
+
+ assert result == polars_result
+ assert_only_one_called(mock_functions, "to_polars")
+
+
+ not DependencyManager.polars.has(),
+ reason="Polars is not installed",
+)
+class TestLazyPolarsOutputFormat:
+ """Test lazy-polars output format scenarios."""
+
+ def test_with_to_lazy_polars(self, mock_functions: MockFnDict) -> None:
+ """Test lazy-polars output format when to_lazy_polars is provided."""
+ result = convert_to_output(
+ sql_output_format="lazy-polars",
+ to_polars=mock_functions["to_polars"],
+ to_pandas=mock_functions["to_pandas"],
+ to_lazy_polars=mock_functions["to_lazy_polars"],
+ )
+
+ assert result == lazy_polars_result
+ assert_only_one_called(mock_functions, "to_lazy_polars")
+
+ def test_without_to_lazy_polars_dataframe(
+ self, mock_functions: MockFnDict
+ ) -> None:
+ """Test lazy-polars output format when to_lazy_polars is not provided and to_polars returns DataFrame."""
+ mock_dataframe = Mock()
+ mock_lazy_frame = Mock()
+ mock_dataframe.lazy.return_value = mock_lazy_frame
+ mock_functions["to_polars"].return_value = mock_dataframe
+
+ result = convert_to_output(
+ sql_output_format="lazy-polars",
+ to_polars=mock_functions["to_polars"],
+ to_pandas=mock_functions["to_pandas"],
+ )
+
+ assert result == mock_lazy_frame
+ mock_functions["to_polars"].assert_called_once()
+ mock_dataframe.lazy.assert_called_once()
+ mock_functions["to_pandas"].assert_not_called()
+
+ def test_without_to_lazy_polars_series(
+ self, mock_functions: MockFnDict
+ ) -> None:
+ """Test lazy-polars output format when to_lazy_polars is not provided and to_polars returns Series."""
+ import polars as pl
+
+ mock_series = Mock(spec=pl.Series)
+ mock_frame = Mock()
+ mock_lazy_frame = Mock()
+ mock_series.to_frame.return_value = mock_frame
+ mock_frame.lazy.return_value = mock_lazy_frame
+ mock_functions["to_polars"].return_value = mock_series
+
+ result = convert_to_output(
+ sql_output_format="lazy-polars",
+ to_polars=mock_functions["to_polars"],
+ to_pandas=mock_functions["to_pandas"],
+ )
+
+ assert result == mock_lazy_frame
+ mock_functions["to_polars"].assert_called_once()
+ mock_series.to_frame.assert_called_once()
+ mock_frame.lazy.assert_called_once()
+ mock_functions["to_pandas"].assert_not_called()
+
+
+ not DependencyManager.pandas.has(),
+ reason="Pandas is not installed",
+)
+class TestPandasOutputFormat:
+ """Test pandas output format scenarios."""
+
+ def test_pandas_format(self, mock_functions: MockFnDict) -> None:
+ """Test pandas output format."""
+ result = convert_to_output(
+ sql_output_format="pandas",
+ to_polars=mock_functions["to_polars"],
+ to_pandas=mock_functions["to_pandas"],
+ )
+
+ assert result == pandas_result
+ assert_only_one_called(mock_functions, "to_pandas")
+
+
+class TestAutoOutputFormat:
+ """Test auto output format scenarios."""
+
+ @pytest.mark.skipif(
+ not DependencyManager.polars.has(),
+ reason="Polars is not installed",
+ )
+ @patch("marimo._sql.utils.DependencyManager")
+ def test_with_polars_success(
+ self, mock_dependency_manager: Mock, mock_functions: MockFnDict
+ ) -> None:
+ """Test auto output format when polars is available and succeeds."""
+ mock_dependency_manager.polars.has.return_value = True
+ mock_dependency_manager.pandas.has.return_value = False
+
+ result = convert_to_output(
+ sql_output_format="auto",
+ to_polars=mock_functions["to_polars"],
+ to_pandas=mock_functions["to_pandas"],
+ )
+
+ assert result == polars_result
+ assert_only_one_called(mock_functions, "to_polars")
+
+ @pytest.mark.skipif(
+ not DependencyManager.polars.has(),
+ reason="Polars is not installed",
+ )
+ @patch("marimo._sql.utils.DependencyManager")
+ @patch("marimo._sql.utils.LOGGER")
+ def test_with_polars_failure_fallback_to_pandas(
+ self,
+ mock_logger: Mock,
+ mock_dependency_manager: Mock,
+ mock_functions: MockFnDict,
+ ) -> None:
+ """Test auto output format when polars fails and falls back to pandas."""
+ mock_dependency_manager.polars.has.return_value = True
+ mock_dependency_manager.pandas.has.return_value = True
+
+ import polars as pl
+
+ mock_functions["to_polars"].side_effect = pl.exceptions.PanicException(
+ "test error"
+ )
+
+ result = convert_to_output(
+ sql_output_format="auto",
+ to_polars=mock_functions["to_polars"],
+ to_pandas=mock_functions["to_pandas"],
+ )
+
+ assert result == pandas_result
+ assert_multiple_called_once(mock_functions, ["to_polars", "to_pandas"])
+ mock_logger.info.assert_called_once_with(
+ "Failed to convert to polars, falling back to pandas"
+ )
+
+ @pytest.mark.skipif(
+ not DependencyManager.polars.has(),
+ reason="Polars is not installed",
+ )
+ @patch("marimo._sql.utils.DependencyManager")
+ @patch("marimo._sql.utils.LOGGER")
+ def test_with_polars_compute_error_fallback_to_pandas(
+ self,
+ mock_logger: Mock,
+ mock_dependency_manager: Mock,
+ mock_functions: MockFnDict,
+ ) -> None:
+ """Test auto output format when polars ComputeError occurs and falls back to pandas."""
+ mock_dependency_manager.polars.has.return_value = True
+ mock_dependency_manager.pandas.has.return_value = True
+
+ import polars as pl
+
+ mock_functions["to_polars"].side_effect = pl.exceptions.ComputeError(
+ "test error"
+ )
+
+ result = convert_to_output(
+ sql_output_format="auto",
+ to_polars=mock_functions["to_polars"],
+ to_pandas=mock_functions["to_pandas"],
+ )
+
+ assert result == pandas_result
+ assert_multiple_called_once(mock_functions, ["to_polars", "to_pandas"])
+ mock_logger.info.assert_called_once_with(
+ "Failed to convert to polars, falling back to pandas"
+ )
+
+ @patch("marimo._sql.utils.DependencyManager")
+ def test_without_polars_with_pandas_success(
+ self, mock_dependency_manager: Mock, mock_functions: MockFnDict
+ ) -> None:
+ """Test auto output format when polars is not available but pandas succeeds."""
+ mock_dependency_manager.polars.has.return_value = False
+ mock_dependency_manager.pandas.has.return_value = True
+
+ result = convert_to_output(
+ sql_output_format="auto",
+ to_polars=mock_functions["to_polars"],
+ to_pandas=mock_functions["to_pandas"],
+ )
+
+ assert result == pandas_result
+ assert_only_one_called(mock_functions, "to_pandas")
+
+ @patch("marimo._sql.utils.DependencyManager")
+ @patch("marimo._sql.utils.LOGGER")
+ def test_without_polars_with_pandas_failure(
+ self,
+ mock_logger: Mock,
+ mock_dependency_manager: Mock,
+ mock_functions: MockFnDict,
+ ) -> None:
+ """Test auto output format when polars is not available and pandas fails."""
+ mock_dependency_manager.polars.has.return_value = False
+ mock_dependency_manager.pandas.has.return_value = True
+
+ pandas_error = Exception("pandas error")
+ mock_functions["to_pandas"].side_effect = pandas_error
+
+ result = convert_to_output(
+ sql_output_format="auto",
+ to_polars=mock_functions["to_polars"],
+ to_pandas=mock_functions["to_pandas"],
+ )
+
+ assert result is None
+ assert_only_one_called(mock_functions, "to_pandas")
+ mock_logger.warning.assert_called_once_with(
+ "Failed to convert dataframe", exc_info=pandas_error
+ )
+
+ @patch("marimo._sql.utils.DependencyManager")
+ def test_without_polars_without_pandas(
+ self, mock_dependency_manager: Mock, mock_functions: MockFnDict
+ ) -> None:
+ """Test auto output format when neither polars nor pandas is available."""
+ mock_dependency_manager.polars.has.return_value = False
+ mock_dependency_manager.pandas.has.return_value = False
+
+ with pytest.raises(
+ ModuleNotFoundError, match="pandas or polars is required"
+ ):
+ convert_to_output(
+ sql_output_format="auto",
+ to_polars=mock_functions["to_polars"],
+ to_pandas=mock_functions["to_pandas"],
+ )
+
+ mock_functions["to_polars"].assert_not_called()
+ mock_functions["to_pandas"].assert_not_called()
+
+ @pytest.mark.skipif(
+ not DependencyManager.polars.has(),
+ reason="Polars is not installed",
+ )
+ @patch("marimo._sql.utils.DependencyManager")
+ def test_with_polars_failure_no_pandas(
+ self, mock_dependency_manager: Mock, mock_functions: MockFnDict
+ ) -> None:
+ """Test auto output format when polars fails and pandas is not available."""
+ mock_dependency_manager.polars.has.return_value = True
+ mock_dependency_manager.pandas.has.return_value = False
+
+ import polars as pl
+
+ mock_functions["to_polars"].side_effect = pl.exceptions.PanicException(
+ "test error"
+ )
+
+ with pytest.raises(
+ ModuleNotFoundError, match="pandas or polars is required"
+ ):
+ convert_to_output(
+ sql_output_format="auto",
+ to_polars=mock_functions["to_polars"],
+ to_pandas=mock_functions["to_pandas"],
+ )
+
+ mock_functions["to_polars"].assert_called_once()
+ mock_functions["to_pandas"].assert_not_called()
+
+
+class TestAllOutputFormats:
+ """Test all output format types."""
+
+ @pytest.mark.skipif(
+ not DependencyManager.polars.has()
+ and not DependencyManager.pandas.has(),
+ reason="Polars and pandas are not installed",
+ )
+ @pytest.mark.parametrize(
+ ("format_type", "expected_result", "expected_called_once"),
+ [
+ ("polars", polars_result, ["to_polars"]),
+ ("pandas", pandas_result, ["to_pandas"]),
+ ("native", native_result, ["to_native"]),
+ ("lazy-polars", lazy_polars_result, ["to_lazy_polars"]),
+ ],
+ )
+ def test_basic_formats(
+ self,
+ format_type: str,
+ expected_result: dict,
+ expected_called_once: list[str],
+ mock_functions: MockFnDict,
+ ) -> None:
+ """Test basic output formats without complex dependencies."""
+ result = convert_to_output(
+ sql_output_format=format_type,
+ to_polars=mock_functions["to_polars"],
+ to_pandas=mock_functions["to_pandas"],
+ to_native=mock_functions["to_native"],
+ to_lazy_polars=mock_functions["to_lazy_polars"],
+ )
+
+ assert result == expected_result
+ assert_multiple_called_once(mock_functions, expected_called_once) # type: ignore
+
+ @pytest.mark.skipif(
+ not DependencyManager.polars.has(),
+ reason="Polars is not installed",
+ )
+ @patch("marimo._sql.utils.DependencyManager")
+ def test_auto_format_with_polars(
+ self, mock_dependency_manager: Mock, mock_functions: MockFnDict
+ ) -> None:
+ """Test auto format when polars is available."""
+ mock_dependency_manager.polars.has.return_value = True
+ mock_dependency_manager.pandas.has.return_value = False
+
+ result = convert_to_output(
+ sql_output_format="auto",
+ to_polars=mock_functions["to_polars"],
+ to_pandas=mock_functions["to_pandas"],
+ )
+
+ assert result == polars_result
+ assert_only_one_called(mock_functions, "to_polars")