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.

feat: Ibis SQL engine (#4683)

Thierry Jeand7d7bab7bfdb
diff --git a/marimo/_sql/engines/ibis.py b/marimo/_sql/engines/ibis.py
new file mode 100644
index 0000000000..22af37a2ca
--- /dev/null
+++ b/marimo/_sql/engines/ibis.py
@@ -0,0 +1,395 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Literal, Optional, Union
+
+from marimo import _loggers
+from marimo._data.models import (
+ Database,
+ DataTable,
+ DataTableColumn,
+ DataType,
+ Schema,
+)
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._sql.engines.types import (
+ InferenceConfig,
+ SQLEngine,
+ register_engine,
+)
+from marimo._sql.utils import raise_df_import_error
+from marimo._types.ids import VariableName
+
+if TYPE_CHECKING:
+ from ibis.backends.sql import SQLBackend # type: ignore
+ from ibis.expr import datatypes as dt # type: ignore
+
+LOGGER = _loggers.marimo_logger()
+
+
+class IbisToMarimoConversionError(Exception):
+ """Raise for unhandled type during Ibis to Marimo conversion"""
+
+
+@register_engine
+class IbisEngine(SQLEngine):
+ """Ibis engine."""
+
+ def __init__(
+ self,
+ connection: SQLBackend,
+ engine_name: Optional[VariableName] = None,
+ ) -> None:
+ self._backend = connection
+ self._engine_name = engine_name
+
+ self.default_database = self.get_default_database()
+ self.default_schema = self.get_default_schema()
+
+ @property
+ def source(self) -> str:
+ # TODO should this be the backend name, the SQL dialect, or ibis?
+ return "ibis"
+
+ @property
+ def dialect(self) -> str:
+ dialect_registry = self._backend.dialect.classes
+ # reverse lookup
+ for dialect_name, dialect_class in dialect_registry.items():
+ if self._backend.dialect == dialect_class:
+ assert isinstance(dialect_name, str)
+ return dialect_name
+
+ return str(self._backend.dialect)
+
+ def execute(self, query: str) -> Any:
+ query_expr = self._backend.sql(query)
+
+ 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]")
+
+ @staticmethod
+ def is_compatible(var: Any) -> bool:
+ if not DependencyManager.ibis.imported():
+ return False
+
+ from ibis import BaseBackend # type: ignore
+ from ibis.backends.sql import SQLBackend # type: ignore
+
+ if isinstance(var, BaseBackend) and not isinstance(var, SQLBackend):
+ LOGGER.debug(
+ f"Ibis backend found, but it's not an SQLBackend subclass. Variable name: {var}"
+ )
+
+ return isinstance(var, SQLBackend)
+
+ @property
+ def inference_config(self) -> InferenceConfig:
+ return InferenceConfig(
+ auto_discover_schemas=True,
+ auto_discover_tables="auto",
+ auto_discover_columns=False,
+ )
+
+ def get_default_database(self) -> Optional[str]:
+ """Get the current database name.
+
+ Returns:
+ - The database name from the connection URL if available
+ - The database name queried from the database if URL doesn't contain it
+ - An empty string if the connection is detached but valid
+ - None if the connection is invalid
+ """
+ database_name = None
+ try:
+ database_name = self._backend.current_catalog
+ except AttributeError:
+ pass
+
+ if database_name is None:
+ try:
+ database_name = self._backend.name
+ except AttributeError:
+ pass
+
+ return database_name
+
+ def get_default_schema(self) -> Optional[str]:
+ """Get the default schema name"""
+ try:
+ schema_name: str | None = self._backend.current_database
+ except AttributeError:
+ schema_name = None
+
+ return schema_name
+
+ def get_databases(
+ self,
+ *,
+ include_schemas: Union[bool, Literal["auto"]],
+ include_tables: Union[bool, Literal["auto"]],
+ include_table_details: Union[bool, Literal["auto"]],
+ ) -> list[Database]:
+ """Get all databases from the engine.
+
+ Args:
+ include_schemas: Whether to include schema information. If False, databases will have empty schemas.
+ include_tables: Whether to include table information within schemas. If False, schemas will have empty tables.
+ include_table_details: Whether to include each table's detailed information. If False, tables will have empty columns, PK, indexes.
+
+ Returns:
+ List of Database objects representing the database structure.
+
+ Note: This operation can be performance intensive when fetching full metadata.
+ """
+ if self.default_database is None:
+ return []
+
+ database_name = self.default_database
+ if self._resolve_should_auto_discover(include_schemas):
+ schemas = self._get_schemas(
+ database=database_name,
+ include_tables=self._resolve_should_auto_discover(
+ include_tables
+ ),
+ include_table_details=self._resolve_should_auto_discover(
+ include_table_details
+ ),
+ )
+ else:
+ schemas = []
+
+ database: Database = Database(
+ name=database_name,
+ dialect=self.dialect,
+ schemas=schemas,
+ engine=self._engine_name,
+ )
+ return [database]
+
+ def _get_schemas(
+ self,
+ *,
+ database: Optional[str],
+ include_tables: bool,
+ include_table_details: bool,
+ ) -> list[Schema]:
+ """Get all schemas and optionally their tables. Keys are schema names."""
+ meta_schemas = self._get_meta_schemas()
+
+ schemas: list[Schema] = []
+ # TODO handle backends without .list_databases()
+ for schema_name in self._backend.list_databases():
+ if schema_name.lower() in meta_schemas:
+ LOGGER.debug(
+ f"Meta schema found `{schema_name}`. Not displaying schema."
+ )
+ continue
+
+ tables: list[DataTable] = []
+ if include_tables:
+ tables = self.get_tables_in_schema(
+ schema=schema_name,
+ database=database if database is not None else "",
+ include_table_details=include_table_details,
+ )
+ # ignore schemas with 0 tables
+ if len(tables) == 0:
+ LOGGER.debug(
+ f"No table found for schema `{schema_name}`. Not displaying schema."
+ )
+
+ schema = Schema(name=schema_name, tables=tables)
+ schemas.append(schema)
+
+ return schemas
+
+ def _get_meta_schemas(self) -> list[str]:
+ """List of schemas for internal tables we want to ignore."""
+ # TODO find a way to support meta schemas from all Ibis backends
+ return ["information_schema", "pg_catalog"]
+
+ def get_tables_in_schema(
+ self, *, schema: str, database: str, include_table_details: bool
+ ) -> list[DataTable]:
+ """Return all tables in a schema."""
+ if self._backend is None:
+ return []
+
+ try:
+ table_names = self._backend.list_tables(
+ database=(database, schema)
+ )
+ except Exception:
+ LOGGER.warning(
+ f"Failed to get tables from database {database}", exc_info=True
+ )
+ return []
+
+ # NOTE ibis can't distinguish tables and views
+ tables: list[DataTable] = []
+ for table_name in table_names:
+ if include_table_details:
+ table = self.get_table_details(
+ table_name=table_name,
+ schema_name=schema,
+ database_name=database,
+ )
+ if table is None:
+ continue
+ else:
+ table = DataTable(
+ source_type="connection",
+ source=self.source,
+ name=table_name,
+ num_rows=None,
+ num_columns=None,
+ variable_name=None,
+ engine=self._engine_name,
+ type="table",
+ columns=[],
+ primary_keys=None,
+ indexes=None,
+ )
+ tables.append(table)
+
+ return tables
+
+ def get_table_details(
+ self, *, table_name: str, schema_name: str, database_name: str
+ ) -> Optional[DataTable]:
+ """Get a single table from the engine."""
+ if self._backend is None:
+ return None
+
+ try:
+ table = self._backend.table(
+ table_name, database=(database_name, schema_name)
+ )
+ table_schema = table.schema()
+ except Exception:
+ LOGGER.warning(
+ f"Failed to get details for {table_name} in database {database_name}",
+ exc_info=True,
+ )
+ return None
+
+ cols: list[DataTableColumn] = []
+ for col_name, ibis_dtype in table_schema.fields.items():
+ try:
+ col_type: DataType = self._ibis_to_marimo_dtype(ibis_dtype)
+ except IbisToMarimoConversionError:
+ col_type = "string"
+ LOGGER.warning(
+ f"Failed to convert column `{col_name}` with ibis dtype `{ibis_dtype}` to marimo dtype."
+ " Defaulting to `string`."
+ )
+
+ # type and external_type will always match; ibis is unaware of physical type
+ cols.append(
+ DataTableColumn(
+ name=col_name,
+ type=col_type,
+ external_type=str(ibis_dtype),
+ sample_values=[],
+ )
+ )
+
+ # num_rows is not in metadata and would require a count or approx_count
+ # ibis is unaware of primary keys and indices
+ return DataTable(
+ source_type="connection",
+ source=self.source,
+ name=table_name,
+ num_rows=None,
+ num_columns=len(table_schema.fields),
+ variable_name=None,
+ engine=self._engine_name,
+ columns=cols,
+ primary_keys=None,
+ indexes=None,
+ )
+
+ @staticmethod
+ def _ibis_to_marimo_dtype(ibis_dtype: dt.DataType) -> DataType:
+ """Map the Ibis typing system to marimo SQL types.
+
+ Ibis datatypes ref: https://ibis-project.org/reference/datatypes
+ """
+ if ibis_dtype.is_integer():
+ return "integer"
+ # numeric is a superset of integer, so we evaluate after is_integer
+ elif ibis_dtype.is_numeric():
+ return "number"
+
+ elif ibis_dtype.is_date():
+ return "date"
+
+ elif ibis_dtype.is_timestamp():
+ return "datetime"
+
+ elif ibis_dtype.is_time():
+ return "time"
+
+ elif ibis_dtype.is_boolean():
+ return "boolean"
+
+ elif ibis_dtype.is_string():
+ return "string"
+
+ elif ibis_dtype.is_binary():
+ return "string"
+
+ else:
+ raise IbisToMarimoConversionError
+
+ def _resolve_should_auto_discover(
+ self,
+ value: Union[bool, Literal["auto"]],
+ ) -> bool:
+ if value == "auto":
+ return self._is_cheap_discovery()
+ return value
+
+ def _is_cheap_discovery(self) -> bool:
+ return self.dialect.lower() in (
+ "duckdb",
+ "sqlite",
+ "mysql",
+ "postgresql",
+ )
diff --git a/marimo/_sql/get_engines.py b/marimo/_sql/get_engines.py
index f30dac44bd..f776f3fd1e 100644
--- a/marimo/_sql/get_engines.py
+++ b/marimo/_sql/get_engines.py
@@ -19,6 +19,7 @@ from marimo._sql.engines.duckdb import (
INTERNAL_DUCKDB_ENGINE,
DuckDBEngine,
)
+from marimo._sql.engines.ibis import IbisEngine
from marimo._sql.engines.pyiceberg import PyIcebergEngine
from marimo._sql.engines.sqlalchemy import SQLAlchemyEngine
from marimo._sql.engines.types import SQLEngine
@@ -34,6 +35,7 @@ def get_engines_from_variables(
supported_engines: list[type[SQLEngine]] = [
SQLAlchemyEngine,
+ IbisEngine,
DuckDBEngine,
ClickhouseEmbedded,
ClickhouseServer,
diff --git a/marimo/_sql/sql.py b/marimo/_sql/sql.py
index 645f10a485..900200f43b 100644
--- a/marimo/_sql/sql.py
+++ b/marimo/_sql/sql.py
@@ -8,6 +8,7 @@ from marimo._dependencies.dependencies import DependencyManager
from marimo._output.rich_help import mddoc
from marimo._runtime.output import replace
from marimo._sql.engines.duckdb import DuckDBEngine
+from marimo._sql.engines.ibis import IbisEngine
from marimo._sql.engines.sqlalchemy import SQLAlchemyEngine
from marimo._sql.engines.types import ENGINE_REGISTRY
from marimo._sql.utils import raise_df_import_error
@@ -32,7 +33,11 @@ def sql(
*,
output: bool = True,
engine: Optional[
- SAEngine | DuckDBPyConnection | ClickhouseClient | ChdbConnection
+ SAEngine
+ | DuckDBPyConnection
+ | ClickhouseClient
+ | ChdbConnection
+ | IbisEngine
] = None,
) -> Any:
"""
@@ -73,7 +78,7 @@ def sql(
break
else:
raise ValueError(
- "Unsupported engine. Must be a SQLAlchemy, Clickhouse, or DuckDB engine."
+ "Unsupported engine. Must be a SQLAlchemy, Ibis, Clickhouse, or DuckDB engine."
)
df = sql_engine.execute(query)
diff --git a/tests/_sql/test_engines.py b/tests/_sql/test_engines.py
index 00e3aca221..9fa09d37af 100644
--- a/tests/_sql/test_engines.py
+++ b/tests/_sql/test_engines.py
@@ -47,7 +47,7 @@ def test_raise_df_import_error() -> None:
@pytest.mark.skipif(
not (HAS_DUCKDB and HAS_SQLALCHEMY and HAS_CLICKHOUSE),
- reason="Duckdb, sqlalchemy and Clickhouse not installed",
+ reason="Duckdb, sqlalchemy, and Clickhouse not installed",
)
def test_engine_name_initialization() -> None:
"""Test engine name initialization."""
diff --git a/tests/_sql/test_get_engines.py b/tests/_sql/test_get_engines.py
index b0b2f0ab0e..4291fdc2c3 100644
--- a/tests/_sql/test_get_engines.py
+++ b/tests/_sql/test_get_engines.py
@@ -16,6 +16,7 @@ from marimo._sql.engines.duckdb import (
INTERNAL_DUCKDB_ENGINE,
DuckDBEngine,
)
+from marimo._sql.engines.ibis import IbisEngine
from marimo._sql.engines.sqlalchemy import SQLAlchemyEngine
from marimo._sql.get_engines import (
engine_to_data_source_connection,
@@ -24,6 +25,7 @@ from marimo._sql.get_engines import (
from marimo._sql.sql import sql
HAS_SQLALCHEMY = DependencyManager.sqlalchemy.has()
+HAS_IBIS = DependencyManager.ibis.has()
HAS_DUCKDB = DependencyManager.duckdb.has()
HAS_CLICKHOUSE = DependencyManager.chdb.has()
@@ -74,6 +76,22 @@ def test_engine_to_data_source_connection() -> None:
assert connection.name == "my_postgres"
assert connection.display_name == "postgresql (my_postgres)"
+ # Test with Ibis engine
+ var_name = "my_ibis"
+ backend_name = "duckdb"
+ backend_class = MagicMock
+ mock_ibis_backend = MagicMock()
+ mock_ibis_backend.dialect = backend_class
+ mock_ibis_backend.dialect.classes = {backend_name: backend_class}
+
+ ibis_engine = IbisEngine(mock_ibis_backend)
+ connection = engine_to_data_source_connection(var_name, ibis_engine)
+ assert isinstance(connection, DataSourceConnection)
+ assert connection.source == "ibis"
+ assert connection.dialect == backend_name
+ assert connection.name == var_name
+ assert connection.display_name == f"{backend_name} ({var_name})"
+
@pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")
def test_get_engines_from_variables_duckdb():
@@ -120,6 +138,21 @@ def test_get_engines_from_variables_sqlalchemy() -> None:
assert isinstance(engine, SQLAlchemyEngine)
[email protected](not HAS_IBIS, reason="Ibis not installed")
+def test_get_engines_from_variables_ibis() -> None:
+ import ibis
+
+ ibis_backend = ibis.duckdb.connect()
+ variables: list[tuple[str, object]] = [("ibis_backend", ibis_backend)]
+
+ engines = get_engines_from_variables(variables)
+
+ assert len(engines) == 1
+ var_name, engine = engines[0]
+ assert var_name == "ibis_backend"
+ assert isinstance(engine, IbisEngine)
+
+
def test_get_engines_from_variables_mixed():
variables: list[tuple[str, object]] = [
("not_an_engine", "some string"),
@@ -131,28 +164,31 @@ def test_get_engines_from_variables_mixed():
@pytest.mark.skipif(
- not (HAS_SQLALCHEMY and HAS_DUCKDB and HAS_CLICKHOUSE),
- reason="SQLAlchemy or DuckDB not installed",
+ not (HAS_SQLALCHEMY and HAS_DUCKDB and HAS_CLICKHOUSE and HAS_IBIS),
+ reason="SQLAlchemy, Clickhouse, Ibis, or DuckDB not installed",
)
def test_get_engines_from_variables_multiple():
import chdb
import duckdb
+ import ibis
import sqlalchemy as sa
mock_duckdb_conn = MagicMock(spec=duckdb.DuckDBPyConnection)
mock_clickhouse = MagicMock(spec=chdb.state.sqlitelike.Connection)
sqlalchemy_engine = sa.create_engine("sqlite:///:memory:")
+ ibis_backend = ibis.duckdb.connect()
variables: list[tuple[str, object]] = [
("sa_engine", sqlalchemy_engine),
("duckdb_conn", mock_duckdb_conn),
("clickhouse_conn", mock_clickhouse),
+ ("ibis_backend", ibis_backend),
("not_an_engine", "some string"),
]
engines = get_engines_from_variables(variables)
- assert len(engines) == 3
+ assert len(engines) == 4
# Check SQLAlchemy engine
sa_var_name, _sa_engine = next(
@@ -176,6 +212,12 @@ def test_get_engines_from_variables_multiple():
)
assert ch_var_name == "clickhouse_conn"
+ # Check Clickhouse engine
+ ibis_var_name, _ibis_engine = next(
+ (name, eng) for name, eng in engines if isinstance(eng, IbisEngine)
+ )
+ assert ibis_var_name == "ibis_backend"
+
@pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")
def test_get_engines_duckdb_databases() -> None:
@@ -248,6 +290,32 @@ def test_get_engines_sqlalchemy_databases() -> None:
]
[email protected](not HAS_IBIS, reason="Ibis not installed")
+def test_get_engines_ibis_databases() -> None:
+ import ibis
+
+ ibis_backend = ibis.duckdb.connect()
+ engine = IbisEngine(ibis_backend)
+
+ connection = engine_to_data_source_connection("my_ibis", engine)
+ assert isinstance(connection, DataSourceConnection)
+
+ assert connection.source == "ibis"
+ assert connection.dialect == "duckdb"
+ assert connection.name == "my_ibis"
+ assert connection.display_name == "duckdb (my_ibis)"
+ assert connection.default_database == "memory"
+ assert connection.default_schema == "main"
+
+ assert connection.databases == [
+ Database(
+ name="memory",
+ dialect="duckdb",
+ schemas=[Schema(name="main", tables=[])],
+ )
+ ]
+
+
@pytest.mark.skipif(not HAS_CLICKHOUSE, reason="Clickhouse not installed")
def test_get_engines_clickhouse() -> None:
import chdb
diff --git a/tests/_sql/test_ibis.py b/tests/_sql/test_ibis.py
new file mode 100644
index 0000000000..da8ad69140
--- /dev/null
+++ b/tests/_sql/test_ibis.py
@@ -0,0 +1,728 @@
+"""Tests for Ibis engines."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+from unittest import mock
+
+import pytest
+
+from marimo._data.models import Database, DataTable, DataTableColumn, Schema
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._sql.engines.ibis import IbisEngine, IbisToMarimoConversionError
+from marimo._sql.sql import sql
+from marimo._types.ids import VariableName
+
+HAS_IBIS = DependencyManager.ibis.has()
+HAS_POLARS = DependencyManager.polars.has()
+HAS_PANDAS = DependencyManager.pandas.has()
+
+if TYPE_CHECKING:
+ from ibis.backends.sql import SQLBackend
+
+
+UNUSED_DB_NAME = "unused_db_name"
+
+
+def empty_ibis_backend() -> SQLBackend:
+ """Create an empty in-memory DuckDB database for testing with Ibis."""
+ import ibis
+
+ backend = ibis.duckdb.connect()
+ return backend
+
+
+def ibis_backend() -> SQLBackend:
+ """Create an in-memory DuckDB database for testing with Ibis."""
+
+ import ibis
+
+ backend = ibis.duckdb.connect()
+
+ data_table = ibis.memtable(
+ {"id": [1, 2, 3], "name": ["Alice", "Bob", "Charlie"]}
+ )
+
+ backend.create_table("test", obj=data_table)
+
+ backend.create_database("my_schema")
+ backend.create_table(
+ "test2",
+ schema=ibis.schema({"id": "int", "name": "str"}),
+ database="my_schema",
+ )
+
+ # Test if mo.sql works
+ sql("SELECT * FROM test", engine=backend)
+ return backend
+
+
+def get_expected_table(
+ table_name: str, include_table_details: bool = True
+) -> DataTable:
+ "This test can be reused for ibis_backend"
+ return DataTable(
+ source_type="connection",
+ source="ibis",
+ name=table_name,
+ num_rows=None,
+ num_columns=2 if include_table_details else None,
+ variable_name=None,
+ engine=VariableName("my_ibis"),
+ primary_keys=None,
+ indexes=None,
+ columns=[
+ DataTableColumn(
+ name="id",
+ type="integer",
+ external_type="int64",
+ sample_values=[],
+ ),
+ DataTableColumn(
+ name="name",
+ type="string",
+ external_type="string",
+ sample_values=[],
+ ),
+ ]
+ if include_table_details
+ else [],
+ )
+
+
+def get_expected_schema(schema_name: str, table_name: str) -> Schema:
+ return Schema(
+ name=schema_name,
+ tables=[get_expected_table(table_name)],
+ )
+
+
[email protected](not HAS_IBIS, reason="Ibis not installed")
+def test_engine_compatibility() -> None:
+ """Test engine compatibility checks."""
+ from ibis.backends.sql import SQLBackend
+
+ obj = object()
+ mock_ibis = mock.MagicMock(spec=SQLBackend)
+
+ assert IbisEngine.is_compatible(mock_ibis)
+ assert not IbisEngine.is_compatible(obj)
+
+
[email protected](not HAS_IBIS, reason="Ibis not installed")
+def test_engine_name_initialization() -> None:
+ import ibis
+
+ ibis_backend = ibis.duckdb.connect() # in-memory connection
+ ibis_engine = IbisEngine(ibis_backend, engine_name="my_ibis")
+ assert ibis_engine._engine_name == "my_ibis"
+
+ # Test default name
+ ibis_engine = IbisEngine(ibis_backend)
+ assert ibis_engine._engine_name is None
+
+
[email protected](not HAS_IBIS, reason="Ibis not installed")
+def test_ibis_engine_source_and_dialect() -> None:
+ """Test IbisEngine source and dialect properties."""
+ import ibis
+
+ sqlite_con = ibis.sqlite.connect() # in-memory
+ sqlite_engine = IbisEngine(sqlite_con)
+ assert sqlite_engine.source == "ibis"
+ assert sqlite_engine.dialect == "sqlite"
+
+ duckdb_con = ibis.duckdb.connect() # in-memory
+ duckdb_engine = IbisEngine(duckdb_con)
+ assert duckdb_engine.source == "ibis"
+ assert duckdb_engine.dialect == "duckdb"
+
+
[email protected](not HAS_IBIS, reason="Ibis not installed")
+def test_ibis_engine_get_database_name(ibis_backend: SQLBackend) -> None:
+ """Test IbisEngine get_database_name."""
+ engine = IbisEngine(ibis_backend, engine_name=VariableName("my_ibis"))
+ assert engine.get_default_database() == "memory"
+
+
[email protected](not HAS_IBIS, reason="Ibis not installed")
+def test_ibis_invalid_engine() -> None:
+ """Test IbisEngine with an invalid backend and inspector does not raise errors."""
+
+ engine = IbisEngine(connection=None, engine_name=None) # type: ignore
+ assert engine._backend is None
+ assert engine.default_database is None
+ assert engine.default_schema is None
+
+
[email protected](not HAS_IBIS, reason="Ibis not installed")
+def test_ibis_empty_engine(empty_ibis_backend: SQLBackend) -> None:
+ """Test IbisEngine with an empty engine."""
+ engine_name = VariableName("my_ibis")
+ engine = IbisEngine(connection=empty_ibis_backend, engine_name=engine_name)
+
+ databases = engine.get_databases(
+ include_schemas=True, include_tables=True, include_table_details=True
+ )
+ assert databases == [
+ Database(
+ name="memory",
+ dialect="duckdb",
+ schemas=[Schema(name="main", tables=[])],
+ engine=engine_name,
+ )
+ ]
+
+ tables = engine.get_tables_in_schema(
+ schema="main", database=UNUSED_DB_NAME, include_table_details=False
+ )
+ assert tables == []
+
+ table_info = engine.get_table_details(
+ table_name="test", schema_name="main", database_name=UNUSED_DB_NAME
+ )
+ assert table_info is None
+
+
[email protected](not HAS_IBIS, reason="Ibis not installed")
+def test_ibis_sql_types() -> None:
+ import ibis
+ import ibis.expr.datatypes as dt
+
+ ALL_TYPES = (
+ dt.Boolean(),
+ dt.Int8(),
+ dt.Int16(),
+ dt.Int32(),
+ dt.Int64(),
+ dt.UInt8(),
+ dt.UInt16(),
+ dt.UInt32(),
+ dt.UInt64(),
+ dt.Float16(),
+ dt.Float32(),
+ dt.Float64(),
+ dt.Decimal(),
+ dt.Binary(),
+ dt.String(),
+ dt.Date(),
+ dt.Time(),
+ dt.Timestamp(),
+ dt.Interval(unit="D"),
+ dt.Array(value_type=dt.Int32()),
+ dt.Map(key_type=dt.String(), value_type=dt.Int32()),
+ dt.Struct(fields={"foo": dt.Int32()}),
+ dt.JSON(),
+ dt.MACADDR(),
+ dt.UUID(),
+ # dt.Null(), # not supported in duckdb
+ # dt.MultiLineString(), # is a duckdb extension
+ # dt.MultiPoint(), # is a duckdb extension
+ # dt.MultiPolygon(), # is a duckdb extension
+ # dt.Point(), # is a duckdb extension
+ # dt.Polygon(), # is a duckdb extension
+ )
+ expected_external_type = {
+ str(dt.Boolean()): "boolean",
+ str(dt.Int8()): "int8",
+ str(dt.Int16()): "int16",
+ str(dt.Int32()): "int32",
+ str(dt.Int64()): "int64",
+ str(dt.UInt8()): "uint8",
+ str(dt.UInt16()): "uint16",
+ str(dt.UInt32()): "uint32",
+ str(dt.UInt64()): "uint64",
+ str(dt.Float16()): "float32", # duckdb does not support float16
+ str(dt.Float32()): "float32",
+ str(dt.Float64()): "float64",
+ str(
+ dt.Decimal()
+ ): "decimal(18, 3)", # duckdb sets default precision and scale
+ str(dt.Binary()): "binary",
+ str(dt.String()): "string",
+ str(dt.Date()): "date",
+ str(dt.Time()): "time",
+ str(dt.Timestamp()): "timestamp(6)", # duckdb sets default precision
+ str(dt.Interval(unit="D")): "interval('us')",
+ str(dt.Array(value_type=dt.Int32())): "array<int32>",
+ str(
+ dt.Map(key_type=dt.String(), value_type=dt.Int32())
+ ): "map<string, int32>",
+ str(dt.Struct(fields={"foo": dt.Int32()})): "struct<foo: int32>",
+ str(dt.JSON()): "json",
+ str(dt.MACADDR()): "string",
+ str(dt.UUID()): "uuid",
+ }
+ expected_marimo_type = {
+ str(dt.Boolean()): "boolean",
+ str(dt.Int8()): "integer",
+ str(dt.Int16()): "integer",
+ str(dt.Int32()): "integer",
+ str(dt.Int64()): "integer",
+ str(dt.UInt8()): "integer",
+ str(dt.UInt16()): "integer",
+ str(dt.UInt32()): "integer",
+ str(dt.UInt64()): "integer",
+ str(dt.Float16()): "number",
+ str(dt.Float32()): "number",
+ str(dt.Float64()): "number",
+ str(dt.Decimal()): "number",
+ str(dt.Binary()): "string",
+ str(dt.String()): "string",
+ str(dt.Date()): "date",
+ str(dt.Time()): "time",
+ str(dt.Timestamp()): "datetime",
+ str(dt.Interval(unit="D")): "string", # default case
+ str(dt.Array(value_type=dt.Int32())): "string", # default case
+ str(
+ dt.Map(key_type=dt.String(), value_type=dt.Int32())
+ ): "string", # default case
+ str(dt.Struct(fields={"foo": dt.Int32()})): "string", # default case
+ str(dt.JSON()): "string", # default case
+ str(dt.MACADDR()): "string", # default case
+ str(dt.UUID()): "string", # default case
+ }
+
+ ibis_backend = ibis.duckdb.connect()
+ schema = ibis.schema({str(t): t for t in ALL_TYPES})
+ ibis_backend.create_table("all_types", schema=schema)
+
+ engine = IbisEngine(ibis_backend, engine_name=VariableName("my_ibis"))
+ tables = engine.get_tables_in_schema(
+ schema="main", database="memory", include_table_details=True
+ )
+
+ assert len(tables) == 1
+ table = tables[0]
+ assert table.source == "ibis"
+ assert table.name == "all_types"
+ assert table.num_columns == 25
+ assert table.num_rows is None
+
+ for column in table.columns:
+ assert column.name in expected_marimo_type.keys()
+ assert column.type == expected_marimo_type[column.name]
+ assert column.external_type == expected_external_type[column.name]
+
+
[email protected](not HAS_IBIS, reason="Ibis not installed")
+def test_ibis_type_conversion() -> None:
+ """Test IbisEngine _ibis_to_marimo_dtype.
+
+ The IbisToMarimoConversionError should be caught by calling function (e.g., .get_table_details())
+ Attempts to exhaustively test type conversion
+
+ reference: https://ibis-project.org/reference/datatypes
+ """
+ import ibis.expr.datatypes as dt
+
+ to_marimo = IbisEngine._ibis_to_marimo_dtype
+
+ assert to_marimo(dt.Boolean()) == "boolean"
+
+ assert to_marimo(dt.Int8()) == "integer"
+ assert to_marimo(dt.Int16()) == "integer"
+ assert to_marimo(dt.Int32()) == "integer"
+ assert to_marimo(dt.Int64()) == "integer"
+ assert to_marimo(dt.UInt8()) == "integer"
+ assert to_marimo(dt.UInt16()) == "integer"
+ assert to_marimo(dt.UInt32()) == "integer"
+ assert to_marimo(dt.UInt64()) == "integer"
+
+ assert to_marimo(dt.Decimal()) == "number"
+ assert to_marimo(dt.Float16()) == "number"
+ assert to_marimo(dt.Float32()) == "number"
+ assert to_marimo(dt.Float64()) == "number"
+
+ # Binary is a sequence of bytes
+ assert to_marimo(dt.Binary()) == "string"
+ assert to_marimo(dt.String()) == "string"
+
+ # temporal
+ assert to_marimo(dt.Date()) == "date"
+ assert to_marimo(dt.Time()) == "time"
+ assert to_marimo(dt.Timestamp()) == "datetime"
+
+ # unhandled cases will be converted to string
+ with pytest.raises(IbisToMarimoConversionError):
+ to_marimo(dt.Interval(unit="D"))
+
+ # nested types
+ with pytest.raises(IbisToMarimoConversionError):
+ to_marimo(dt.Array(value_type=dt.Int32()))
+
+ with pytest.raises(IbisToMarimoConversionError):
+ to_marimo(dt.Map(key_type=dt.String(), value_type=dt.Int32()))
+
+ with pytest.raises(IbisToMarimoConversionError):
+ to_marimo(dt.Struct(fields={"foo": dt.Int32()}))
+
+ # geometry
+ with pytest.raises(IbisToMarimoConversionError):
+ to_marimo(dt.MultiLineString())
+
+ with pytest.raises(IbisToMarimoConversionError):
+ to_marimo(dt.MultiPoint())
+
+ with pytest.raises(IbisToMarimoConversionError):
+ to_marimo(dt.MultiPolygon())
+
+ with pytest.raises(IbisToMarimoConversionError):
+ to_marimo(dt.Null())
+
+ with pytest.raises(IbisToMarimoConversionError):
+ to_marimo(dt.Point())
+
+ with pytest.raises(IbisToMarimoConversionError):
+ to_marimo(dt.Polygon())
+
+ # special types
+ with pytest.raises(IbisToMarimoConversionError):
+ to_marimo(dt.JSON())
+
+ with pytest.raises(IbisToMarimoConversionError):
+ to_marimo(dt.MACADDR())
+
+ with pytest.raises(IbisToMarimoConversionError):
+ to_marimo(dt.UUID())
+
+
[email protected](not HAS_IBIS, reason="Ibis not installed")
+def test_ibis_engine_get_table_details(ibis_backend: SQLBackend) -> None:
+ """Test IbisEngine get_table method."""
+ engine = IbisEngine(ibis_backend, engine_name=VariableName("my_ibis"))
+ table = engine.get_table_details(
+ table_name="test", schema_name="main", database_name="memory"
+ )
+ assert table == get_expected_table("test")
+
+ # different schema
+ table = engine.get_table_details(
+ table_name="test2",
+ schema_name="my_schema",
+ database_name="memory",
+ )
+ assert table == get_expected_table("test2")
+
+ # non-existent table
+ assert (
+ engine.get_table_details(
+ table_name="non_existent",
+ schema_name="main",
+ database_name="memory",
+ )
+ is None
+ )
+
+ # non-existent schema
+ assert (
+ engine.get_table_details(
+ table_name="test",
+ schema_name="non_existent",
+ database_name="memory",
+ )
+ is None
+ )
+
+
[email protected](not HAS_IBIS, reason="Ibis not installed")
+def test_ibis_engine_get_tables_in_schema(ibis_backend: SQLBackend) -> None:
+ """Test IbisEngine get_tables method."""
+ engine = IbisEngine(ibis_backend, engine_name=VariableName("my_ibis"))
+ tables = engine.get_tables_in_schema(
+ schema="main", database="memory", include_table_details=True
+ )
+
+ assert isinstance(tables, list)
+ assert len(tables) == 1
+ assert tables[0] == get_expected_table("test")
+
+ # Test with other schema
+ tables = engine.get_tables_in_schema(
+ schema="my_schema", database="memory", include_table_details=True
+ )
+ assert isinstance(tables, list)
+ assert len(tables) == 1
+ assert tables[0] == get_expected_table("test2")
+
+ # Test with non-existent schema
+ assert (
+ engine.get_tables_in_schema(
+ schema="non_existent",
+ database="memory",
+ include_table_details=True,
+ )
+ == []
+ )
+
+ # Test with include_table_details false
+ tables = engine.get_tables_in_schema(
+ schema="main", database="memory", include_table_details=False
+ )
+ assert isinstance(tables, list)
+ assert len(tables) == 1
+ expected_table = get_expected_table("test", False)
+ assert tables[0] == expected_table
+
+
[email protected](not HAS_IBIS, reason="Ibis not installed")
+def test_ibis_engine_get_schemas(ibis_backend: SQLBackend) -> None:
+ """Test IbisEngine get_schemas method."""
+ var_name = VariableName("my_ibis")
+ engine = IbisEngine(ibis_backend, engine_name=var_name)
+ schemas = engine._get_schemas(
+ database="memory",
+ include_tables=True,
+ include_table_details=True,
+ )
+
+ assert isinstance(schemas, list)
+ assert len(schemas) == 2
+
+ schema = schemas[0]
+ assert schema == get_expected_schema("main", "test")
+
+ schema = schemas[1]
+ assert schema == get_expected_schema("my_schema", "test2")
+
+ # Test with include_table_details false
+ schemas = engine._get_schemas(
+ database="memory",
+ include_tables=True,
+ include_table_details=False,
+ )
+ assert isinstance(schemas, list)
+ assert len(schemas) == 2
+
+ schema = schemas[0]
+ assert schema.name == "main"
+ assert len(schema.tables) == 1
+
+ expected_table = get_expected_table("test", include_table_details=False)
+ assert schema.tables[0] == expected_table
+
+ # Test with include_tables false
+ schemas = engine._get_schemas(
+ database="memory",
+ include_tables=False,
+ include_table_details=True,
+ )
+ assert isinstance(schemas, list)
+ assert len(schemas) == 2
+
+ schema = schemas[0]
+ assert schema.name == "main"
+ assert len(schema.tables) == 0
+
+ schema = schemas[1]
+ assert schema.name == "my_schema"
+ assert len(schema.tables) == 0
+
+
[email protected](not HAS_IBIS, reason="Ibis not installed")
+def test_ibis_engine_get_databases(ibis_backend: SQLBackend) -> None:
+ """Test IbisEngine get_databases method."""
+ var_name = VariableName("my_ibis")
+ engine = IbisEngine(ibis_backend, engine_name=var_name)
+ databases = engine.get_databases(
+ include_schemas=True, include_tables=True, include_table_details=True
+ )
+
+ assert databases == [
+ Database(
+ name="memory",
+ dialect="duckdb",
+ schemas=[
+ get_expected_schema("main", "test"),
+ get_expected_schema("my_schema", "test2"),
+ ],
+ engine=var_name,
+ )
+ ]
+
+ # Test with include_table_details false
+ databases = engine.get_databases(
+ include_schemas=True, include_tables=True, include_table_details=False
+ )
+ tables_main = get_expected_table("test", include_table_details=False)
+ tables_my_schema = get_expected_table("test2", include_table_details=False)
+
+ assert databases == [
+ Database(
+ name="memory",
+ dialect="duckdb",
+ schemas=[
+ Schema(name="main", tables=[tables_main]),
+ Schema(name="my_schema", tables=[tables_my_schema]),
+ ],
+ engine=var_name,
+ )
+ ]
+
+ # Test with include_tables false
+ databases = engine.get_databases(
+ include_schemas=True, include_tables=False, include_table_details=True
+ )
+ assert databases == [
+ Database(
+ name="memory",
+ dialect="duckdb",
+ schemas=[
+ Schema(name="main", tables=[]),
+ Schema(name="my_schema", tables=[]),
+ ],
+ engine=var_name,
+ )
+ ]
+
+ # Test with include_schemas false
+ databases = engine.get_databases(
+ include_schemas=False, include_tables=True, include_table_details=True
+ )
+ assert databases == [
+ Database(
+ name="memory",
+ dialect="duckdb",
+ schemas=[],
+ engine=var_name,
+ )
+ ]
+
+ # Test with include_schemas and include_tables false
+ databases = engine.get_databases(
+ include_schemas=False, include_tables=False, include_table_details=True
+ )
+ assert databases == [
+ Database(
+ name="memory",
+ dialect="duckdb",
+ schemas=[],
+ engine=var_name,
+ )
+ ]
+
+
[email protected](not HAS_IBIS, reason="Ibis not installed")
+def test_ibis_engine_get_databases_auto(ibis_backend: SQLBackend) -> None:
+ """Test IbisEngine get_databases method with 'auto' option."""
+ var_name = VariableName("my_ibis")
+ engine = IbisEngine(ibis_backend, engine_name=var_name)
+
+ # 'auto' should behave like True
+ databases = engine.get_databases(
+ include_schemas="auto",
+ include_tables="auto",
+ include_table_details="auto",
+ )
+
+ # Should be equivalent to setting all params to True
+ tables_main = get_expected_table("test", include_table_details=True)
+ tables_my_schema = get_expected_table("test2", include_table_details=True)
+ assert tables_main.columns == tables_my_schema.columns
+ assert tables_main.primary_keys == tables_my_schema.primary_keys
+ assert databases == [
+ Database(
+ name="memory",
+ dialect="duckdb",
+ schemas=[
+ get_expected_schema("main", "test"),
+ get_expected_schema("my_schema", "test2"),
+ ],
+ engine=var_name,
+ )
+ ]
+
+ # Test with a mock to simulate a non-cheap dialect
+ with mock.patch.object(
+ IbisEngine, "_is_cheap_discovery", return_value=False
+ ):
+ # For a non-cheap dialect, 'auto' should behave like False
+ databases = engine.get_databases(
+ include_schemas="auto",
+ include_tables="auto",
+ include_table_details="auto",
+ )
+
+ assert databases == [
+ Database(
+ name="memory",
+ dialect="duckdb",
+ schemas=[],
+ engine=var_name,
+ )
+ ]
+
+
+ not HAS_IBIS or not (HAS_PANDAS or HAS_POLARS),
+ reason="Ibis and either pandas or polars not installed",
+)
+def test_ibis_engine_execute(ibis_backend: SQLBackend) -> None:
+ """Test Ibis execute."""
+ import pandas as pd
+ import polars as pl
+
+ engine = IbisEngine(ibis_backend, engine_name=VariableName("my_ibis"))
+ result = engine.execute("SELECT * FROM test ORDER BY id")
+ assert isinstance(result, (pd.DataFrame, pl.DataFrame))
+ assert len(result) == 3
+
+
+ not HAS_IBIS or not HAS_POLARS or not HAS_PANDAS,
+ reason="Ibis, Polars, and Pandas not installed",
+)
+def test_ibis_engine_sql_output_formats(ibis_backend: SQLBackend) -> None:
+ """Test IbisEngine execute with different SQL output formats."""
+ import pandas as pd
+ import polars as pl
+ from ibis import Expr
+
+ # Test with polars output format
+ with mock.patch.object(
+ IbisEngine, "sql_output_format", return_value="polars"
+ ):
+ engine = IbisEngine(ibis_backend, engine_name=VariableName("my_ibis"))
+ result = engine.execute("SELECT * FROM test ORDER BY id")
+ assert isinstance(result, pl.DataFrame)
+ assert len(result) == 3
+
+ # Test with lazy-polars output format
+ with mock.patch.object(
+ IbisEngine, "sql_output_format", return_value="lazy-polars"
+ ):
+ engine = IbisEngine(ibis_backend, engine_name=VariableName("my_ibis"))
+ result = engine.execute("SELECT * FROM test ORDER BY id")
+ assert isinstance(result, pl.LazyFrame)
+ assert len(result.collect()) == 3
+
+ # Test with pandas output format
+ with mock.patch.object(
+ IbisEngine, "sql_output_format", return_value="pandas"
+ ):
+ engine = IbisEngine(ibis_backend, engine_name=VariableName("my_ibis"))
+ result = engine.execute("SELECT * FROM test ORDER BY id")
+ assert isinstance(result, pd.DataFrame)
+ assert len(result) == 3
+
+ # Test with native output format
+ with mock.patch.object(
+ IbisEngine, "sql_output_format", return_value="native"
+ ):
+ engine = IbisEngine(ibis_backend, engine_name=VariableName("my_ibis"))
+ result = engine.execute("SELECT * FROM test ORDER BY id")
+ assert not isinstance(
+ result, (pd.DataFrame, pl.DataFrame, pl.LazyFrame)
+ )
+ assert isinstance(result, Expr)
+
+ # Test with auto output format (should use polars if available)
+ with mock.patch.object(
+ IbisEngine, "sql_output_format", return_value="auto"
+ ):
+ engine = IbisEngine(ibis_backend, engine_name=VariableName("my_ibis"))
+ result = engine.execute("SELECT * FROM test ORDER BY id")
+ assert isinstance(result, (pd.DataFrame, pl.DataFrame))
+ assert len(result) == 3
diff --git a/tests/_sql/test_sql.py b/tests/_sql/test_sql.py
index 220bb97d86..9a30749377 100644
--- a/tests/_sql/test_sql.py
+++ b/tests/_sql/test_sql.py
@@ -10,6 +10,7 @@ import pytest
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins import ui
+from marimo._sql.engines.ibis import IbisEngine
from marimo._sql.engines.sqlalchemy import SQLAlchemyEngine
from marimo._sql.sql import _query_includes_limit, sql
@@ -22,6 +23,7 @@ if TYPE_CHECKING:
HAS_DUCKDB = DependencyManager.duckdb.has()
HAS_SQLALCHEMY = DependencyManager.sqlalchemy.has()
+HAS_IBIS = DependencyManager.ibis.has()
HAS_POLARS = DependencyManager.polars.has()
HAS_PANDAS = DependencyManager.pandas.has()
HAS_SQLGLOT = DependencyManager.sqlglot.has()
@@ -343,3 +345,18 @@ def test_sql_with_cursor_result(sqlite_engine: sa.Engine):
):
result = sql("SELECT * FROM test", engine=sqlite_engine)
assert isinstance(result, CursorResult)
+
+
[email protected](not HAS_IBIS, reason="Ibis not installed")
+def test_sql_with_ibis_expression_result():
+ import ibis
+ from ibis import Expr
+
+ duckdb_backend = ibis.duckdb.connect() # in-memory
+ # Create a test table with data
+ data_table = ibis.memtable({"id": [1, 2], "name": ["test1", "test2"]})
+ duckdb_backend.create_table("test", obj=data_table)
+
+ with patch.object(IbisEngine, "sql_output_format", return_value="native"):
+ result = sql("SELECT * FROM test", engine=duckdb_backend)
+ assert isinstance(result, Expr)