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: Support DB API as a SQL connection (#5027)

Myles Scolnick02fadd1bacd5
diff --git a/frontend/src/components/databases/icon.tsx b/frontend/src/components/databases/icon.tsx
index eb87ab58f9..a587be6e6e 100644
--- a/frontend/src/components/databases/icon.tsx
+++ b/frontend/src/components/databases/icon.tsx
@@ -15,6 +15,7 @@ import IcebergIcon from "./icons/iceberg.png";
import DataFusionIcon from "./icons/datafusion.png";
import PySparkIcon from "./icons/spark.svg";
import { cn } from "@/utils/cn";
+import { DatabaseIcon } from "lucide-react";
export type DBLogoName =
| "sqlite"
@@ -66,7 +67,8 @@ export const DatabaseLogo: FC<DatabaseLogoProps> = ({ name, className }) => {
const url = URLS[lowerName as DBLogoName];
if (!url) {
- return null;
+ // Shift the icon down a bit to align with the text
+ return <DatabaseIcon className={cn("mt-0.5", className)} />;
}
return (
diff --git a/frontend/src/components/datasources/components.tsx b/frontend/src/components/datasources/components.tsx
index 48cc78e401..54702931f3 100644
--- a/frontend/src/components/datasources/components.tsx
+++ b/frontend/src/components/datasources/components.tsx
@@ -14,7 +14,7 @@ export const DatasourceLabel: React.FC<{
children: React.ReactNode;
}> = ({ children }) => {
return (
- <div className="flex gap-1 items-center font-bold px-2 py-1.5 text-muted-foreground bg-[var(--slate-2)] text-sm">
+ <div className="flex gap-1.5 items-center font-bold px-2 py-1.5 text-muted-foreground bg-[var(--slate-2)] text-sm">
{children}
</div>
);
diff --git a/frontend/src/components/datasources/datasources.tsx b/frontend/src/components/datasources/datasources.tsx
index c3e01aff80..afc5b934e3 100644
--- a/frontend/src/components/datasources/datasources.tsx
+++ b/frontend/src/components/datasources/datasources.tsx
@@ -60,6 +60,7 @@ import { dbDisplayName } from "@/components/databases/display";
import { AddDatabaseDialog } from "../editor/database/add-database-form";
import {
dataConnectionsMapAtom,
+ DUCKDB_ENGINE,
INTERNAL_SQL_ENGINES,
type SQLTableContext,
useDataSourceActions,
@@ -219,7 +220,7 @@ export const DataSources: React.FC = () => {
{dataConnections.length > 0 && tables.length > 0 && (
<DatasourceLabel>
<PythonIcon className="h-4 w-4 text-muted-foreground" />
- <span>Python</span>
+ <span className="text-xs">Python</span>
</DatasourceLabel>
)}
{tables.length > 0 && (
@@ -235,10 +236,8 @@ const Engine: React.FC<{
children: React.ReactNode;
hasChildren?: boolean;
}> = ({ connection, children, hasChildren }) => {
- // The internal DuckDB engine may have no engine name, so we provide one.
- // The connection is also updated automatically, so we do not need to refresh.
- const internalEngine =
- connection.databases.length === 0 || !connection.databases[0]?.engine;
+ // The internal duckdb connection is updated automatically, so we do not need to refresh.
+ const internalEngine = connection.name === DUCKDB_ENGINE;
const engineName = internalEngine ? "In-Memory" : connection.name;
const [isSpinning, setIsSpinning] = React.useState(false);
@@ -259,7 +258,7 @@ const Engine: React.FC<{
className="h-4 w-4 text-muted-foreground"
name={connection.dialect}
/>
- <span>{dbDisplayName(connection.dialect)}</span>
+ <span className="text-xs">{dbDisplayName(connection.dialect)}</span>
<span className="text-xs text-muted-foreground">
(<EngineVariable variableName={engineName as VariableName} />)
</span>
diff --git a/frontend/src/core/codemirror/language/__tests__/extension.test.ts b/frontend/src/core/codemirror/language/__tests__/extension.test.ts
index ffd25541ae..3425971742 100644
--- a/frontend/src/core/codemirror/language/__tests__/extension.test.ts
+++ b/frontend/src/core/codemirror/language/__tests__/extension.test.ts
@@ -12,6 +12,7 @@ import { EditorView } from "@codemirror/view";
import type { CellId } from "@/core/cells/ids";
import { cellConfigExtension } from "../../config/extension";
import { languageMetadataField } from "../metadata";
+import { DUCKDB_ENGINE } from "@/core/datasets/data-source-connections";
function createState(content: string, selection?: { anchor: number }) {
const state = EditorState.create({
@@ -189,7 +190,7 @@ describe("switchLanguage", () => {
{
"commentLines": [],
"dataframeName": "_df",
- "engine": "__marimo_duckdb",
+ "engine": "${DUCKDB_ENGINE}",
"quotePrefix": "f",
"showOutput": true,
}
@@ -227,7 +228,7 @@ describe("switchLanguage", () => {
expect(mockEditor.state.field(languageMetadataField)).toEqual({
commentLines: [],
dataframeName: "_df",
- engine: "__marimo_duckdb",
+ engine: DUCKDB_ENGINE,
quotePrefix: "f",
showOutput: true,
});
diff --git a/frontend/src/core/codemirror/language/__tests__/sql.test.ts b/frontend/src/core/codemirror/language/__tests__/sql.test.ts
index f4dd54df2d..c3f5927276 100644
--- a/frontend/src/core/codemirror/language/__tests__/sql.test.ts
+++ b/frontend/src/core/codemirror/language/__tests__/sql.test.ts
@@ -26,7 +26,7 @@ describe("SQLLanguageAdapter", () => {
{
"commentLines": [],
"dataframeName": "_df",
- "engine": "__marimo_duckdb",
+ "engine": "${DUCKDB_ENGINE}",
"quotePrefix": "f",
"showOutput": true,
}
diff --git a/frontend/src/core/datasets/data-source-connections.ts b/frontend/src/core/datasets/data-source-connections.ts
index 658f2d8c65..2b0a032218 100644
--- a/frontend/src/core/datasets/data-source-connections.ts
+++ b/frontend/src/core/datasets/data-source-connections.ts
@@ -14,8 +14,9 @@ import { isSchemaless } from "@/components/datasources/utils";
export type ConnectionName = TypedString<"ConnectionName">;
-// duckdb engine is treated as the default engine
-// as it doesn't require passing an engine variable to the backend
+// DuckDB engine is treated as the default engine
+// As it doesn't require passing an engine variable to the backend
+// Keep this in sync with the backend name
export const DUCKDB_ENGINE = "__marimo_duckdb" as ConnectionName;
export const INTERNAL_SQL_ENGINES = new Set([DUCKDB_ENGINE]);
diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.py
index 51f16fb5d9..67c1beeee0 100644
--- a/marimo/_runtime/runner/hooks_post_execution.py
+++ b/marimo/_runtime/runner/hooks_post_execution.py
@@ -163,14 +163,16 @@ def _broadcast_data_source_connection(
]
)
- if engines:
- LOGGER.debug("Broadcasting data source connections")
- DataSourceConnections(
- connections=[
- engine_to_data_source_connection(variable, engine)
- for variable, engine in engines
- ]
- ).broadcast()
+ if not engines:
+ return
+
+ LOGGER.debug("Broadcasting data source connections")
+ DataSourceConnections(
+ connections=[
+ engine_to_data_source_connection(variable, engine)
+ for variable, engine in engines
+ ]
+ ).broadcast()
@kernel_tracer.start_as_current_span("broadcast_duckdb_datasource")
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 91950f6167..c81a2c6c70 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -166,7 +166,7 @@ from marimo._secrets.load_dotenv import (
from marimo._secrets.secrets import get_secret_keys
from marimo._server.model import SessionMode
from marimo._server.types import QueueType
-from marimo._sql.engines.types import SQLEngine
+from marimo._sql.engines.types import EngineCatalog
from marimo._sql.get_engines import (
engine_to_data_source_connection,
get_engines_from_variables,
@@ -2220,10 +2220,12 @@ class DatasetCallbacks:
).broadcast()
return
- def _get_sql_engine(
+ def _get_engine_catalog(
self, variable_name: str
- ) -> tuple[Optional[SQLEngine], Optional[str]]:
- """Find the SQL engine associated with the given variable name. Returns the engine and the error message if any."""
+ ) -> tuple[Optional[EngineCatalog[Any]], Optional[str]]:
+ """Fetch the catalog-capable engine associated with the given variable name.
+
+ Returns the engine if it supports catalog operations, or an error message if not."""
variable_name = cast(VariableName, variable_name)
try:
@@ -2232,7 +2234,11 @@ class DatasetCallbacks:
engines = get_engines_from_variables([(variable_name, engine_val)])
if engines is None or len(engines) == 0:
return None, "Engine not found"
- return engines[0][1], None
+ engine = engines[0][1]
+ if isinstance(engine, EngineCatalog):
+ return engine, None
+ else:
+ return None, "Connection does not support catalog operations"
except Exception as e:
LOGGER.warning(
"Failed to get engine %s", variable_name, exc_info=e
@@ -2255,7 +2261,7 @@ class DatasetCallbacks:
schema_name = request.schema
table_name = request.table_name
- engine, error = self._get_sql_engine(variable_name)
+ engine, error = self._get_engine_catalog(variable_name)
if error is not None or engine is None:
SQLTablePreview(
request_id=request.request_id, table=None, error=error
@@ -2300,7 +2306,7 @@ class DatasetCallbacks:
database_name = request.database
schema_name = request.schema
- engine, error = self._get_sql_engine(variable_name)
+ engine, error = self._get_engine_catalog(variable_name)
if error is not None or engine is None:
SQLTableListPreview(
request_id=request.request_id, tables=[], error=error
@@ -2332,7 +2338,7 @@ class DatasetCallbacks:
) -> None:
"""Broadcasts a datasource connection for a given engine"""
variable_name = cast(VariableName, request.engine)
- engine, error = self._get_sql_engine(variable_name)
+ engine, error = self._get_engine_catalog(variable_name)
if error is not None or engine is None:
LOGGER.error("Failed to get engine %s", variable_name)
return
diff --git a/marimo/_smoke_tests/sql/dbapi_sqlite.py b/marimo/_smoke_tests/sql/dbapi_sqlite.py
new file mode 100644
index 0000000000..b3741781cc
--- /dev/null
+++ b/marimo/_smoke_tests/sql/dbapi_sqlite.py
@@ -0,0 +1,51 @@
+import marimo
+
+__generated_with = "0.13.11"
+app = marimo.App(width="medium")
+
+
+def _():
+ import marimo as mo
+ return (mo,)
+
+
+def _():
+ import sqlite3
+ return (sqlite3,)
+
+
+def _(sqlite3):
+ conn = sqlite3.connect(":memory:")
+ conn.execute("""
+ CREATE TABLE test (
+ id INTEGER PRIMARY KEY,
+ name TEXT,
+ value REAL
+ )
+ """)
+ conn.execute("""
+ INSERT INTO test (name, value) VALUES
+ ('a', 1.0),
+ ('b', 2.0),
+ ('c', 3.0)
+ """)
+ return (conn,)
+
+
+
+def _(conn, mo, test):
+ _df = mo.sql(
+ f"""
+ select * FROM test
+ """,
+ engine=conn
+ )
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_sql/engines/clickhouse.py b/marimo/_sql/engines/clickhouse.py
index dbfdfb5141..85a49808fd 100644
--- a/marimo/_sql/engines/clickhouse.py
+++ b/marimo/_sql/engines/clickhouse.py
@@ -16,7 +16,7 @@ from marimo._dependencies.dependencies import DependencyManager
from marimo._sql.engines.types import (
NO_SCHEMA_NAME,
InferenceConfig,
- SQLEngine,
+ SQLConnection,
register_engine,
)
from marimo._sql.utils import raise_df_import_error, sql_type_to_data_type
@@ -36,7 +36,7 @@ WHY_PANDAS_REQUIRED = (
@register_engine
-class ClickhouseEmbedded(SQLEngine):
+class ClickhouseEmbedded(SQLConnection[Optional["ChdbConnection"]]):
"""Use chdb to connect to an embedded Clickhouse"""
def __init__(
@@ -44,8 +44,7 @@ class ClickhouseEmbedded(SQLEngine):
connection: Optional[ChdbConnection] = None,
engine_name: Optional[VariableName] = None,
) -> None:
- self._connection = connection
- self._engine_name = engine_name
+ super().__init__(connection, engine_name)
self._cursor = None if connection is None else connection.cursor()
@property
@@ -214,7 +213,7 @@ class ClickhouseEmbedded(SQLEngine):
@register_engine
-class ClickhouseServer(SQLEngine):
+class ClickhouseServer(SQLConnection[Optional["ClickhouseClient"]]):
"""Use clickhouse.connect to connect to a Clickhouse server"""
def __init__(
@@ -222,8 +221,7 @@ class ClickhouseServer(SQLEngine):
connection: Optional[ClickhouseClient] = None,
engine_name: Optional[VariableName] = None,
) -> None:
- self._connection = connection
- self._engine_name = engine_name
+ super().__init__(connection, engine_name)
self._meta_dbs = ["system", "information_schema"]
@property
diff --git a/marimo/_sql/engines/dbapi.py b/marimo/_sql/engines/dbapi.py
new file mode 100644
index 0000000000..ae25448945
--- /dev/null
+++ b/marimo/_sql/engines/dbapi.py
@@ -0,0 +1,147 @@
+# Copyright 2024 Marimo. All rights reserved.
+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, register_engine
+from marimo._sql.utils import raise_df_import_error
+
+LOGGER = _loggers.marimo_logger()
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+
+class DBAPIConnection(Protocol):
+ def cursor(self) -> Any: ...
+
+ def commit(self) -> None: ...
+
+
+@register_engine
+class DBAPIEngine(QueryEngine[DBAPIConnection]):
+ """DB-API 2.0 (PEP 249) engine."""
+
+ @property
+ def source(self) -> str:
+ return "dbapi"
+
+ @property
+ def dialect(self) -> str:
+ # Try to get dialect from connection
+ try:
+ return str(self._connection.dialect) # type: ignore[attr-defined]
+ except AttributeError:
+ return "sql"
+
+ def execute(
+ self, query: str, parameters: Optional[Sequence[Any]] = None
+ ) -> Any:
+ sql_output_format = self.sql_output_format()
+
+ cursor = self._connection.cursor()
+ should_close = True
+ try:
+ cursor.execute(query, parameters or ())
+
+ if sql_output_format == "native":
+ should_close = False
+ return cursor
+
+ rows = cursor.fetchall() if cursor.description else None
+
+ try:
+ self._connection.commit()
+ except Exception:
+ LOGGER.info("Unable to commit transaction", exc_info=True)
+
+ if rows is None:
+ return None
+
+ # Get column names from cursor description
+ if cursor.description:
+ columns = [col[0] for col in cursor.description]
+ else:
+ columns = []
+
+ def convert_to_polars(rows: list[tuple[Any, ...]]) -> pl.DataFrame:
+ import polars as pl
+
+ data: dict[str, list[Any]] = {col: [] for col in columns}
+ for row in rows:
+ for i, col in enumerate(columns):
+ 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":
+ 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]")
+ finally:
+ if should_close:
+ cursor.close()
+
+ @staticmethod
+ def is_compatible(var: Any) -> bool:
+ """Check if a variable is a DB-API 2.0 compatible connection.
+
+ A DB-API 2.0 connection must have:
+ - cursor() method
+ - commit() method
+ - rollback() method
+ - close() method
+ """
+ try:
+ required_methods = ["cursor", "commit", "rollback", "close"]
+ has_required_methods = all(
+ callable(getattr(var, method, None))
+ for method in required_methods
+ )
+
+ if not has_required_methods:
+ return False
+
+ cursor = var.cursor()
+ cursor_methods = ["execute", "fetchall"]
+ has_cursor_methods = all(
+ callable(getattr(cursor, method, None))
+ for method in cursor_methods
+ )
+
+ return has_required_methods and has_cursor_methods
+
+ except Exception:
+ return False
diff --git a/marimo/_sql/engines/doc.md b/marimo/_sql/engines/doc.md
new file mode 100644
index 0000000000..da1df456b6
--- /dev/null
+++ b/marimo/_sql/engines/doc.md
@@ -0,0 +1,55 @@
+# SQL Engine Architecture
+
+marimo's SQL engine uses a class hierarchy to separate catalog (metadata discovery) and query operations (execution).
+
+## Class Hierarchy
+
+```mermaid
+classDiagram
+ BaseEngine <|-- EngineCatalog
+ BaseEngine <|-- QueryEngine
+ EngineCatalog <|-- SQLConnection
+ QueryEngine <|-- SQLConnection
+
+ class BaseEngine {
+ <<abstract>>
+ +source: str
+ +dialect: str
+ +is_compatible(var: Any): bool
+ }
+
+ class EngineCatalog {
+ <<abstract>>
+ +inference_config: InferenceConfig
+ +get_default_database(): str
+ +get_default_schema(): str
+ +get_databases(): list[Database]
+ +get_tables_in_schema(): list[DataTable]
+ +get_table_details(): DataTable
+ }
+
+ class QueryEngine {
+ <<abstract>>
+ +execute(query: str): Any
+ +sql_output_format(): SqlOutputType
+ }
+
+ class SQLConnection {
+ Implements both catalog and query interfaces
+ }
+```
+
+Examples of just the catalog operations:
+
+- PyIceberg
+
+Examples of just the query operations:
+
+- PEP 249
+
+Examples of both catalog and query operations:
+
+- SQLAlchemy/SQLModel
+- DuckDB
+- Clickhouse
+- Ibis
diff --git a/marimo/_sql/engines/duckdb.py b/marimo/_sql/engines/duckdb.py
index e5de4d98ab..cc346dfdf3 100644
--- a/marimo/_sql/engines/duckdb.py
+++ b/marimo/_sql/engines/duckdb.py
@@ -9,7 +9,7 @@ from marimo._data.models import Database, DataTable
from marimo._dependencies.dependencies import DependencyManager
from marimo._sql.engines.types import (
InferenceConfig,
- SQLEngine,
+ SQLConnection,
register_engine,
)
from marimo._sql.utils import raise_df_import_error, wrapped_sql
@@ -25,7 +25,7 @@ INTERNAL_DUCKDB_ENGINE = cast(VariableName, "__marimo_duckdb")
@register_engine
-class DuckDBEngine(SQLEngine):
+class DuckDBEngine(SQLConnection[Optional["duckdb.DuckDBPyConnection"]]):
"""DuckDB SQL engine."""
def __init__(
@@ -33,8 +33,7 @@ class DuckDBEngine(SQLEngine):
connection: Optional[duckdb.DuckDBPyConnection] = None,
engine_name: Optional[VariableName] = None,
) -> None:
- self._connection = connection
- self._engine_name = engine_name
+ super().__init__(connection, engine_name)
@property
def source(self) -> str:
@@ -146,7 +145,7 @@ class DuckDBEngine(SQLEngine):
return []
def get_table_details(
- self, table_name: str, schema_name: str, database_name: str
+ self, *, table_name: str, schema_name: str, database_name: str
) -> Optional[DataTable]:
"""Get a single table from the engine. This is currently implemented in get_databases_from_duckdb."""
_, _, _ = table_name, schema_name, database_name
diff --git a/marimo/_sql/engines/ibis.py b/marimo/_sql/engines/ibis.py
index 00fb5fa272..8d253554d5 100644
--- a/marimo/_sql/engines/ibis.py
+++ b/marimo/_sql/engines/ibis.py
@@ -14,7 +14,7 @@ from marimo._data.models import (
from marimo._dependencies.dependencies import DependencyManager
from marimo._sql.engines.types import (
InferenceConfig,
- SQLEngine,
+ SQLConnection,
register_engine,
)
from marimo._sql.utils import raise_df_import_error
@@ -32,7 +32,7 @@ class IbisToMarimoConversionError(Exception):
@register_engine
-class IbisEngine(SQLEngine):
+class IbisEngine(SQLConnection["SQLBackend"]):
"""Ibis engine."""
def __init__(
@@ -40,8 +40,7 @@ class IbisEngine(SQLEngine):
connection: SQLBackend,
engine_name: Optional[VariableName] = None,
) -> None:
- self._backend = connection
- self._engine_name = engine_name
+ super().__init__(connection, engine_name)
self.default_database = self.get_default_database()
self.default_schema = self.get_default_schema()
@@ -52,17 +51,17 @@ class IbisEngine(SQLEngine):
@property
def dialect(self) -> str:
- dialect_registry = self._backend.dialect.classes
+ dialect_registry = self._connection.dialect.classes
# reverse lookup
for dialect_name, dialect_class in dialect_registry.items():
- if self._backend.dialect == dialect_class:
+ if self._connection.dialect == dialect_class:
assert isinstance(dialect_name, str)
return dialect_name
- return str(self._backend.dialect)
+ return str(self._connection.dialect)
def execute(self, query: str) -> Any:
- query_expr = self._backend.sql(query)
+ query_expr = self._connection.sql(query)
sql_output_format = self.sql_output_format()
@@ -137,13 +136,13 @@ class IbisEngine(SQLEngine):
"""
database_name = None
try:
- database_name = self._backend.current_catalog
+ database_name = self._connection.current_catalog
except AttributeError:
pass
if database_name is None:
try:
- database_name = self._backend.name
+ database_name = self._connection.name
except AttributeError:
pass
@@ -152,7 +151,7 @@ class IbisEngine(SQLEngine):
def get_default_schema(self) -> Optional[str]:
"""Get the default schema name"""
try:
- schema_name: str | None = self._backend.current_database
+ schema_name: str | None = self._connection.current_database
except AttributeError:
schema_name = None
@@ -214,7 +213,7 @@ class IbisEngine(SQLEngine):
schemas: list[Schema] = []
# TODO handle backends without .list_databases()
- for schema_name in self._backend.list_databases():
+ for schema_name in self._connection.list_databases():
if schema_name.lower() in meta_schemas:
LOGGER.debug(
f"Meta schema found `{schema_name}`. Not displaying schema."
@@ -248,11 +247,11 @@ class IbisEngine(SQLEngine):
self, *, schema: str, database: str, include_table_details: bool
) -> list[DataTable]:
"""Return all tables in a schema."""
- if self._backend is None:
+ if self._connection is None:
return []
try:
- table_names = self._backend.list_tables(
+ table_names = self._connection.list_tables(
database=(database, schema)
)
except Exception:
@@ -294,11 +293,11 @@ class IbisEngine(SQLEngine):
self, *, table_name: str, schema_name: str, database_name: str
) -> Optional[DataTable]:
"""Get a single table from the engine."""
- if self._backend is None:
+ if self._connection is None:
return None
try:
- table = self._backend.table(
+ table = self._connection.table(
table_name, database=(database_name, schema_name)
)
table_schema = table.schema()
diff --git a/marimo/_sql/engines/pyiceberg.py b/marimo/_sql/engines/pyiceberg.py
index 9c82ae3ede..ff7f8fd161 100644
--- a/marimo/_sql/engines/pyiceberg.py
+++ b/marimo/_sql/engines/pyiceberg.py
@@ -13,8 +13,8 @@ from marimo._data.models import (
from marimo._dependencies.dependencies import DependencyManager
from marimo._sql.engines.types import (
NO_SCHEMA_NAME,
+ EngineCatalog,
InferenceConfig,
- SQLEngine,
register_engine,
)
from marimo._sql.utils import sql_type_to_data_type
@@ -27,14 +27,13 @@ if TYPE_CHECKING:
@register_engine
-class PyIcebergEngine(SQLEngine):
+class PyIcebergEngine(EngineCatalog["Catalog"]):
"""PyIceberg engine."""
def __init__(
self, connection: Catalog, engine_name: Optional[VariableName] = None
) -> None:
- self._catalog: Catalog = connection
- self._engine_name = engine_name
+ super().__init__(connection, engine_name)
self.default_database = self.get_default_database()
self.default_schema = self.get_default_schema()
@@ -46,11 +45,6 @@ class PyIcebergEngine(SQLEngine):
def dialect(self) -> str:
return "iceberg"
- def execute(self, query: str) -> Any:
- raise NotImplementedError(
- "PyIceberg does not support direct SQL execution"
- )
-
@staticmethod
def is_compatible(var: Any) -> bool:
if not DependencyManager.pyiceberg.imported():
@@ -88,7 +82,7 @@ class PyIcebergEngine(SQLEngine):
databases: list[Database] = []
try:
namespaces = sorted(
- self._catalog.list_namespaces()
+ self._connection.list_namespaces()
) # Sort for consistent ordering
for namespace in namespaces:
tables = []
@@ -128,7 +122,7 @@ class PyIcebergEngine(SQLEngine):
from pyiceberg.catalog import Catalog
try:
- tables = self._catalog.list_tables(database)
+ tables = self._connection.list_tables(database)
if not include_table_details:
return [
DataTable(
@@ -168,7 +162,7 @@ class PyIcebergEngine(SQLEngine):
"""Get a single table from the engine."""
del schema_name # Not used since Iceberg doesn't have schemas
try:
- table = self._catalog.load_table((database_name, table_name))
+ table = self._connection.load_table((database_name, table_name))
schema = table.schema()
cols: list[DataTableColumn] = []
diff --git a/marimo/_sql/engines/sqlalchemy.py b/marimo/_sql/engines/sqlalchemy.py
index 80b7f5206d..7bbbf45f23 100644
--- a/marimo/_sql/engines/sqlalchemy.py
+++ b/marimo/_sql/engines/sqlalchemy.py
@@ -15,7 +15,7 @@ from marimo._data.models import (
from marimo._dependencies.dependencies import DependencyManager
from marimo._sql.engines.types import (
InferenceConfig,
- SQLEngine,
+ SQLConnection,
register_engine,
)
from marimo._sql.utils import raise_df_import_error, sql_type_to_data_type
@@ -30,21 +30,20 @@ if TYPE_CHECKING:
@register_engine
-class SQLAlchemyEngine(SQLEngine):
+class SQLAlchemyEngine(SQLConnection["Engine"]):
"""SQLAlchemy engine."""
def __init__(
self, connection: Engine, engine_name: Optional[VariableName] = None
) -> None:
- self._engine = connection
- self._engine_name = engine_name
+ super().__init__(connection, engine_name)
self.inspector: Optional[Inspector] = None
try:
# May not exist in older versions of SQLAlchemy
from sqlalchemy import inspect
- self.inspector = inspect(self._engine)
+ self.inspector = inspect(self._connection)
except Exception:
LOGGER.warning("Failed to create inspector", exc_info=True)
self.inspector = None
@@ -58,14 +57,14 @@ class SQLAlchemyEngine(SQLEngine):
@property
def dialect(self) -> str:
- return str(self._engine.dialect.name)
+ return str(self._connection.dialect.name)
def execute(self, query: str) -> Any:
sql_output_format = self.sql_output_format()
from sqlalchemy import text
- with self._engine.connect() as connection:
+ with self._connection.connect() as connection:
result = connection.execute(text(query))
if sql_output_format == "native":
return result
@@ -149,8 +148,8 @@ class SQLAlchemyEngine(SQLEngine):
from sqlalchemy import text
try:
- if self._engine.url.database is not None:
- return self._engine.url.database
+ if self._connection.url.database is not None:
+ return self._connection.url.database
except Exception:
LOGGER.warning("Connection URL is invalid", exc_info=True)
return None
@@ -165,7 +164,7 @@ class SQLAlchemyEngine(SQLEngine):
# Try to get the database name by querying the database directly
if query := dialect_queries.get(self.dialect):
try:
- with self._engine.connect() as connection:
+ with self._connection.connect() as connection:
rows = connection.execute(text(query)).fetchone()
if rows is not None and rows[0] is not None:
database_name = str(rows[0])
diff --git a/marimo/_sql/engines/types.py b/marimo/_sql/engines/types.py
index 3c7cf46492..330afdb280 100644
--- a/marimo/_sql/engines/types.py
+++ b/marimo/_sql/engines/types.py
@@ -3,7 +3,7 @@ from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
-from typing import Any, Literal, Optional, Union
+from typing import Any, Generic, Literal, Optional, TypeVar, Union
from marimo._config.config import SqlOutputType
from marimo._data.models import Database, DataTable
@@ -13,16 +13,12 @@ from marimo._runtime.context.types import (
get_context,
runtime_context_installed,
)
+from marimo._types.ids import VariableName
-ENGINE_REGISTRY: list[type[SQLEngine]] = []
+ENGINE_REGISTRY: list[type[BaseEngine[Any]]] = []
NO_SCHEMA_NAME = ""
-def register_engine(cls: type[SQLEngine]) -> type[SQLEngine]:
- ENGINE_REGISTRY.append(cls)
- return cls
-
-
@dataclass
class InferenceConfig(ABC):
auto_discover_schemas: Union[bool, Literal["auto"]]
@@ -42,23 +38,17 @@ def _validate_sql_output_format(sql_output: SqlOutputType) -> SqlOutputType:
return sql_output
-class SQLEngine(ABC):
- """Protocol for SQL engines that can execute queries."""
+CONN = TypeVar("CONN")
- def sql_output_format(self) -> SqlOutputType:
- if runtime_context_installed():
- try:
- ctx = get_context()
- return _validate_sql_output_format(ctx.app_config.sql_output)
- except ContextNotInitializedError:
- return "auto"
- return "auto"
- @abstractmethod
+class BaseEngine(ABC, Generic[CONN]):
+ """Base fields for all engines and catalogs."""
+
def __init__(
- self, connection: Any, engine_name: Optional[str] = None
+ self, connection: CONN, engine_name: Optional[VariableName] = None
) -> None:
- pass
+ self._connection: CONN = connection
+ self._engine_name: Optional[VariableName] = engine_name
@property
@abstractmethod
@@ -72,21 +62,28 @@ class SQLEngine(ABC):
"""Return the sqlglot dialect for this engine."""
pass
- @property
+ @staticmethod
@abstractmethod
- def inference_config(self) -> InferenceConfig:
- """Return the inference config for the engine."""
+ def is_compatible(var: Any) -> bool:
+ """Check if a variable is a compatible engine."""
pass
- @abstractmethod
- def execute(self, query: str) -> Any:
- """Execute a SQL query and return a dataframe."""
- pass
- @staticmethod
+T = TypeVar("T", bound=BaseEngine[Any])
+
+
+def register_engine(cls: type[T]) -> type[T]:
+ ENGINE_REGISTRY.append(cls)
+ return cls
+
+
+class EngineCatalog(BaseEngine[CONN], ABC):
+ """Protocol for querying the catalog of an engine."""
+
+ @property
@abstractmethod
- def is_compatible(var: Any) -> bool:
- """Check if a variable is a compatible engine."""
+ def inference_config(self) -> InferenceConfig:
+ """Return the inference config for the engine."""
pass
@abstractmethod
@@ -123,3 +120,27 @@ class SQLEngine(ABC):
) -> Optional[DataTable]:
"""Get a single table from the engine."""
pass
+
+
+class QueryEngine(BaseEngine[CONN], ABC):
+ """Protocol for SQL engines that can execute queries."""
+
+ @abstractmethod
+ def execute(self, query: str) -> Any:
+ """Execute a SQL query and return a dataframe."""
+ pass
+
+ def sql_output_format(self) -> SqlOutputType:
+ if runtime_context_installed():
+ try:
+ ctx = get_context()
+ return _validate_sql_output_format(ctx.app_config.sql_output)
+ except ContextNotInitializedError:
+ return "auto"
+ return "auto"
+
+
+class SQLConnection(EngineCatalog[CONN], QueryEngine[CONN]):
+ """Combines the catalog and query interfaces for an SQL engine."""
+
+ pass
diff --git a/marimo/_sql/get_engines.py b/marimo/_sql/get_engines.py
index f776f3fd1e..fd1d4b3a03 100644
--- a/marimo/_sql/get_engines.py
+++ b/marimo/_sql/get_engines.py
@@ -15,6 +15,7 @@ from marimo._sql.engines.clickhouse import (
ClickhouseEmbedded,
ClickhouseServer,
)
+from marimo._sql.engines.dbapi import DBAPIEngine
from marimo._sql.engines.duckdb import (
INTERNAL_DUCKDB_ENGINE,
DuckDBEngine,
@@ -22,7 +23,10 @@ from marimo._sql.engines.duckdb import (
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
+from marimo._sql.engines.types import (
+ BaseEngine,
+ EngineCatalog,
+)
from marimo._types.ids import VariableName
LOGGER = _loggers.marimo_logger()
@@ -30,16 +34,19 @@ LOGGER = _loggers.marimo_logger()
def get_engines_from_variables(
variables: list[tuple[VariableName, object]],
-) -> list[tuple[VariableName, SQLEngine]]:
- engines: list[tuple[VariableName, SQLEngine]] = []
+) -> list[tuple[VariableName, BaseEngine[Any]]]:
+ engines: list[tuple[VariableName, BaseEngine[Any]]] = []
- supported_engines: list[type[SQLEngine]] = [
+ # TODO: this is O(n) and can be O(1) using similar logic to the
+ # formatters, but order does matter here
+ supported_engines: list[type[BaseEngine[Any]]] = [
SQLAlchemyEngine,
IbisEngine,
DuckDBEngine,
ClickhouseEmbedded,
ClickhouseServer,
PyIcebergEngine,
+ DBAPIEngine,
]
for variable_name, value in variables:
@@ -53,18 +60,26 @@ def get_engines_from_variables(
),
)
)
+ break
return engines
def engine_to_data_source_connection(
- variable_name: VariableName,
- engine: SQLEngine,
+ variable_name: VariableName, engine: BaseEngine[Any]
) -> DataSourceConnection:
databases: list[Database] = []
default_database: Optional[str] = None
default_schema: Optional[str] = None
+ if not isinstance(engine, EngineCatalog):
+ return DataSourceConnection(
+ source=engine.source,
+ dialect=engine.dialect,
+ name=variable_name,
+ display_name=variable_name,
+ )
+
default_database = engine.get_default_database()
default_schema = engine.get_default_schema()
inference_config = engine.inference_config
diff --git a/marimo/_sql/sql.py b/marimo/_sql/sql.py
index 900200f43b..bf3b37b1f5 100644
--- a/marimo/_sql/sql.py
+++ b/marimo/_sql/sql.py
@@ -10,8 +10,12 @@ 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.engines.types import (
+ ENGINE_REGISTRY,
+ QueryEngine,
+)
from marimo._sql.utils import raise_df_import_error
+from marimo._types.ids import VariableName
from marimo._utils.narwhals_utils import can_narwhalify_lazyframe
@@ -62,6 +66,7 @@ def sql(
if query is None or query.strip() == "":
return None
+ sql_engine: QueryEngine[Any]
if engine is None:
DependencyManager.require_many(
"to execute sql",
@@ -73,7 +78,7 @@ def sql(
for engine_cls in ENGINE_REGISTRY:
if engine_cls.is_compatible(engine):
sql_engine = engine_cls(
- connection=engine, engine_name="custom"
+ connection=engine, engine_name=VariableName("custom")
) # type: ignore
break
else:
diff --git a/pyproject.toml b/pyproject.toml
index e15a95c33e..cb87103977 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -445,18 +445,21 @@ ban-relative-imports = "all"
# Ban certain modules from being imported at module level, instead requiring
# that they're imported lazily (e.g., within a function definition).
banned-module-level-imports = [
- "numpy",
- "pandas",
- "tomlkit",
- "polars",
- "sqlglot",
- "duckdb",
- "sqlalchemy",
"altair",
- "ipython",
"anywidget",
+ "chdb",
+ "clickhouse_connect",
+ "duckdb",
+ "ipython",
+ "numpy",
"packaging",
+ "pandas",
+ "polars",
+ "pyarrow",
"redis",
+ "sqlalchemy",
+ "sqlglot",
+ "tomlkit",
"typing_extensions",
]
diff --git a/tests/_sql/test_clickhouse.py b/tests/_sql/test_clickhouse.py
index 49269b0694..2f85db42da 100644
--- a/tests/_sql/test_clickhouse.py
+++ b/tests/_sql/test_clickhouse.py
@@ -9,6 +9,7 @@ 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.engines.types import EngineCatalog, QueryEngine
from marimo._sql.get_engines import engine_to_data_source_connection
from marimo._sql.sql import sql
@@ -57,6 +58,10 @@ def test_clickhouse_embedded_creation() -> None:
assert connection.name == "clickhouse"
assert connection.source == "clickhouse"
+ assert isinstance(engine, ClickhouseEmbedded)
+ assert isinstance(engine, EngineCatalog)
+ assert isinstance(engine, QueryEngine)
+
chdb_conn.close()
diff --git a/tests/_sql/test_dbapi.py b/tests/_sql/test_dbapi.py
new file mode 100644
index 0000000000..07d4578097
--- /dev/null
+++ b/tests/_sql/test_dbapi.py
@@ -0,0 +1,145 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import sqlite3
+from unittest.mock import patch
+
+import pytest
+
+from marimo._sql.engines.dbapi import DBAPIEngine
+from marimo._sql.engines.types import EngineCatalog, QueryEngine
+
+
+def sqlite_connection() -> sqlite3.Connection:
+ conn = sqlite3.connect(":memory:")
+ conn.execute("""
+ CREATE TABLE test (
+ id INTEGER PRIMARY KEY,
+ name TEXT,
+ value REAL
+ )
+ """)
+ conn.execute("""
+ INSERT INTO test (name, value) VALUES
+ ('a', 1.0),
+ ('b', 2.0),
+ ('c', 3.0)
+ """)
+ return conn
+
+
+def dbapi_engine(sqlite_connection: sqlite3.Connection) -> DBAPIEngine:
+ return DBAPIEngine(connection=sqlite_connection)
+
+
+def test_source(dbapi_engine: DBAPIEngine) -> None:
+ assert dbapi_engine.source == "dbapi"
+
+
+def test_dialect(dbapi_engine: DBAPIEngine) -> None:
+ assert dbapi_engine.dialect == "sql"
+
+
+def test_is_compatible() -> None:
+ # Test with sqlite3 connection
+ conn = sqlite3.connect(":memory:")
+ assert DBAPIEngine.is_compatible(conn)
+ conn.close()
+
+ # Test with non-DBAPI object
+ assert not DBAPIEngine.is_compatible("not a connection")
+ assert not DBAPIEngine.is_compatible(None)
+
+ engine = DBAPIEngine(conn)
+ assert isinstance(engine, DBAPIEngine)
+ assert isinstance(engine, QueryEngine)
+ assert not isinstance(engine, EngineCatalog)
+
+
+def test_execute_native(dbapi_engine: DBAPIEngine) -> None:
+ with patch.object(
+ dbapi_engine, "sql_output_format", return_value="native"
+ ):
+ result = dbapi_engine.execute("SELECT * FROM test")
+ assert isinstance(result, sqlite3.Cursor)
+ assert result.fetchall() == [
+ (1, "a", 1.0),
+ (2, "b", 2.0),
+ (3, "c", 3.0),
+ ]
+
+
+def test_execute_pandas(dbapi_engine: DBAPIEngine) -> None:
+ pd = pytest.importorskip("pandas")
+ with patch.object(
+ dbapi_engine, "sql_output_format", return_value="pandas"
+ ):
+ result = dbapi_engine.execute("SELECT * FROM test")
+ assert isinstance(result, pd.DataFrame)
+ assert list(result.columns) == ["id", "name", "value"]
+ assert len(result) == 3
+ assert result.iloc[0].to_dict() == {"id": 1, "name": "a", "value": 1.0}
+
+
+def test_execute_polars(dbapi_engine: DBAPIEngine) -> None:
+ pl = pytest.importorskip("polars")
+ with patch.object(
+ dbapi_engine, "sql_output_format", return_value="polars"
+ ):
+ result = dbapi_engine.execute("SELECT * FROM test")
+ assert isinstance(result, pl.DataFrame)
+ assert result.columns == ["id", "name", "value"]
+ assert len(result) == 3
+ assert result.row(0) == (1, "a", 1.0)
+
+
+def test_execute_lazy_polars(dbapi_engine: DBAPIEngine) -> None:
+ pl = pytest.importorskip("polars")
+ with patch.object(
+ dbapi_engine, "sql_output_format", return_value="lazy-polars"
+ ):
+ result = dbapi_engine.execute("SELECT * FROM test")
+ assert isinstance(result, pl.LazyFrame)
+ result = result.collect()
+ assert result.columns == ["id", "name", "value"]
+ assert result.row(0) == (1, "a", 1.0)
+
+
+def test_execute_no_results(dbapi_engine: DBAPIEngine) -> None:
+ result = dbapi_engine.execute("CREATE TABLE empty (id INTEGER)")
+ assert result is None
+
+
+def test_execute_error(dbapi_engine: DBAPIEngine) -> None:
+ with pytest.raises(sqlite3.OperationalError):
+ dbapi_engine.execute("SELECT * FROM nonexistent")
+
+
+def test_execute_transaction(dbapi_engine: DBAPIEngine) -> None:
+ pytest.importorskip("pandas")
+
+ # Test that transaction is committed
+ with patch.object(
+ dbapi_engine, "sql_output_format", return_value="pandas"
+ ):
+ dbapi_engine.execute(
+ "INSERT INTO test (name, value) VALUES ('d', 4.0)"
+ )
+ result = dbapi_engine.execute("SELECT * FROM test")
+ assert len(result) == 4
+ assert result.iloc[3].to_dict() == {"id": 4, "name": "d", "value": 4.0}
+
+
+def test_execute_with_parameters(dbapi_engine: DBAPIEngine) -> None:
+ pytest.importorskip("pandas")
+
+ with patch.object(
+ dbapi_engine, "sql_output_format", return_value="pandas"
+ ):
+ result = dbapi_engine.execute(
+ "SELECT * FROM test WHERE name = ?", ["a"]
+ )
+ assert len(result) == 1
+ assert result.iloc[0].to_dict() == {"id": 1, "name": "a", "value": 1.0}
diff --git a/tests/_sql/test_duckdb.py b/tests/_sql/test_duckdb.py
index ca586113c1..551d75bdbe 100644
--- a/tests/_sql/test_duckdb.py
+++ b/tests/_sql/test_duckdb.py
@@ -10,6 +10,7 @@ import pytest
from marimo._data.models import Database, DataTable, DataTableColumn, Schema
from marimo._dependencies.dependencies import DependencyManager
from marimo._sql.engines.duckdb import DuckDBEngine
+from marimo._sql.engines.types import EngineCatalog, QueryEngine
from marimo._sql.sql import sql
from marimo._types.ids import VariableName
@@ -59,6 +60,15 @@ def test_duckdb_engine_dialect() -> None:
assert engine.dialect == "duckdb"
[email protected](not HAS_DUCKDB, reason="DuckDB not installed")
+def test_duckdb_engine_is_instance() -> None:
+ """Test DuckDBEngine is an instance of the correct types."""
+ engine = DuckDBEngine(None, engine_name=None)
+ assert isinstance(engine, DuckDBEngine)
+ assert isinstance(engine, EngineCatalog)
+ assert isinstance(engine, QueryEngine)
+
+
@pytest.mark.skipif(
not HAS_DUCKDB or not HAS_PANDAS, reason="DuckDB and Pandas not installed"
)
diff --git a/tests/_sql/test_get_engines.py b/tests/_sql/test_get_engines.py
index 82ac93281d..a861309124 100644
--- a/tests/_sql/test_get_engines.py
+++ b/tests/_sql/test_get_engines.py
@@ -12,6 +12,7 @@ from marimo._data.models import (
)
from marimo._dependencies.dependencies import DependencyManager
from marimo._sql.engines.clickhouse import ClickhouseEmbedded
+from marimo._sql.engines.dbapi import DBAPIEngine
from marimo._sql.engines.duckdb import (
INTERNAL_DUCKDB_ENGINE,
DuckDBEngine,
@@ -23,6 +24,7 @@ from marimo._sql.get_engines import (
get_engines_from_variables,
)
from marimo._sql.sql import sql
+from marimo._types.ids import VariableName
HAS_SQLALCHEMY = DependencyManager.sqlalchemy.has()
HAS_IBIS = DependencyManager.ibis.has()
@@ -36,7 +38,9 @@ def test_engine_to_data_source_connection() -> None:
# Test with DuckDB engine
duckdb_engine = DuckDBEngine(None)
- connection = engine_to_data_source_connection("my_duckdb", duckdb_engine)
+ connection = engine_to_data_source_connection(
+ VariableName("my_duckdb"), duckdb_engine
+ )
assert isinstance(connection, DataSourceConnection)
assert connection.source == "duckdb"
assert connection.dialect == "duckdb"
@@ -219,6 +223,31 @@ def test_get_engines_from_variables_multiple():
assert ibis_var_name == "ibis_backend"
+def test_get_engines_dbapi():
+ import sqlite3
+
+ mock_sqlite_conn = MagicMock(spec=sqlite3.Connection)
+ variables: list[tuple[str, object]] = [("sqlite_conn", mock_sqlite_conn)]
+
+ engines = get_engines_from_variables(variables)
+ assert len(engines) == 1
+ var_name, engine = engines[0]
+ assert var_name == "sqlite_conn"
+ assert isinstance(engine, DBAPIEngine)
+
+
+def test_get_engines_dbapi_databases():
+ import sqlite3
+
+ with sqlite3.connect(":memory:") as conn:
+ engine = DBAPIEngine(conn)
+ connection = engine_to_data_source_connection(
+ VariableName("sqlite_conn"), engine
+ )
+ assert connection.databases == []
+ assert connection.dialect == "sql"
+
+
@pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")
def test_get_engines_duckdb_databases() -> None:
duckdb_engine = DuckDBEngine(None)
@@ -229,7 +258,9 @@ def test_get_engines_duckdb_databases() -> None:
)
assert connection.display_name == "duckdb (In-Memory)"
- connection = engine_to_data_source_connection("my_duckdb", duckdb_engine)
+ connection = engine_to_data_source_connection(
+ VariableName("my_duckdb"), duckdb_engine
+ )
assert isinstance(connection, DataSourceConnection)
assert connection.source == "duckdb"
@@ -242,7 +273,9 @@ def test_get_engines_duckdb_databases() -> None:
sql("CREATE TABLE test_table (id INTEGER);")
# Reload the connection to get the new table
- connection = engine_to_data_source_connection("my_duckdb", duckdb_engine)
+ connection = engine_to_data_source_connection(
+ VariableName("my_duckdb"), duckdb_engine
+ )
assert len(connection.databases) == 1
database = connection.databases[0]
@@ -271,7 +304,9 @@ def test_get_engines_sqlalchemy_databases() -> None:
sqlalchemy_engine = sa.create_engine("sqlite:///:memory:")
engine = SQLAlchemyEngine(sqlalchemy_engine)
- connection = engine_to_data_source_connection("sqlite", engine)
+ connection = engine_to_data_source_connection(
+ VariableName("sqlite"), engine
+ )
assert isinstance(connection, DataSourceConnection)
assert connection.source == "sqlalchemy"
@@ -297,7 +332,9 @@ def test_get_engines_ibis_databases() -> None:
ibis_backend = ibis.duckdb.connect()
engine = IbisEngine(ibis_backend)
- connection = engine_to_data_source_connection("my_ibis", engine)
+ connection = engine_to_data_source_connection(
+ VariableName("my_ibis"), engine
+ )
assert isinstance(connection, DataSourceConnection)
assert connection.source == "ibis"
@@ -321,8 +358,10 @@ def test_get_engines_clickhouse() -> None:
import chdb
clickhouse_conn = chdb.connect(":memory:")
- engine = ClickhouseEmbedded(clickhouse_conn, engine_name="clickhouse")
- variable_name = "clickhouse_conn"
+ engine = ClickhouseEmbedded(
+ clickhouse_conn, engine_name=VariableName("clickhouse")
+ )
+ variable_name = VariableName("clickhouse_conn")
connection = engine_to_data_source_connection(variable_name, engine)
assert isinstance(connection, DataSourceConnection)
diff --git a/tests/_sql/test_ibis.py b/tests/_sql/test_ibis.py
index 365d16c7e9..21dd04cf84 100644
--- a/tests/_sql/test_ibis.py
+++ b/tests/_sql/test_ibis.py
@@ -10,6 +10,7 @@ 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.engines.types import EngineCatalog, QueryEngine
from marimo._sql.sql import sql
from marimo._types.ids import VariableName
@@ -123,6 +124,10 @@ def test_engine_name_initialization() -> None:
ibis_engine = IbisEngine(ibis_backend)
assert ibis_engine._engine_name is None
+ assert isinstance(ibis_engine, IbisEngine)
+ assert isinstance(ibis_engine, EngineCatalog)
+ assert isinstance(ibis_engine, QueryEngine)
+
@pytest.mark.skipif(not HAS_IBIS, reason="Ibis not installed")
def test_ibis_engine_source_and_dialect() -> None:
@@ -152,7 +157,7 @@ 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._connection is None
assert engine.default_database is None
assert engine.default_schema is None
diff --git a/tests/_sql/test_pyiceberg.py b/tests/_sql/test_pyiceberg.py
index da2865970b..9d5343020f 100644
--- a/tests/_sql/test_pyiceberg.py
+++ b/tests/_sql/test_pyiceberg.py
@@ -10,7 +10,11 @@ import pytest
from marimo._data.models import DataTable, DataTableColumn
from marimo._dependencies.dependencies import DependencyManager
from marimo._sql.engines.pyiceberg import PyIcebergEngine
-from marimo._sql.engines.types import NO_SCHEMA_NAME
+from marimo._sql.engines.types import (
+ NO_SCHEMA_NAME,
+ EngineCatalog,
+ QueryEngine,
+)
from marimo._types.ids import VariableName
HAS_PYICEBERG = DependencyManager.pyiceberg.has()
@@ -119,14 +123,21 @@ def get_expected_table(
@pytest.mark.skipif(not HAS_PYICEBERG, reason="PyIceberg not installed")
def test_engine_compatibility() -> None:
"""Test engine compatibility checks."""
- from pyiceberg.catalog import Catalog
+ from pyiceberg.catalog.memory import InMemoryCatalog
obj = object()
- mock_catalog = mock.MagicMock(spec=Catalog)
+ mock_catalog = InMemoryCatalog("test_catalog")
assert PyIcebergEngine.is_compatible(mock_catalog)
assert not PyIcebergEngine.is_compatible(obj)
+ engine = PyIcebergEngine(
+ mock_catalog, engine_name=VariableName("my_iceberg")
+ )
+ assert isinstance(engine, PyIcebergEngine)
+ assert isinstance(engine, EngineCatalog)
+ assert not isinstance(engine, QueryEngine)
+
@pytest.mark.skipif(not HAS_PYICEBERG, reason="PyIceberg not installed")
def test_engine_name_initialization(memory_catalog: Catalog) -> None:
@@ -165,7 +176,9 @@ def test_pyiceberg_execute(memory_catalog: Catalog) -> None:
engine = PyIcebergEngine(
memory_catalog, engine_name=VariableName("my_iceberg")
)
- with pytest.raises(NotImplementedError):
+ assert isinstance(engine, EngineCatalog)
+ assert not isinstance(engine, QueryEngine)
+ with pytest.raises(AttributeError):
engine.execute("SELECT * FROM table")
diff --git a/tests/_sql/test_sqlalchemy.py b/tests/_sql/test_sqlalchemy.py
index 27373fa715..3665b06a11 100644
--- a/tests/_sql/test_sqlalchemy.py
+++ b/tests/_sql/test_sqlalchemy.py
@@ -12,6 +12,7 @@ from marimo._dependencies.dependencies import DependencyManager
from marimo._sql.engines.sqlalchemy import (
SQLAlchemyEngine,
)
+from marimo._sql.engines.types import EngineCatalog, QueryEngine
from marimo._sql.sql import sql
from marimo._types.ids import VariableName
@@ -115,6 +116,17 @@ def test_sqlalchemy_engine_dialect(sqlite_engine: sa.Engine) -> None:
assert engine.dialect == "sqlite"
[email protected](not HAS_SQLALCHEMY, reason="SQLAlchemy not installed")
+def test_sqlalchemy_engine_is_instance(sqlite_engine: sa.Engine) -> None:
+ """Test SQLAlchemyEngine is an instance of the correct types."""
+ engine = SQLAlchemyEngine(
+ sqlite_engine, engine_name=VariableName("sqlite")
+ )
+ assert isinstance(engine, SQLAlchemyEngine)
+ assert isinstance(engine, EngineCatalog)
+ assert isinstance(engine, QueryEngine)
+
+
@pytest.mark.skipif(not HAS_SQLALCHEMY, reason="SQLAlchemy not installed")
def test_sqlalchemy_invalid_engine() -> None:
"""Test SQLAlchemyEngine with an invalid engine and inspector does not raise errors."""