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.

improve: add clickhouse support for diff sql output types (#4456)

Shahmir Varqha7e6043346981
diff --git a/marimo/_sql/engines/clickhouse.py b/marimo/_sql/engines/clickhouse.py
index a480662891..ccd64abd00 100644
--- a/marimo/_sql/engines/clickhouse.py
+++ b/marimo/_sql/engines/clickhouse.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Any, Literal, Optional, Union, cast
from marimo import _loggers
+from marimo._config.config import SqlOutputType
from marimo._data.models import (
Database,
DataTable,
@@ -17,7 +18,7 @@ from marimo._sql.engines.types import (
SQLEngine,
register_engine,
)
-from marimo._sql.utils import sql_type_to_data_type
+from marimo._sql.utils import raise_df_import_error, sql_type_to_data_type
from marimo._types.ids import VariableName
LOGGER = _loggers.marimo_logger()
@@ -27,8 +28,9 @@ if TYPE_CHECKING:
from clickhouse_connect.driver.client import Client as ClickhouseClient # type: ignore
-PANDAS_REQUIRED_MSG = (
- "Pandas is required to convert Clickhouse results to a DataFrame"
+WHY_PANDAS_REQUIRED = (
+ "required to convert Clickhouse results to a DataFrame. "
+ "You may opt to choose Native output instead."
)
@@ -54,31 +56,111 @@ class ClickhouseEmbedded(SQLEngine):
return "clickhouse"
def execute(self, query: str) -> Any:
- # chdb currently only supports pandas
- DependencyManager.pandas.require(PANDAS_REQUIRED_MSG)
-
import chdb # type: ignore
- import pandas as pd
- # TODO: this will fail weirdly / silently when there is another connection
+ query = query.strip()
+ sql_output_format = self.sql_output_format()
- # Do not catch exceptions here or it may silently fail
+ # Handle connection-based execution
if self._cursor:
self._cursor.execute(query)
+
+ if sql_output_format == "native":
+ LOGGER.info(
+ "Native output chosen, query is executed but results are not fetched"
+ )
+ return None
+
rows = self._cursor.fetchall()
col_names = self._cursor.column_names()
- # col_types = self._cursor.column_types()
- return pd.DataFrame(rows, columns=col_names)
+ return self._convert_to_output_format(
+ sql_output_format, rows, col_names
+ )
+ # 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:
- result = chdb.query(query, "Dataframe")
+ 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")
+
except Exception:
LOGGER.exception("Failed to execute query")
return None
- if isinstance(result, pd.DataFrame):
- return result
- return None
+
+ def _convert_to_output_format(
+ self,
+ output_format: SqlOutputType,
+ rows: list[tuple[Any, ...]],
+ col_names: list[str],
+ ) -> Any:
+ # For polars, orient the rows since each tuple represents a column
+ if output_format == "polars":
+ import polars as pl
+
+ return pl.DataFrame(rows, schema=col_names, orient="row")
+ elif output_format == "lazy-polars":
+ import polars as pl
+
+ return pl.LazyFrame(rows, schema=col_names, orient="row")
+ elif output_format == "pandas":
+ 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")
# TODO: Implement the following functionalities
def get_databases(
@@ -155,19 +237,46 @@ class ClickhouseServer(SQLEngine):
if self._connection is None:
return None
- # clickhouse connect supports pandas and arrow format
- DependencyManager.pandas.require(PANDAS_REQUIRED_MSG)
+ query = query.strip()
- import pandas as pd
+ 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)
+
+ # 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"
+ )
- query = query.strip()
+ if DependencyManager.pandas.has():
+ import pandas as pd
- # If wrapped with try/catch, an error may not be caught
- result = self._connection.query_df(query)
+ # 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
- if isinstance(result, pd.DataFrame):
- return result
- return None
+ raise_df_import_error("polars[pyarrow]")
@staticmethod
def is_compatible(var: Any) -> bool:
diff --git a/marimo/_sql/sql.py b/marimo/_sql/sql.py
index 7146f78fac..97e5628e5c 100644
--- a/marimo/_sql/sql.py
+++ b/marimo/_sql/sql.py
@@ -117,6 +117,8 @@ def sql(
# Also preload the first page of data without user confirmation.
t = table.table.lazy(df, preload=True)
else:
+ # df may be a cursor result from an SQL Engine
+ # In this case, we need to convert it to a DataFrame
t = table.table(
df,
selection=None,
diff --git a/tests/_sql/test_clickhouse.py b/tests/_sql/test_clickhouse.py
index 93fe6fe126..49269b0694 100644
--- a/tests/_sql/test_clickhouse.py
+++ b/tests/_sql/test_clickhouse.py
@@ -1,22 +1,25 @@
from __future__ import annotations
+from typing import Any
+from unittest import mock
+
import pytest
+from marimo._config.config import SqlOutputType
from marimo._data.models import DataSourceConnection
from marimo._dependencies.dependencies import DependencyManager
from marimo._sql.engines.clickhouse import ClickhouseEmbedded, ClickhouseServer
from marimo._sql.get_engines import engine_to_data_source_connection
from marimo._sql.sql import sql
-HAS_CHDB = DependencyManager.chdb.has() and DependencyManager.pandas.has()
-HAS_CLICKHOUSE_CONNECT = (
- DependencyManager.clickhouse_connect.has()
- and DependencyManager.pandas.has()
-)
+HAS_CHDB = DependencyManager.chdb.has()
+HAS_POLARS = DependencyManager.polars.has()
+HAS_PANDAS = DependencyManager.pandas.has()
+HAS_CLICKHOUSE_CONNECT = DependencyManager.clickhouse_connect.has()
@pytest.mark.skipif(
- not HAS_CLICKHOUSE_CONNECT, reason="Clickhouse and Pandas not installed"
+ not HAS_CLICKHOUSE_CONNECT, reason="Clickhouse connect not installed"
)
def test_clickhouse_server_creation() -> None:
engine = ClickhouseServer(None)
@@ -32,7 +35,7 @@ def test_clickhouse_server_creation() -> None:
assert connection.source == "clickhouse"
[email protected](not HAS_CHDB, reason="chdb and pandas not installed")
[email protected](not HAS_CHDB, reason="chdb not installed")
def test_clickhouse_embedded_creation() -> None:
import chdb
@@ -57,26 +60,91 @@ def test_clickhouse_embedded_creation() -> None:
chdb_conn.close()
[email protected](not HAS_CHDB, reason="chdb and pandas not installed")
[email protected](reason="Flaky test")
-def test_clickhouse_execute() -> None:
+ not HAS_CHDB and not HAS_POLARS, reason="chdb and polars not installed"
+)
+def test_clickhouse_embedded_execute() -> None:
import chdb
- import pandas as pd
+ import polars as pl
+
+ chdb_conn = None
+ try:
+ chdb_conn = chdb.connect(":memory:")
+
+ sql(
+ "CREATE TABLE test (id Int32, name String) ENGINE = Memory",
+ engine=chdb_conn,
+ )
+ sql(
+ "INSERT INTO test VALUES (1, 'Alice'), (2, 'Bob')",
+ engine=chdb_conn,
+ )
+ result = sql("SELECT * FROM test", engine=chdb_conn)
+
+ assert isinstance(result, pl.DataFrame)
+ expected = pl.DataFrame({"id": [1, 2], "name": ["Alice", "Bob"]})
+ assert result.equals(expected)
+ finally:
+ if chdb_conn is not None:
+ chdb_conn.close()
- chdb_conn = chdb.connect(":memory:")
- sql(
- "CREATE TABLE test (id Int32, name String) ENGINE = Memory",
- engine=chdb_conn,
- )
- sql(
- "INSERT INTO test VALUES (1, 'Alice'), (2, 'Bob')",
- engine=chdb_conn,
- )
- result = sql("SELECT * FROM test", engine=chdb_conn)
-
- assert isinstance(result, pd.DataFrame)
- expected = pd.DataFrame({"id": [1, 2], "name": ["Alice", "Bob"]})
- assert result.equals(expected)
-
- chdb_conn.close()
+ not HAS_CHDB and not HAS_POLARS and not HAS_PANDAS,
+ reason="chdb, polars, and pandas not installed",
+)
+def test_clickhouse_emdbedded_connection_based_output_formats() -> None:
+ import chdb
+ import pandas as pd
+ import polars as pl
+
+ # Test different output formats
+ output_formats: tuple[SqlOutputType, Any, Any] = [
+ ("native", None, None),
+ ("polars", pl.DataFrame, pl.DataFrame({"1": [1], "2": [2]})),
+ ("lazy-polars", pl.LazyFrame, None),
+ ("pandas", pd.DataFrame, pd.DataFrame({"1": [1], "2": [2]})),
+ ("auto", pl.DataFrame, pl.DataFrame({"1": [1]})),
+ ]
+
+ for format_name, expected_type, expected_result in output_formats:
+ with mock.patch.object(
+ ClickhouseEmbedded, "sql_output_format", return_value=format_name
+ ):
+ chdb_conn = None
+ try:
+ chdb_conn = chdb.connect(":memory:")
+ query = "SELECT 1, 2" if format_name != "auto" else "SELECT 1"
+ if format_name == "lazy-polars":
+ query = "SELECT 1, 2 FROM generate_series(1, 2)"
+
+ result = sql(query, engine=chdb_conn)
+
+ if format_name == "native":
+ assert result is None
+ else:
+ assert isinstance(result, expected_type)
+ if expected_result is not None:
+ assert result.equals(expected_result)
+ if format_name == "lazy-polars":
+ assert len(result.collect()) == 2
+ finally:
+ if chdb_conn is not None:
+ chdb_conn.close()
+
+ # Test auto when polars not available
+ with (
+ mock.patch.object(
+ ClickhouseEmbedded, "sql_output_format", return_value="auto"
+ ),
+ mock.patch.object(DependencyManager.polars, "has", return_value=False),
+ ):
+ chdb_conn = None
+ try:
+ chdb_conn = chdb.connect(":memory:")
+ result = sql("SELECT 1", engine=chdb_conn)
+ assert isinstance(result, pd.DataFrame)
+ assert result.equals(pd.DataFrame({"1": [1]}))
+ finally:
+ if chdb_conn is not None:
+ chdb_conn.close()