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: add redshift engine (#5132)

Shahmir Varqha94d7f2da1259
diff --git a/frontend/src/components/datasources/datasources.tsx b/frontend/src/components/datasources/datasources.tsx
index 448b4b9b82..a0dbb52bbd 100644
--- a/frontend/src/components/datasources/datasources.tsx
+++ b/frontend/src/components/datasources/datasources.tsx
@@ -600,6 +600,11 @@ const DatasetTableItem: React.FC<{
}
const columns = table.columns;
+
+ if (columns.length === 0) {
+ return <EmptyState content="No columns found" className="pl-12" />;
+ }
+
return columns.map((column) => (
<DatasetColumnItem
key={column.name}
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index 215405fd88..3dd48415a3 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -207,6 +207,7 @@ class DependencyManager:
loro = Dependency("loro")
boto3 = Dependency("boto3")
litellm = Dependency("litellm")
+ redshift_connector = Dependency("redshift_connector")
# Version requirements to properly support the new superfences introduced in
# pymdown#2470
diff --git a/marimo/_smoke_tests/sql/redshift_example.py b/marimo/_smoke_tests/sql/redshift_example.py
new file mode 100644
index 0000000000..6db90dc869
--- /dev/null
+++ b/marimo/_smoke_tests/sql/redshift_example.py
@@ -0,0 +1,210 @@
+# /// script
+# requires-python = ">=3.12"
+# dependencies = [
+# "marimo",
+# "pandas==2.2.3",
+# "polars[pyarrow]==1.30.0",
+# "redshift-connector[full]==2.1.7",
+# "sqlglot==26.23.0",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.13.14"
+app = marimo.App(width="medium")
+
+
+def _():
+ import marimo as mo
+ import redshift_connector
+ import os
+ return mo, os, redshift_connector
+
+
+def _(mo):
+ mo.md(
+ r"""
+ # Connecting to Redshift via redshift_connector
+
+ Steps:
+
+ 1. Make sure the instance is publicly accessible
+ 2. Check VPC/subnets is public traffic is allowed
+ 3. Navigate to redshift -> workgroup -> obtain connection details
+ """
+ )
+ return
+
+
+def _(os, redshift_connector):
+ # IAM Connection
+ _host = os.environ.get("HOST")
+ _aws_access_key_id = os.environ.get("AWS_ACCESS_KEY_ID")
+ _aws_secret_access_key = os.environ.get("AWS_SECRET_KEY")
+ conn = redshift_connector.connect(
+ iam=True,
+ host=_host,
+ port=5439,
+ region="ap-southeast-1",
+ database="dev",
+ access_key_id=_aws_access_key_id,
+ secret_access_key=_aws_secret_access_key,
+ )
+
+ # Default connection
+ # _conn = redshift_connector.connect(
+ # host="testwg.549569150818.ap-southeast-1.redshift-serverless.amazonaws.com",
+ # database="dev",
+ # user="admin",
+ # password="****",
+ # port=5439,
+ # )
+
+ cursor = conn.cursor()
+ return conn, cursor
+
+
+def _(cursor):
+ cursor.execute("DROP TABLE IF EXISTS users;")
+
+ cursor.execute("""
+ CREATE TABLE IF NOT EXISTS users (
+ user_id INTEGER IDENTITY(1,1) PRIMARY KEY,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ created_date DATE NOT NULL
+ )
+ DISTSTYLE AUTO
+ SORTKEY (user_id);
+ """)
+
+ cursor.execute("""
+ INSERT INTO users (username, email, created_date) VALUES
+ ('john_doe', '[email protected]', '2024-01-15'),
+ ('jane_smith', '[email protected]', '2024-02-20'),
+ ('mike_wilson', '[email protected]', '2024-03-10'),
+ ('sarah_jones', '[email protected]', '2024-04-05'),
+ ('alex_brown', '[email protected]', '2024-05-12');
+ """)
+ return
+
+
+def _(conn, mo):
+ _df = mo.sql(
+ f"""
+ SHOW COLUMNS FROM TABLE dev.public.users;
+ """,
+ engine=conn
+ )
+ return
+
+
+def close_prepared_statements_sample():
+ import ast
+
+ x = """{'S': 'ERROR', 'C': '42P05', 'M': 'prepared statement "redshift_connector_statement_90026_2" already exists', 'F': '/opt/brazil-pkg-cache/packages/RedshiftPADB/RedshiftPADB-1.0.12895.0/AL2_aarch64/generic-flavor/src/src/pg/src/backend/commands/commands_prepare.c', 'L': '685', 'R': 'StorePreparedStatement'}"""
+
+ message = ast.literal_eval(x)["M"]
+ parts = message.split('"')
+
+ # The part within the first pair of double quotes is usually at index 1
+ if len(parts) > 1:
+ extracted_message = parts[1]
+ print(f"Extracted message: {extracted_message}")
+ else:
+ print("Could not find content within double quotes.")
+
+
+def _(mo):
+ mo.md(
+ r"""
+ ## Introspection
+
+ get_tables() ->
+ [
+ "dev", "information_schema", "views", "VIEW", None, "", "", "","", ""
+ ]
+
+ 1. catalog
+ 2. schema
+ 3. table_name
+ 4. table_type
+ 5. unknown
+ 6. unknown
+ 7. unknown
+ 8. unknown
+ 9. unknown
+ 10. unknown
+
+ get_schemas() -> ["information_schema", "dev"]
+
+ 1. schema
+ 2. catalog
+
+ get_columns() -> [
+ "dev",
+ "public",
+ "users",
+ "user_id",
+ 4,
+ "int4",
+ 10,
+ None,
+ 0,
+ 10,
+ 0,
+ None,
+ "\"identity\"(110900, 0, '1,1'::text)",
+ 4,
+ None,
+ 10,
+ 1,
+ "NO",
+ None,
+ None,
+ None,
+ None,
+ "YES",
+ "YES"
+ ]
+
+ 1. catalog
+ 2. schema
+ 3. table_name
+ 4. column_name
+ 5. unknown
+ 6. data type
+ 7. unknown
+ ...
+ 14. unknown
+
+ get_primary_keys() -> [
+ "dev",
+ "public",
+ "users",
+ "user_id",
+ 1,
+ "users_pkey"
+ ]
+
+ 1. catalog
+ 2. schema
+ 3. table_name
+ 4. column_name
+ 5. key_sequence
+ 6. pk_name
+ """
+ )
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_sql/engines/clickhouse.py b/marimo/_sql/engines/clickhouse.py
index 85a49808fd..a919b66161 100644
--- a/marimo/_sql/engines/clickhouse.py
+++ b/marimo/_sql/engines/clickhouse.py
@@ -17,7 +17,6 @@ from marimo._sql.engines.types import (
NO_SCHEMA_NAME,
InferenceConfig,
SQLConnection,
- register_engine,
)
from marimo._sql.utils import raise_df_import_error, sql_type_to_data_type
from marimo._types.ids import VariableName
@@ -35,7 +34,6 @@ WHY_PANDAS_REQUIRED = (
)
-@register_engine
class ClickhouseEmbedded(SQLConnection[Optional["ChdbConnection"]]):
"""Use chdb to connect to an embedded Clickhouse"""
@@ -212,7 +210,6 @@ class ClickhouseEmbedded(SQLConnection[Optional["ChdbConnection"]]):
)
-@register_engine
class ClickhouseServer(SQLConnection[Optional["ClickhouseClient"]]):
"""Use clickhouse.connect to connect to a Clickhouse server"""
diff --git a/marimo/_sql/engines/dbapi.py b/marimo/_sql/engines/dbapi.py
index ae25448945..2e58b3eea4 100644
--- a/marimo/_sql/engines/dbapi.py
+++ b/marimo/_sql/engines/dbapi.py
@@ -5,7 +5,7 @@ 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.engines.types import QueryEngine
from marimo._sql.utils import raise_df_import_error
LOGGER = _loggers.marimo_logger()
@@ -20,7 +20,6 @@ class DBAPIConnection(Protocol):
def commit(self) -> None: ...
-@register_engine
class DBAPIEngine(QueryEngine[DBAPIConnection]):
"""DB-API 2.0 (PEP 249) engine."""
diff --git a/marimo/_sql/engines/doc.md b/marimo/_sql/engines/doc.md
index da1df456b6..13cbb58fcb 100644
--- a/marimo/_sql/engines/doc.md
+++ b/marimo/_sql/engines/doc.md
@@ -53,3 +53,4 @@ Examples of both catalog and query operations:
- DuckDB
- Clickhouse
- Ibis
+- Redshift
diff --git a/marimo/_sql/engines/duckdb.py b/marimo/_sql/engines/duckdb.py
index cc346dfdf3..bf6d824b1c 100644
--- a/marimo/_sql/engines/duckdb.py
+++ b/marimo/_sql/engines/duckdb.py
@@ -7,11 +7,7 @@ from marimo import _loggers
from marimo._data.get_datasets import get_databases_from_duckdb
from marimo._data.models import Database, DataTable
from marimo._dependencies.dependencies import DependencyManager
-from marimo._sql.engines.types import (
- InferenceConfig,
- SQLConnection,
- register_engine,
-)
+from marimo._sql.engines.types import InferenceConfig, SQLConnection
from marimo._sql.utils import raise_df_import_error, wrapped_sql
from marimo._types.ids import VariableName
@@ -24,7 +20,6 @@ if TYPE_CHECKING:
INTERNAL_DUCKDB_ENGINE = cast(VariableName, "__marimo_duckdb")
-@register_engine
class DuckDBEngine(SQLConnection[Optional["duckdb.DuckDBPyConnection"]]):
"""DuckDB SQL engine."""
diff --git a/marimo/_sql/engines/ibis.py b/marimo/_sql/engines/ibis.py
index 8d253554d5..b4aba85eff 100644
--- a/marimo/_sql/engines/ibis.py
+++ b/marimo/_sql/engines/ibis.py
@@ -12,11 +12,7 @@ from marimo._data.models import (
Schema,
)
from marimo._dependencies.dependencies import DependencyManager
-from marimo._sql.engines.types import (
- InferenceConfig,
- SQLConnection,
- register_engine,
-)
+from marimo._sql.engines.types import InferenceConfig, SQLConnection
from marimo._sql.utils import raise_df_import_error
from marimo._types.ids import VariableName
@@ -31,7 +27,6 @@ class IbisToMarimoConversionError(Exception):
"""Raise for unhandled type during Ibis to Marimo conversion"""
-@register_engine
class IbisEngine(SQLConnection["SQLBackend"]):
"""Ibis engine."""
diff --git a/marimo/_sql/engines/pyiceberg.py b/marimo/_sql/engines/pyiceberg.py
index ff7f8fd161..5619cb8ab2 100644
--- a/marimo/_sql/engines/pyiceberg.py
+++ b/marimo/_sql/engines/pyiceberg.py
@@ -15,7 +15,6 @@ from marimo._sql.engines.types import (
NO_SCHEMA_NAME,
EngineCatalog,
InferenceConfig,
- register_engine,
)
from marimo._sql.utils import sql_type_to_data_type
from marimo._types.ids import VariableName
@@ -26,7 +25,6 @@ if TYPE_CHECKING:
from pyiceberg.catalog import Catalog
-@register_engine
class PyIcebergEngine(EngineCatalog["Catalog"]):
"""PyIceberg engine."""
diff --git a/marimo/_sql/engines/redshift.py b/marimo/_sql/engines/redshift.py
new file mode 100644
index 0000000000..e087eff7e0
--- /dev/null
+++ b/marimo/_sql/engines/redshift.py
@@ -0,0 +1,407 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import ast
+from typing import TYPE_CHECKING, Any, Literal, Optional, Union
+
+from marimo import _loggers
+from marimo._data.models import (
+ Database,
+ DataTable,
+ DataTableColumn,
+ DataTableType,
+ DataType,
+ Schema,
+)
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._sql.engines.types import InferenceConfig, SQLConnection
+from marimo._sql.utils import (
+ raise_df_import_error,
+ sql_type_to_data_type,
+ try_convert_to_polars,
+)
+from marimo._types.ids import VariableName
+
+LOGGER = _loggers.marimo_logger()
+
+if TYPE_CHECKING:
+ from redshift_connector import Connection # type: ignore
+
+
+class RedshiftEngine(SQLConnection["Connection"]):
+ """Redshift engine."""
+
+ def __init__(
+ self,
+ connection: Connection,
+ engine_name: Optional[VariableName] = None,
+ ):
+ super().__init__(connection, engine_name)
+
+ @property
+ def source(self) -> str:
+ return "redshift"
+
+ @property
+ def dialect(self) -> str:
+ return "redshift"
+
+ @staticmethod
+ def is_compatible(var: Any) -> bool:
+ if not DependencyManager.redshift_connector.imported():
+ return False
+
+ from redshift_connector import Connection
+
+ return isinstance(var, Connection)
+
+ @property
+ def inference_config(self) -> InferenceConfig:
+ return InferenceConfig(
+ auto_discover_schemas=True,
+ auto_discover_tables=False,
+ auto_discover_columns=False,
+ )
+
+ def _try_commit(self) -> None:
+ try:
+ self._connection.commit()
+ except Exception as e:
+ LOGGER.debug("Failed to commit. Reason: %s.", e)
+
+ def _try_rollback(self) -> None:
+ """
+ Rollback the connection to avoid errors with the connection being in a bad state.
+ For example, after a query failure
+ """
+ from redshift_connector.error import ProgrammingError # type: ignore
+
+ try:
+ self._connection.rollback()
+ except ProgrammingError as e:
+ # Close prepared statements that are left open
+ # They can prevent rollbacks
+ LOGGER.debug(f"Programming error {e}")
+ error_message = ast.literal_eval(str(e))["M"]
+ parts = error_message.split('"')
+ if len(parts) > 1:
+ prepared_statement_name = parts[1]
+ statement_bin = self._connection.get_statement_name_bin(
+ prepared_statement_name
+ )
+ self._connection.close_prepared_statement(
+ statement_name_bin=statement_bin
+ )
+ LOGGER.debug(
+ f"Closing prepared statement {prepared_statement_name}"
+ )
+ try:
+ self._connection.rollback()
+ except Exception as e:
+ LOGGER.debug(
+ "Failed to rollback after closing prepared statement. Reason: %s.",
+ e,
+ )
+ except Exception as e:
+ LOGGER.debug("Failed to rollback. Reason: %s.", e)
+
+ def execute(self, query: str) -> Any:
+ sql_output_format = self.sql_output_format()
+
+ with self._connection.cursor() as cursor:
+ self._try_rollback()
+
+ if sql_output_format == "auto":
+ if DependencyManager.polars.has():
+ sql_output_format = "polars"
+ elif DependencyManager.pandas.has():
+ sql_output_format = "pandas"
+ else:
+ raise_df_import_error("polars[pyarrow]")
+
+ if sql_output_format in ("polars", "lazy-polars"):
+ result, error = try_convert_to_polars(
+ query=query,
+ connection=cursor,
+ lazy=sql_output_format == "lazy-polars",
+ )
+ if error is None:
+ self._try_commit()
+ return result
+
+ LOGGER.warning(
+ "Failed to convert to polars. Reason: %s.", error
+ )
+ DependencyManager.pandas.require("to convert this data")
+ # Fall back to pandas
+ sql_output_format = "pandas"
+
+ cursor_result = cursor.execute(query)
+ self._try_commit()
+
+ if sql_output_format == "native":
+ return cursor_result
+ if sql_output_format == "pandas":
+ return cursor_result.fetch_dataframe()
+ return cursor_result
+
+ def get_default_database(self) -> Optional[str]:
+ with self._connection.cursor() as cursor:
+ try:
+ return str(cursor.cur_catalog())
+ except Exception as e:
+ LOGGER.debug("Failed to get default database. Reason: %s.", e)
+ return None
+
+ def get_default_schema(self) -> Optional[str]:
+ with self._connection.cursor() as cursor:
+ try:
+ result = cursor.execute("SELECT current_schema()")
+ return str(result.fetchone()[0])
+ except Exception as e:
+ LOGGER.debug("Failed to get default schema. Reason: %s.", e)
+ return None
+
+ 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 catalogs from the engine. Redshift only supports one catalog per connection.
+
+ Catalogs -> Schemas -> Tables
+ """
+
+ with self._connection.cursor() as cursor:
+ try:
+ # get_catalogs only returns current catalog
+ catalog = cursor.get_catalogs()[0][0]
+ except Exception as e:
+ LOGGER.debug("Failed to get catalogs. Reason: %s.", e)
+ return []
+
+ databases: list[Database] = []
+
+ include_schemas = self._resolve_should_auto_discover(
+ include_schemas
+ )
+ include_tables = self._resolve_should_auto_discover(include_tables)
+ include_table_details = self._resolve_should_auto_discover(
+ include_table_details
+ )
+
+ schemas: list[Schema] = []
+ if include_schemas:
+ schemas = self.get_schemas(
+ catalog=catalog,
+ include_tables=include_tables,
+ include_table_details=include_table_details,
+ )
+
+ databases.append(
+ Database(
+ name=catalog,
+ dialect=self.dialect,
+ schemas=schemas,
+ engine=self._engine_name,
+ )
+ )
+
+ return databases
+
+ def get_schemas(
+ self,
+ *,
+ catalog: str,
+ include_tables: bool,
+ include_table_details: bool,
+ ) -> list[Schema]:
+ """Get schemas from the engine."""
+
+ output_schemas: list[Schema] = []
+ with self._connection.cursor() as cursor:
+ # get_schemas returns [["schema_name", "catalog"], ["schema_2", "catalog"]]
+ schemas = cursor.get_schemas(catalog=catalog)
+
+ for schema in schemas:
+ schema_name = schema[0]
+ if schema_name == "information_schema": # Skip meta-schemas
+ continue
+
+ tables = (
+ self.get_tables_in_schema(
+ schema=schema_name,
+ database=catalog,
+ include_table_details=include_table_details,
+ )
+ if include_tables
+ else []
+ )
+ output_schemas.append(Schema(name=schema_name, tables=tables))
+
+ return output_schemas
+
+ def get_tables_in_schema(
+ self, *, schema: str, database: str, include_table_details: bool
+ ) -> list[DataTable]:
+ """Get tables from the engine. Databases are treated as catalogs."""
+
+ output_tables: list[DataTable] = []
+
+ with self._connection.cursor() as cursor:
+ # get_tables returns [["catalog", "schema", "table_name", "table_type (VIEW / TABLE)", None, "", ...]]
+ try:
+ tables = cursor.get_tables(
+ catalog=database, schema_pattern=schema
+ )
+ except Exception as e:
+ LOGGER.debug("Failed to get tables. Reason: %s.", e)
+ return []
+
+ for table in tables:
+ table_name, table_type = table[2], table[3]
+ table_type = self._resolve_table_type(table_type)
+
+ # If we are satisfied with this info, we can return
+ if not include_table_details:
+ output_tables.append(
+ DataTable(
+ source_type="connection",
+ source=self.dialect,
+ name=table_name,
+ num_rows=None,
+ num_columns=None,
+ variable_name=None,
+ engine=self._engine_name,
+ type=table_type,
+ columns=[],
+ primary_keys=[],
+ indexes=[],
+ )
+ )
+ continue
+
+ detailed_table = self.get_table_details(
+ table_name=table_name,
+ schema_name=schema,
+ database_name=database,
+ )
+ if detailed_table is not None:
+ output_tables.append(detailed_table)
+ return output_tables
+
+ def _get_columns_api(
+ self,
+ *,
+ catalog: str,
+ schema_name: str,
+ table_name: str,
+ ) -> tuple[tuple[str, ...], ...]:
+ """The API is unreliable hence this method is not preferred"""
+ columns: tuple[tuple[str, ...], ...] = ()
+ with self._connection.cursor() as cursor:
+ try:
+ # get_columns returns:
+ # [[catalog, schema, table_name, column_name, unknown, data type, unknown, ...], ...]
+ columns = cursor.get_columns(
+ catalog=catalog,
+ schema_pattern=schema_name,
+ tablename_pattern=table_name,
+ )
+ except Exception as e:
+ LOGGER.debug(
+ f"Failed to get columns for {catalog}.{schema_name}.{table_name} Reason: {e}"
+ )
+ return columns
+
+ def get_table_details(
+ self, *, table_name: str, schema_name: str, database_name: str
+ ) -> Optional[DataTable]:
+ """Get detailed metadata for a given table in a database."""
+
+ with self._connection.cursor() as cursor:
+ try:
+ table = cursor.get_tables(
+ catalog=database_name,
+ schema_pattern=schema_name,
+ table_name_pattern=table_name,
+ )
+ except Exception as e:
+ LOGGER.debug("Failed to get table. Reason: %s.", e)
+ return None
+
+ table_type = self._resolve_table_type(table[0][3])
+
+ row_count = cursor.execute(
+ f"SELECT COUNT(*) FROM {database_name}.{schema_name}.{table_name}"
+ )
+ num_rows = row_count.fetchone()[0]
+
+ try:
+ # [[catalog, schema, table_name, column_name, ordinal_position, column_default, is_nullable, data_type, character_maximum_length, numeric_precision, numeric_scale, remarks]]
+ columns = cursor.execute(
+ f"SHOW COLUMNS FROM TABLE {database_name}.{schema_name}.{table_name};"
+ )
+ except Exception as e:
+ LOGGER.debug(
+ f"Failed to get columns for {database_name}.{schema_name}.{table_name}. Reason: {e}"
+ )
+ columns = []
+
+ cols: list[DataTableColumn] = []
+ for col in columns:
+ col_name, col_type = col[3], col[7]
+ data_type = self._get_data_type(
+ col_type
+ ) or sql_type_to_data_type(col_type)
+ cols.append(
+ DataTableColumn(
+ name=col_name,
+ type=data_type,
+ external_type=str(col_type),
+ sample_values=[],
+ )
+ )
+
+ # get_primary_keys returns:
+ # [[catalog, schema, table_name, column_name, key_seq, pk_name], ...]
+ primary_keys = cursor.get_primary_keys(
+ catalog=database_name, schema=schema_name, table=table_name
+ )
+
+ primary_keys = [pk[3] for pk in primary_keys]
+
+ return DataTable(
+ source_type="connection",
+ source=self.dialect,
+ name=table_name,
+ num_rows=num_rows,
+ num_columns=len(cols),
+ variable_name=None,
+ engine=self._engine_name,
+ type=table_type,
+ columns=cols,
+ primary_keys=primary_keys,
+ indexes=[],
+ )
+
+ def _resolve_table_type(self, table_type: str) -> DataTableType:
+ return "view" if table_type == "VIEW" else "table"
+
+ def _get_data_type(self, data_type: str) -> Optional[DataType]:
+ data_type = data_type.lower()
+ if "cardinal_number" in data_type:
+ return "number"
+ elif "character_data" in data_type:
+ return "string"
+ return None
+
+ def _resolve_should_auto_discover(
+ self, value: Union[bool, Literal["auto"]]
+ ) -> bool:
+ # Opt to not auto-discover for now
+ if value == "auto":
+ return False
+ return value
diff --git a/marimo/_sql/engines/sqlalchemy.py b/marimo/_sql/engines/sqlalchemy.py
index 7bbbf45f23..6eeb3e3478 100644
--- a/marimo/_sql/engines/sqlalchemy.py
+++ b/marimo/_sql/engines/sqlalchemy.py
@@ -13,11 +13,7 @@ from marimo._data.models import (
Schema,
)
from marimo._dependencies.dependencies import DependencyManager
-from marimo._sql.engines.types import (
- InferenceConfig,
- SQLConnection,
- register_engine,
-)
+from marimo._sql.engines.types import InferenceConfig, SQLConnection
from marimo._sql.utils import raise_df_import_error, sql_type_to_data_type
from marimo._types.ids import VariableName
@@ -29,7 +25,6 @@ if TYPE_CHECKING:
from sqlalchemy.sql.type_api import TypeEngine
-@register_engine
class SQLAlchemyEngine(SQLConnection["Engine"]):
"""SQLAlchemy engine."""
@@ -102,10 +97,9 @@ class SQLAlchemyEngine(SQLConnection["Engine"]):
except (
pl.exceptions.PanicException,
pl.exceptions.ComputeError,
- ):
- LOGGER.info(
- "Failed to convert to polars, falling back to pandas"
- )
+ ) as e:
+ LOGGER.warning(f"Failed to convert to polars. Reason: {e}")
+ DependencyManager.pandas.require("to convert this data")
if DependencyManager.pandas.has():
import pandas as pd
diff --git a/marimo/_sql/engines/types.py b/marimo/_sql/engines/types.py
index 330afdb280..c376fee66c 100644
--- a/marimo/_sql/engines/types.py
+++ b/marimo/_sql/engines/types.py
@@ -15,7 +15,6 @@ from marimo._runtime.context.types import (
)
from marimo._types.ids import VariableName
-ENGINE_REGISTRY: list[type[BaseEngine[Any]]] = []
NO_SCHEMA_NAME = ""
@@ -72,11 +71,6 @@ class BaseEngine(ABC, Generic[CONN]):
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."""
@@ -130,6 +124,7 @@ class QueryEngine(BaseEngine[CONN], ABC):
"""Execute a SQL query and return a dataframe."""
pass
+ # TODO: Maybe this should be called during init of db's
def sql_output_format(self) -> SqlOutputType:
if runtime_context_installed():
try:
diff --git a/marimo/_sql/get_engines.py b/marimo/_sql/get_engines.py
index fd1d4b3a03..1cca757919 100644
--- a/marimo/_sql/get_engines.py
+++ b/marimo/_sql/get_engines.py
@@ -22,6 +22,7 @@ from marimo._sql.engines.duckdb import (
)
from marimo._sql.engines.ibis import IbisEngine
from marimo._sql.engines.pyiceberg import PyIcebergEngine
+from marimo._sql.engines.redshift import RedshiftEngine
from marimo._sql.engines.sqlalchemy import SQLAlchemyEngine
from marimo._sql.engines.types import (
BaseEngine,
@@ -31,26 +32,27 @@ from marimo._types.ids import VariableName
LOGGER = _loggers.marimo_logger()
+# 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,
+ RedshiftEngine,
+ DBAPIEngine,
+]
+
def get_engines_from_variables(
variables: list[tuple[VariableName, object]],
) -> list[tuple[VariableName, BaseEngine[Any]]]:
engines: list[tuple[VariableName, BaseEngine[Any]]] = []
- # 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:
- for sql_engine in supported_engines:
+ for sql_engine in SUPPORTED_ENGINES:
if sql_engine.is_compatible(value):
engines.append(
(
diff --git a/marimo/_sql/sql.py b/marimo/_sql/sql.py
index bf3b37b1f5..ee83925e41 100644
--- a/marimo/_sql/sql.py
+++ b/marimo/_sql/sql.py
@@ -2,18 +2,16 @@
from __future__ import annotations
import os
-from typing import TYPE_CHECKING, Any, Literal, Optional, cast
+from typing import Any, Literal, Optional, cast
from marimo._dependencies.dependencies import DependencyManager
from marimo._output.rich_help import mddoc
from marimo._runtime.output import replace
+from marimo._sql.engines.dbapi import DBAPIConnection
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,
- QueryEngine,
-)
+from marimo._sql.engines.types import QueryEngine
+from marimo._sql.get_engines import SUPPORTED_ENGINES
from marimo._sql.utils import raise_df_import_error
from marimo._types.ids import VariableName
from marimo._utils.narwhals_utils import can_narwhalify_lazyframe
@@ -24,25 +22,12 @@ def get_default_result_limit() -> Optional[int]:
return int(limit) if limit is not None else None
-if TYPE_CHECKING:
- from chdb.state.sqlitelike import Connection as ChdbConnection # type: ignore # noqa: I001
- from clickhouse_connect.driver.client import Client as ClickhouseClient # type: ignore
- from duckdb import DuckDBPyConnection
- from sqlalchemy.engine import Engine as SAEngine
-
-
@mddoc
def sql(
query: str,
*,
output: bool = True,
- engine: Optional[
- SAEngine
- | DuckDBPyConnection
- | ClickhouseClient
- | ChdbConnection
- | IbisEngine
- ] = None,
+ engine: Optional[DBAPIConnection] = None,
) -> Any:
"""
Execute a SQL query.
@@ -50,14 +35,14 @@ def sql(
By default, this uses duckdb to execute the query. Any dataframes in the global
namespace can be used inside the query.
- You can also pass a SQLAlchemy engine to execute queries against other databases.
+ You can also pass a custom engine to execute queries against other databases. The custom engine must be a DBAPI 2.0 compatible engine.
The result of the query is displayed in the UI if output is True.
Args:
query: The SQL query to execute.
output: Whether to display the result in the UI. Defaults to True.
- engine: Optional SQL engine to use. Can be a SQLAlchemy, Clickhouse, or DuckDB engine.
+ engine: Optional SQL engine to use. Can be a SQLAlchemy, DuckDB, Clickhouse, Redshift, Ibis, or DBAPI 2.0 compatible engine.
If None, uses DuckDB.
Returns:
@@ -75,7 +60,7 @@ def sql(
)
sql_engine = DuckDBEngine(connection=None)
else:
- for engine_cls in ENGINE_REGISTRY:
+ for engine_cls in SUPPORTED_ENGINES:
if engine_cls.is_compatible(engine):
sql_engine = engine_cls(
connection=engine, engine_name=VariableName("custom")
@@ -83,7 +68,7 @@ def sql(
break
else:
raise ValueError(
- "Unsupported engine. Must be a SQLAlchemy, Ibis, Clickhouse, or DuckDB engine."
+ "Unsupported engine. Must be a SQLAlchemy, Ibis, Clickhouse, DuckDB, Redshift or DBAPI 2.0 compatible engine."
)
df = sql_engine.execute(query)
diff --git a/marimo/_sql/utils.py b/marimo/_sql/utils.py
index b5642c172a..0e0b0a5a11 100644
--- a/marimo/_sql/utils.py
+++ b/marimo/_sql/utils.py
@@ -12,6 +12,8 @@ from marimo._runtime.context.types import (
if TYPE_CHECKING:
import duckdb
+ import polars as pl
+ from polars._typing import ConnectionOrCursor
def wrapped_sql(
@@ -44,6 +46,30 @@ def wrapped_sql(
return relation
+def try_convert_to_polars(
+ *,
+ query: str,
+ connection: ConnectionOrCursor,
+ lazy: bool,
+) -> tuple[Optional[pl.DataFrame | pl.LazyFrame], Optional[str]]:
+ """Try to convert the query to a polars dataframe.
+
+ Returns:
+ - The polars dataframe, or None if the conversion failed.
+ - Error message, or None if the conversion succeeded.
+ """
+ import polars as pl
+
+ try:
+ df = pl.read_database(query=query, connection=connection)
+ return df.lazy() if lazy else df, None
+ except (
+ pl.exceptions.PanicException,
+ pl.exceptions.ComputeError,
+ ) as e:
+ return None, e
+
+
def raise_df_import_error(pkg: str) -> None:
raise ModuleNotFoundError(
"pandas or polars is required to execute sql. "
@@ -63,6 +89,8 @@ def sql_type_to_data_type(type_str: str) -> DataType:
return "datetime"
elif "date" in type_str:
return "date"
+ elif "time" in type_str:
+ return "time"
elif "bool" in type_str:
return "boolean"
elif any(x in type_str for x in ("char", "text")):
diff --git a/pyproject.toml b/pyproject.toml
index 4d981b5428..40ab6e67e4 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -267,6 +267,7 @@ extra-dependencies = [
# For testing clickhouse
"chdb>=3; platform_system != 'Windows'", # there is no suitable wheel for windows
"clickhouse-connect>=0.8.17",
+ "redshift-connector[full]>=2.1.7",
"pandas>=1.5.3",
"hvplot~=0.11.3",
# Causes issues installing `shapely` (v2.0.7)
@@ -460,6 +461,8 @@ banned-module-level-imports = [
"sqlglot",
"tomlkit",
"typing_extensions",
+ "pyiceberg",
+ "redshift_connector",
]
[tool.ruff.lint.flake8-pytest-style]
diff --git a/tests/_sql/test_engines.py b/tests/_sql/test_engines.py
index e807386292..c412818a95 100644
--- a/tests/_sql/test_engines.py
+++ b/tests/_sql/test_engines.py
@@ -319,6 +319,9 @@ def test_sql_type_to_data_type() -> None:
# Test date type
assert sql_type_to_data_type("DATE") == "date"
+ # Test time type
+ assert sql_type_to_data_type("TIME") == "time"
+
# Test boolean type
assert sql_type_to_data_type("BOOLEAN") == "boolean"
diff --git a/tests/_sql/test_get_engines.py b/tests/_sql/test_get_engines.py
index a861309124..d2075f631a 100644
--- a/tests/_sql/test_get_engines.py
+++ b/tests/_sql/test_get_engines.py
@@ -18,6 +18,7 @@ from marimo._sql.engines.duckdb import (
DuckDBEngine,
)
from marimo._sql.engines.ibis import IbisEngine
+from marimo._sql.engines.redshift import RedshiftEngine
from marimo._sql.engines.sqlalchemy import SQLAlchemyEngine
from marimo._sql.get_engines import (
engine_to_data_source_connection,
@@ -30,6 +31,7 @@ HAS_SQLALCHEMY = DependencyManager.sqlalchemy.has()
HAS_IBIS = DependencyManager.ibis.has()
HAS_DUCKDB = DependencyManager.duckdb.has()
HAS_CLICKHOUSE = DependencyManager.chdb.has()
+HAS_REDSHIFT = DependencyManager.redshift_connector.has()
@pytest.mark.skipif(not HAS_SQLALCHEMY, reason="SQLAlchemy not installed")
@@ -127,6 +129,22 @@ def test_get_engines_from_variables_clickhouse():
assert isinstance(engine, ClickhouseEmbedded)
[email protected](not HAS_REDSHIFT, reason="Redshift not installed")
+def test_get_engines_from_variables_redshift():
+ import redshift_connector
+
+ mock_redshift_conn = MagicMock(spec=redshift_connector.Connection)
+ variables: list[tuple[str, object]] = [
+ ("redshift_conn", mock_redshift_conn)
+ ]
+
+ engines = get_engines_from_variables(variables)
+ assert len(engines) == 1
+ var_name, engine = engines[0]
+ assert var_name == "redshift_conn"
+ assert isinstance(engine, RedshiftEngine)
+
+
@pytest.mark.skipif(not HAS_SQLALCHEMY, reason="SQLAlchemy not installed")
def test_get_engines_from_variables_sqlalchemy() -> None:
import sqlalchemy as sa
diff --git a/tests/_sql/test_redshift.py b/tests/_sql/test_redshift.py
new file mode 100644
index 0000000000..edf2323fc6
--- /dev/null
+++ b/tests/_sql/test_redshift.py
@@ -0,0 +1,82 @@
+"""Tests for Redshift engine."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+from unittest import mock
+
+import pytest
+
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._sql.engines.redshift import RedshiftEngine
+from marimo._sql.engines.types import EngineCatalog, QueryEngine
+from marimo._types.ids import VariableName
+
+HAS_REDSHIFT = DependencyManager.redshift_connector.has()
+
+if TYPE_CHECKING:
+ from collections.abc import Generator
+
+ from redshift_connector import Connection
+
+
+def mock_connection() -> Generator[Connection, None, None]:
+ """Create a mock Redshift connection for testing."""
+ if not HAS_REDSHIFT:
+ yield mock.MagicMock()
+ return
+
+ from redshift_connector import Connection
+
+ # Create mock connection
+ connection = mock.MagicMock(spec=Connection)
+
+ # Mock cursor methods
+ cursor = mock.MagicMock()
+ connection.cursor.return_value = cursor
+
+ yield connection
+
+
+ not HAS_REDSHIFT, reason="Redshift connector not installed"
+)
+def test_engine_compatibility(mock_connection: Connection) -> None:
+ """Test engine compatibility checks."""
+ assert RedshiftEngine.is_compatible(mock_connection)
+ assert not RedshiftEngine.is_compatible(object())
+
+ engine = RedshiftEngine(
+ mock_connection, engine_name=VariableName("my_redshift")
+ )
+ assert isinstance(engine, RedshiftEngine)
+ assert isinstance(engine, EngineCatalog)
+ assert isinstance(engine, QueryEngine)
+
+
+ not HAS_REDSHIFT, reason="Redshift connector not installed"
+)
+def test_engine_name_initialization(mock_connection: Connection) -> None:
+ """Test engine name initialization."""
+ engine = RedshiftEngine(
+ mock_connection, engine_name=VariableName("my_redshift")
+ )
+ assert engine._engine_name == VariableName("my_redshift")
+
+ # Test default name
+ engine = RedshiftEngine(mock_connection)
+ assert engine._engine_name is None
+
+
+ not HAS_REDSHIFT, reason="Redshift connector not installed"
+)
+def test_redshift_engine_source_and_dialect(
+ mock_connection: Connection,
+) -> None:
+ """Test RedshiftEngine source and dialect properties."""
+ engine = RedshiftEngine(mock_connection)
+ assert engine.source == "redshift"
+ assert engine.dialect == "redshift"