Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added docs/_static/docs-sql-connectorx-demo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
120 changes: 84 additions & 36 deletions docs/guides/working_with_data/sql.md
Original file line number Diff line number Diff line change
Expand Up @@ -323,49 +323,50 @@ You can bring your own database via a **connection engine** with one of the foll
- [Custom DuckDB connection](https://duckdb.org/docs/api/python/overview.html#connection-options)
- [ClickHouse Connect](https://clickhouse.com/docs/integrations/python#introduction)
- [chDB](https://clickhouse.com/docs/chdb)
- [ConnectorX](https://github.com/sfu-db/connector-x) *(high-performance analytics on Trino, Redshift, PostgreSQL, and more)*

By default, marimo uses the [in-memory duckdb connection](https://duckdb.org/docs/connect/overview.html#in-memory-database).

??? info "List of supported databases"

Updated: 2025-04-30. This list is not exhaustive.

| Database | Library |
| -------------------------- | ---------------------------------- |
| Amazon Athena | `sqlalchemy`, `sqlmodel`, `ibis` |
| Amazon Redshift | `sqlalchemy`, `sqlmodel` |
| Apache Drill | `sqlalchemy`, `sqlmodel` |
| Apache Druid | `sqlalchemy`, `sqlmodel`, `ibis` |
| Apache Hive and Presto | `sqlalchemy`, `sqlmodel` |
| Apache Solr | `sqlalchemy`, `sqlmodel` |
| BigQuery | `sqlalchemy`, `sqlmodel`, `ibis` |
| ClickHouse | `clickhouse_connect`, `chdb` |
| CockroachDB | `sqlalchemy`, `sqlmodel` |
| Databricks | `sqlalchemy`, `sqlmodel`, `ibis` |
| dlt | `ibis` |
| Datafusion | `ibis` |
| DuckDB | `duckdb` |
| EXASolution | `sqlalchemy`, `sqlmodel`, `ibis` |
| Elasticsearch (readonly) | `sqlalchemy`, `sqlmodel` |
| Firebolt | `sqlalchemy`, `sqlmodel` |
| Flink | `ibis` |
| Google Sheets | `sqlalchemy`, `sqlmodel` |
| Impala | `sqlalchemy`, `sqlmodel`, `ibis` |
| Microsoft Access | `sqlalchemy`, `sqlmodel` |
| Microsoft SQL Server | `sqlalchemy`, `sqlmodel`, `ibis` |
| MonetDB | `sqlalchemy`, `sqlmodel` |
| MySQL | `sqlalchemy`, `sqlmodel`, `ibis` |
| OpenGauss | `sqlalchemy`, `sqlmodel` |
| Oracle | `sqlalchemy`, `sqlmodel`, `ibis` |
| PostgreSQL | `sqlalchemy`, `sqlmodel`, `ibis` |
| PySpark | `ibis` |
| RisingWave | `ibis` |
| SAP HANA | `sqlalchemy`, `sqlmodel` |
| Snowflake | `sqlalchemy`, `sqlmodel`, `ibis` |
| SQLite | `sqlalchemy`, `sqlmodel`, `ibis` |
| Teradata Vantage | `sqlalchemy`, `sqlmodel` |
| TimePlus | `sqlalchemy`, `sqlmodel` |
| Trino | `sqlalchemy`, `sqlmodel`, `ibis` |
| Database | Library |
| -------------------------- | ---------------------------------------------- |
| Amazon Athena | `sqlalchemy`, `sqlmodel`, `ibis` |
| Amazon Redshift | `sqlalchemy`, `sqlmodel`, `connectorx` |
| Apache Drill | `sqlalchemy`, `sqlmodel` |
| Apache Druid | `sqlalchemy`, `sqlmodel`, `ibis` |
| Apache Hive and Presto | `sqlalchemy`, `sqlmodel` |
| Apache Solr | `sqlalchemy`, `sqlmodel` |
| BigQuery | `sqlalchemy`, `sqlmodel`, `ibis`, `connectorx` |
| ClickHouse | `clickhouse_connect`, `chdb`, `connectorx` |
| CockroachDB | `sqlalchemy`, `sqlmodel` |
| Databricks | `sqlalchemy`, `sqlmodel`, `ibis` |
| dlt | `ibis` |
| Datafusion | `ibis` |
| DuckDB | `duckdb` |
| EXASolution | `sqlalchemy`, `sqlmodel`, `ibis` |
| Elasticsearch (readonly) | `sqlalchemy`, `sqlmodel` |
| Firebolt | `sqlalchemy`, `sqlmodel` |
| Flink | `ibis` |
| Google Sheets | `sqlalchemy`, `sqlmodel` |
| Impala | `sqlalchemy`, `sqlmodel`, `ibis` |
| Microsoft Access | `sqlalchemy`, `sqlmodel` |
| Microsoft SQL Server | `sqlalchemy`, `sqlmodel`, `ibis`, `connectorx` |
| MonetDB | `sqlalchemy`, `sqlmodel` |
| MySQL | `sqlalchemy`, `sqlmodel`, `ibis`, `connectorx` |
| OpenGauss | `sqlalchemy`, `sqlmodel` |
| Oracle | `sqlalchemy`, `sqlmodel`, `ibis`, `connectorx` |
| PostgreSQL | `sqlalchemy`, `sqlmodel`, `ibis`, `connectorx` |
| PySpark | `ibis` |
| RisingWave | `ibis` |
| SAP HANA | `sqlalchemy`, `sqlmodel` |
| Snowflake | `sqlalchemy`, `sqlmodel`, `ibis` |
| SQLite | `sqlalchemy`, `sqlmodel`, `ibis`, `connectorx` |
| Teradata Vantage | `sqlalchemy`, `sqlmodel` |
| TimePlus | `sqlalchemy`, `sqlmodel` |
| Trino | `sqlalchemy`, `sqlmodel`, `ibis`, `connectorx` |

Define the engine as a Python variable in a cell:

Expand Down Expand Up @@ -450,6 +451,53 @@ connection = chdb.connect(":memory:")

///

/// tab | ConnectorX

ConnectorX reads SQL directly into Arrow format using a Rust backend, making it
well-suited for read-heavy analytics workloads on Trino, Redshift, PostgreSQL,
and other databases. It requires no native Python drivers (e.g. no `psycopg2`).

Install:

```bash
pip install "connectorx>=0.4.6" pyarrow
```

```python
from marimo._sql.engines.connectorx import ConnectorXConnection

# PostgreSQL β€” zero-copy Arrow path, no psycopg2 needed
conn = ConnectorXConnection("postgresql://user:pass@host:5432/db")

# Trino (analytics warehouse)
conn = ConnectorXConnection(
"trino+https://user:pass@trino.example.com:8443/catalog"
)

# Amazon Redshift
conn = ConnectorXConnection("redshift://user:pass@host:5439/db")
```

!!! note "Read-only & no schema introspection"

ConnectorX only supports `SELECT` queries. The Data Sources panel will not
list schemas or tables for ConnectorX connections.

!!! warning "TLS certificate verification"

TLS verification is enabled by default. Appending `?verify=false` disables
it and should only be used in isolated test environments β€” never in
production, as it exposes credentials to man-in-the-middle attacks.

<div align="center">
<figure>
<img width="750" src="/_static/docs-sql-connectorx-demo.png"/>
<figcaption>ConnectorX engine selected and running in a SQL cell</figcaption>
</figure>
</div>

///

marimo will auto-discover the engine and let you select it in the SQL cell's connection dropdown.

<div align="center">
Expand Down
1 change: 1 addition & 0 deletions marimo/_dependencies/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,7 @@ class DependencyManager:
panel = Dependency("panel")
holoviews = Dependency("holoviews")
sqlalchemy = Dependency("sqlalchemy")
connectorx = Dependency("connectorx", min_version="0.4.6")
pylsp = Dependency("pylsp")
basedpyright = Dependency("basedpyright")
ty = Dependency("ty")
Expand Down
191 changes: 191 additions & 0 deletions marimo/_sql/engines/connectorx.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations

import re
import urllib.parse
from typing import TYPE_CHECKING, Any

from marimo import _loggers
from marimo._dependencies.dependencies import DependencyManager
from marimo._sql.engines.types import QueryEngine
from marimo._sql.utils import convert_to_output
from marimo._types.ids import VariableName

LOGGER = _loggers.marimo_logger()

if TYPE_CHECKING:
import pandas as pd
import polars as pl
import pyarrow as pa

# Maps the leading scheme segment (before any '+') to a sqlglot dialect string.
_SCHEME_TO_DIALECT: dict[str, str] = {
"trino": "trino",
"postgresql": "postgresql",
"postgres": "postgresql",
"redshift": "redshift",
"mysql": "mysql",
"mssql": "tsql",
"oracle": "oracle",
"bigquery": "bigquery",
"clickhouse": "clickhouse",
"sqlite": "sqlite",
}


def mask_uri(uri: str) -> str:
"""Return *uri* with the password replaced by ``'***'``."""
try:
parts = urllib.parse.urlsplit(uri)
if not parts.password:
return uri
userinfo = parts.username or ""
if userinfo:
userinfo = f"{userinfo}:***"
host_part = parts.hostname or ""
if parts.port:
host_part = f"{host_part}:{parts.port}"
netloc = f"{userinfo}@{host_part}" if userinfo else host_part
return urllib.parse.urlunsplit(
(parts.scheme, netloc, parts.path, parts.query, parts.fragment)
)
except Exception:
# Regex fallback for URIs that urlsplit cannot parse
return re.sub(r"(://[^:@/]*:)[^@]*(@)", r"\1***\2", uri)


def _detect_dialect(uri: str) -> str:
"""Return the sqlglot dialect string for *uri*'s scheme.

Trino supports both ``trino://`` and ``trino+https://`` / ``trino+http://``
β€” only the part before any ``+`` is used for dialect lookup.
"""
if "://" not in uri:
return "sql"
scheme_part = (
uri.split("://", maxsplit=1)[0].split("+", maxsplit=1)[0].lower()
)
return _SCHEME_TO_DIALECT.get(scheme_part, "sql")


class ConnectorXConnection:
"""Lightweight wrapper around a ConnectorX connection URI.

Pass an instance to ``mo.sql(engine=...)`` or any marimo SQL cell to run
queries via ConnectorX instead of SQLAlchemy:

.. code-block:: python

import marimo as mo
from marimo._sql.engines.connectorx import ConnectorXConnection

conn = ConnectorXConnection("postgresql://user:pass@host:5432/db")
result = mo.sql("SELECT * FROM my_table LIMIT 100", engine=conn)

ConnectorX supports PostgreSQL, MySQL, SQLite, Trino, Redshift, BigQuery,
SQL Server (``mssql``), Oracle, and ClickHouse URIs. Requires
``connectorx>=0.4.6``.
"""

def __init__(self, uri: str) -> None:
self._uri = uri

@property
def uri(self) -> str:
"""The raw (unmasked) connection URI."""
return self._uri

def __repr__(self) -> str:
return f"ConnectorXConnection({mask_uri(self._uri)!r})"


class ConnectorXEngine(QueryEngine["ConnectorXConnection"]):
"""ConnectorX-backed SQL engine for marimo SQL cells.

Executes queries via ``connectorx.read_sql(..., return_type="arrow")`` and
returns results in the format configured by ``sql_output`` (``polars``,
``lazy-polars``, ``pandas``, ``native``, or ``auto``).

Use :class:`ConnectorXConnection` to wrap a URI and pass it to a SQL cell.
"""

def __init__(
self,
connection: ConnectorXConnection,
engine_name: VariableName | None = None,
) -> None:
super().__init__(connection, engine_name)

@property
def source(self) -> str:
return "connectorx"

@property
def dialect(self) -> str:
return _detect_dialect(self._connection.uri)

@staticmethod
def is_compatible(var: Any) -> bool:
"""Return ``True`` only for :class:`ConnectorXConnection` instances.

Deliberately rejects plain strings so that notebook variables like
``url = "postgresql://..."`` used alongside SQLAlchemy engines are
never captured by this engine.
"""
return isinstance(var, ConnectorXConnection)

def execute(self, query: str) -> Any:
"""Execute *query* via ConnectorX and return a DataFrame."""
DependencyManager.connectorx.require_at_version(
"to execute SQL queries with ConnectorX",
min_version="0.4.6",
)
DependencyManager.pyarrow.require(
"to read ConnectorX results as Arrow"
)
import connectorx as cx

sql_output_format = self.sql_output_format()

raw_password: str | None = None
try:
raw_password = urllib.parse.urlsplit(self._connection.uri).password
except Exception:
pass

try:
table: pa.Table = cx.read_sql(
self._connection.uri,
query,
return_type="arrow",
)
except Exception as exc:
msg = str(exc)
if raw_password:
msg = msg.replace(raw_password, "***")
msg = msg.replace(urllib.parse.unquote(raw_password), "***")
raise RuntimeError(
f"ConnectorX query failed"
f" ({mask_uri(self._connection.uri)}): {msg}"
) from None

def to_polars() -> pl.DataFrame:
import polars as pl

return pl.from_arrow(table)

def to_lazy_polars() -> pl.LazyFrame:
import polars as pl

return pl.from_arrow(table).lazy()

def to_pandas() -> pd.DataFrame:
return table.to_pandas()

return convert_to_output(
sql_output_format=sql_output_format,
to_polars=to_polars,
to_pandas=to_pandas,
to_native=lambda: table,
to_lazy_polars=to_lazy_polars,
)
2 changes: 2 additions & 0 deletions marimo/_sql/get_engines.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
ClickhouseEmbedded,
ClickhouseServer,
)
from marimo._sql.engines.connectorx import ConnectorXEngine
from marimo._sql.engines.dbapi import DBAPIEngine
from marimo._sql.engines.duckdb import INTERNAL_DUCKDB_ENGINE, DuckDBEngine
from marimo._sql.engines.ibis import IbisEngine
Expand All @@ -41,6 +42,7 @@
ClickhouseServer,
PyIcebergEngine,
RedshiftEngine,
ConnectorXEngine,
AdbcDBAPIEngine,
DBAPIEngine,
]
Expand Down
Loading