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 column summaries for sql tables in the datasources panel (#2569)

Myles Scolnicka66f1185e7db
diff --git a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx b/frontend/src/components/editor/chrome/panels/datasources-panel.tsx
index 634a83261c..f75228c249 100644
--- a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/datasources-panel.tsx
@@ -422,22 +422,6 @@ const DatasetColumnPreview: React.FC<{
}> = ({ table, column, preview, onAddColumnChart }) => {
const { theme } = useTheme();
- if (table.source_type === "duckdb") {
- return (
- <Button
- variant="text"
- className="z-10"
- size="xs"
- onClick={Events.stopPropagation(() => {
- const code = `_df = mo.sql(f"SELECT '${column.name}' FROM ${table.name} LIMIT 100")`;
- onAddColumnChart(code);
- })}
- >
- <PlusSquareIcon className="h-4 w-4 mr-2" /> Add cell
- </Button>
- );
- }
-
if (!preview) {
return <span className="text-xs text-muted-foreground">Loading...</span>;
}
@@ -487,15 +471,32 @@ const DatasetColumnPreview: React.FC<{
/>
);
- const addChart = preview.chart_code && (
- <Tooltip content="Add chart to notebook" delayDuration={400}>
+ const addDataframeChart = preview.chart_code &&
+ table.source_type === "local" && (
+ <Tooltip content="Add chart to notebook" delayDuration={400}>
+ <Button
+ variant="outline"
+ size="icon"
+ className="z-10 bg-background absolute right-1 top-0"
+ onClick={Events.stopPropagation(() =>
+ onAddColumnChart(preview.chart_code || ""),
+ )}
+ >
+ <PlusSquareIcon className="h-3 w-3" />
+ </Button>
+ </Tooltip>
+ );
+
+ const addSQLChart = table.source_type === "duckdb" && (
+ <Tooltip content="Add SQL cell" delayDuration={400}>
<Button
variant="outline"
size="icon"
className="z-10 bg-background absolute right-1 top-0"
- onClick={Events.stopPropagation(() =>
- onAddColumnChart(preview.chart_code || ""),
- )}
+ onClick={Events.stopPropagation(() => {
+ const code = `_df = mo.sql(f"SELECT '${column.name}' FROM ${table.name} LIMIT 100")`;
+ onAddColumnChart(code);
+ })}
>
<PlusSquareIcon className="h-3 w-3" />
</Button>
@@ -515,7 +516,8 @@ const DatasetColumnPreview: React.FC<{
return (
<div className="flex flex-col gap-2 relative">
{error}
- {addChart}
+ {addDataframeChart}
+ {addSQLChart}
{chartMaxRowsWarning}
{chart}
{summary}
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.py
index 6c9087b40d..f13171f8b5 100644
--- a/marimo/_ast/visitor.py
+++ b/marimo/_ast/visitor.py
@@ -466,7 +466,7 @@ class ScopedVisitor(ast.NodeVisitor):
#
# This breaks dependency parsing.
statements = duckdb.extract_statements(sql)
- except duckdb.ProgrammingError:
+ except (duckdb.ProgrammingError, duckdb.IOException):
# The user's sql query may have a syntax error,
# or duckdb failed for an unknown reason; don't
# break marimo.
@@ -488,7 +488,7 @@ class ScopedVisitor(ast.NodeVisitor):
# of the statement -- schemas can show up in
# joins, queries, ...
from_targets = find_from_targets(statement.query)
- except duckdb.ProgrammingError:
+ except (duckdb.ProgrammingError, duckdb.IOException):
self.generic_visit(node)
continue
except BaseException as e:
diff --git a/marimo/_data/charts.py b/marimo/_data/charts.py
index 5b89a48a15..4e66bd76d8 100644
--- a/marimo/_data/charts.py
+++ b/marimo/_data/charts.py
@@ -7,6 +7,7 @@ from textwrap import dedent
from typing import Any, cast
from marimo._data.models import DataType
+from marimo._utils import assert_never
@abc.abstractmethod
@@ -285,6 +286,8 @@ def get_chart_builder(
if column_type == "unknown":
return WrapperChartBuilder(UnknownChartBuilder())
+ assert_never(column_type)
+
def _escape_special_path_characters(column: str | int) -> str:
"""
diff --git a/marimo/_data/get_datasets.py b/marimo/_data/get_datasets.py
index 74dc5c5ecd..307b05f490 100644
--- a/marimo/_data/get_datasets.py
+++ b/marimo/_data/get_datasets.py
@@ -138,20 +138,61 @@ def _get_datasets_from_duckdb_internal() -> List[DataTable]:
def _db_type_to_data_type(db_type: str) -> DataType:
- if db_type == "INTEGER":
+ db_type = db_type.lower()
+ # Numeric types
+ if db_type in [
+ "tinyint",
+ "smallint",
+ "integer",
+ "bigint",
+ "hugeint",
+ "utinyint",
+ "usmallint",
+ "uinteger",
+ "ubigint",
+ "uhugeint",
+ ]:
return "integer"
- if db_type == "FLOAT":
+ if db_type in [
+ "float",
+ "real",
+ "double",
+ "decimal",
+ "numeric",
+ ] or db_type.startswith("decimal"):
return "number"
- if db_type == "BOOLEAN":
+ # Boolean type
+ if db_type == "boolean":
return "boolean"
- if db_type == "VARCHAR":
+ # String types
+ if db_type in [
+ "varchar",
+ "char",
+ "bpchar",
+ "text",
+ "string",
+ "blob",
+ "uuid",
+ ]:
return "string"
- if db_type == "DATE":
- return "date"
- if db_type == "DATETIME":
- return "date"
- if db_type == "TIMESTAMP":
- return "date"
- if db_type == "TIME":
+ # Date and Time types
+ if db_type in [
+ "date",
+ "time",
+ "timestamp",
+ "timestamp with time zone",
+ "timestamptz",
+ "datetime",
+ "interval",
+ ]:
return "date"
+ # Nested types
+ if db_type in ["array", "list", "struct", "map", "union"]:
+ return "unknown"
+ # Special types
+ if db_type == "bit":
+ return "string" # Representing bit as string
+ if db_type == "enum":
+ return "string" # Representing enum as string
+ # Unknown type
return "unknown"
diff --git a/marimo/_data/preview_column.py b/marimo/_data/preview_column.py
index 33aabe5180..918b9b4b48 100644
--- a/marimo/_data/preview_column.py
+++ b/marimo/_data/preview_column.py
@@ -6,6 +6,11 @@ from typing import Any, Optional
from marimo import _loggers
from marimo._data.charts import get_chart_builder
from marimo._data.models import ColumnSummary
+from marimo._data.sql_summaries import (
+ get_column_type,
+ get_histogram_data,
+ get_sql_summary,
+)
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.ops import DataColumnPreview
from marimo._plugins.ui._impl.tables.table_manager import TableManager
@@ -15,7 +20,7 @@ from marimo._runtime.requests import PreviewDatasetColumnRequest
LOGGER = _loggers.marimo_logger()
-def get_column_preview(
+def get_column_preview_dataframe(
item: object,
request: PreviewDatasetColumnRequest,
) -> DataColumnPreview | None:
@@ -109,6 +114,44 @@ def get_column_preview(
)
+def get_column_preview_for_sql(
+ table_name: str,
+ column_name: str,
+) -> Optional[DataColumnPreview]:
+ # Drop memory.main
+ if table_name.startswith("memory.main."):
+ query_table_name = table_name.replace("memory.main.", "")
+ else:
+ query_table_name = table_name
+
+ column_type = get_column_type(query_table_name, column_name)
+ summary = get_sql_summary(query_table_name, column_name, column_type)
+ histogram_data = get_histogram_data(query_table_name, column_name)
+
+ # Generate Altair chart
+ chart_spec = None
+ chart_code = None
+ chart_max_rows_errors = False
+
+ if histogram_data and DependencyManager.altair.has():
+ chart_builder = get_chart_builder(column_type, False)
+ try:
+ chart_spec = chart_builder.altair_json(histogram_data, column_name)
+ chart_code = chart_builder.altair_code(table_name, column_name)
+ except Exception as e:
+ LOGGER.warning(f"Failed to generate Altair chart: {str(e)}")
+
+ return DataColumnPreview(
+ table_name=table_name,
+ column_name=column_name,
+ chart_max_rows_errors=chart_max_rows_errors,
+ chart_spec=chart_spec,
+ chart_code=chart_code,
+ summary=summary,
+ error=None,
+ )
+
+
def _get_altair_chart(
request: PreviewDatasetColumnRequest,
table: TableManager[Any],
diff --git a/marimo/_data/sql_summaries.py b/marimo/_data/sql_summaries.py
new file mode 100644
index 0000000000..bfaa65799c
--- /dev/null
+++ b/marimo/_data/sql_summaries.py
@@ -0,0 +1,156 @@
+from __future__ import annotations
+
+from typing import List, Tuple
+
+from marimo._data.get_datasets import _db_type_to_data_type
+from marimo._data.models import ColumnSummary, DataType
+from marimo._sql.sql import _wrapped_sql
+
+
+def get_sql_summary(
+ table_name: str, column_name: str, column_type: DataType
+) -> ColumnSummary:
+ """
+ Get a summary of a column in a SQL table.
+ """
+
+ # Prepare the stats query based on the column type
+ if column_type in ("integer", "number"):
+ stats_query = f"""
+ SELECT
+ COUNT(*) as count,
+ COUNT(DISTINCT "{column_name}") as unique,
+ SUM(CASE WHEN "{column_name}" IS NULL THEN 1 ELSE 0 END) as null_count,
+ MIN("{column_name}") as min,
+ MAX("{column_name}") as max,
+ AVG("{column_name}") as mean,
+ PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY "{column_name}") as median,
+ STDDEV("{column_name}") as std,
+ PERCENTILE_CONT(0.05) WITHIN GROUP (ORDER BY "{column_name}") as p5,
+ PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY "{column_name}") as p25,
+ PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY "{column_name}") as p75,
+ PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY "{column_name}") as p95
+ FROM {table_name}
+ """ # noqa: E501
+ elif column_type == "date":
+ stats_query = f"""
+ SELECT
+ COUNT(*) as count,
+ COUNT(DISTINCT "{column_name}") as unique,
+ SUM(CASE WHEN "{column_name}" IS NULL THEN 1 ELSE 0 END) as null_count,
+ MIN("{column_name}") as min,
+ MAX("{column_name}") as max
+ FROM {table_name}
+ """ # noqa: E501
+ elif column_type == "boolean":
+ stats_query = f"""
+ SELECT
+ COUNT(*) as count,
+ COUNT(DISTINCT "{column_name}") as unique,
+ SUM(CASE WHEN "{column_name}" IS NULL THEN 1 ELSE 0 END) as null_count,
+ SUM(CASE WHEN "{column_name}" = TRUE THEN 1 ELSE 0 END) as true_count,
+ SUM(CASE WHEN "{column_name}" = FALSE THEN 1 ELSE 0 END) as false_count
+ FROM {table_name}
+ """ # noqa: E501
+ else:
+ stats_query = f"""
+ SELECT
+ COUNT(*) as count,
+ COUNT(DISTINCT "{column_name}") as unique,
+ SUM(CASE WHEN "{column_name}" IS NULL THEN 1 ELSE 0 END) as null_count
+ FROM {table_name}
+ """ # noqa: E501
+
+ stats_result: Tuple[int, ...] | None = _wrapped_sql(stats_query).fetchone()
+ if stats_result is None:
+ raise ValueError(
+ f"Column {column_name} not found in table {table_name}"
+ )
+
+ if column_type in ("integer", "number"):
+ (
+ count,
+ unique,
+ null_count,
+ min_val,
+ max_val,
+ mean,
+ median,
+ std,
+ p5,
+ p25,
+ p75,
+ p95,
+ ) = stats_result
+ return ColumnSummary(
+ total=count,
+ unique=unique,
+ nulls=null_count,
+ min=min_val,
+ max=max_val,
+ mean=mean,
+ median=median,
+ std=std,
+ p5=p5,
+ p25=p25,
+ p75=p75,
+ p95=p95,
+ )
+ elif column_type == "date":
+ count, unique, null_count, min_val, max_val = stats_result
+ return ColumnSummary(
+ total=count,
+ unique=unique,
+ nulls=null_count,
+ min=min_val,
+ max=max_val,
+ )
+ elif column_type == "boolean":
+ count, unique, null_count, true_count, false_count = stats_result
+ return ColumnSummary(
+ total=count,
+ unique=unique,
+ nulls=null_count,
+ true=true_count,
+ false=false_count,
+ )
+ else:
+ count, unique, null_count = stats_result
+ return ColumnSummary(total=count, unique=unique, nulls=null_count)
+
+
+def get_column_type(table_name: str, column_name: str) -> DataType:
+ """
+ Get the type of a column in a SQL table.
+ """
+
+ # First, get the column info and data type
+ column_info_query = f"""
+ SELECT data_type
+ FROM information_schema.columns
+ WHERE table_name = '{table_name}'
+ AND column_name = '{column_name}'
+ """
+
+ column_info_result: Tuple[str] | None = _wrapped_sql(
+ column_info_query
+ ).fetchone()
+ if column_info_result is None:
+ raise ValueError(
+ f"Column {column_name} not found in table {table_name}"
+ )
+
+ db_column_type = column_info_result[0].lower()
+ return _db_type_to_data_type(db_column_type)
+
+
+def get_histogram_data(
+ table_name: str, column_name: str
+) -> List[Tuple[str, int]]:
+ """
+ Get the histogram data for a column in a SQL table.
+ """
+ del table_name, column_name
+ # TODO: Implement this
+
+ return []
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index dc161c6adb..a8899975d6 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -25,7 +25,10 @@ from marimo._ast.compiler import compile_cell
from marimo._ast.visitor import ImportData, Name, VariableData
from marimo._config.config import ExecutionType, MarimoConfig, OnCellChangeType
from marimo._config.settings import GLOBAL_SETTINGS
-from marimo._data.preview_column import get_column_preview
+from marimo._data.preview_column import (
+ get_column_preview_dataframe,
+ get_column_preview_for_sql,
+)
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.cell_output import CellChannel
from marimo._messaging.errors import (
@@ -1793,35 +1796,43 @@ class Kernel:
The dataset is loaded, and the column is displayed in the frontend.
"""
+ table_name = request.table_name
+ column_name = request.column_name
+ source_type = request.source_type
- if request.source_type == "duckdb":
- DataColumnPreview(
- column_name=request.column_name,
- table_name=request.table_name,
- ).broadcast()
- return
+ try:
+ if source_type == "duckdb":
+ column_preview = get_column_preview_for_sql(
+ table_name=table_name,
+ column_name=column_name,
+ )
+ elif source_type == "local":
+ dataset = self.globals[table_name]
+ column_preview = get_column_preview_dataframe(dataset, request)
+ else:
+ assert_never(source_type)
- if request.source_type == "local":
- try:
- dataset = self.globals[request.table_name]
- column_preview = get_column_preview(dataset, request)
- if column_preview is None:
- DataColumnPreview(
- error=f"Column {request.column_name} not found",
- column_name=request.column_name,
- table_name=request.table_name,
- ).broadcast()
- else:
- column_preview.broadcast()
- except Exception as e:
+ if column_preview is None:
DataColumnPreview(
- error=str(e),
- column_name=request.column_name,
- table_name=request.table_name,
+ error=f"Column {column_name} not found",
+ column_name=column_name,
+ table_name=table_name,
).broadcast()
- return
-
- assert_never(request.source_type)
+ else:
+ column_preview.broadcast()
+ except Exception as e:
+ LOGGER.warning(
+ "Failed to get preview for column %s in table %s",
+ column_name,
+ table_name,
+ exc_info=e,
+ )
+ DataColumnPreview(
+ error=str(e),
+ column_name=column_name,
+ table_name=table_name,
+ ).broadcast()
+ return
async def handle_message(self, request: ControlRequest) -> None:
"""Handle a message from the client.
diff --git a/marimo/_sql/sql.py b/marimo/_sql/sql.py
index 35b0678c5c..86560234de 100644
--- a/marimo/_sql/sql.py
+++ b/marimo/_sql/sql.py
@@ -2,7 +2,7 @@
from __future__ import annotations
import os
-from typing import Any, Literal, Optional, cast
+from typing import TYPE_CHECKING, Any, Literal, Optional, cast
from marimo._dependencies.dependencies import DependencyManager
from marimo._output.rich_help import mddoc
@@ -13,6 +13,9 @@ from marimo._runtime.context.types import (
)
from marimo._runtime.output import replace
+if TYPE_CHECKING:
+ import duckdb
+
def get_default_result_limit() -> Optional[int]:
limit = os.environ.get("MARIMO_SQL_DEFAULT_LIMIT")
@@ -41,24 +44,7 @@ def sql(
"""
DependencyManager.duckdb.require("to execute sql")
- import duckdb # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
-
- # In Python globals() are scoped to modules; since this function
- # is in a different module than user code, globals() doesn't return
- # the kernel globals, it just returns this module's global namespace.
- #
- # However, duckdb needs access to the kernel's globals. For this reason,
- # we manually exec duckdb and provide it with the kernel's globals.
- try:
- ctx = get_context()
- except ContextNotInitializedError:
- relation = duckdb.sql(query=query)
- else:
- relation = eval(
- "duckdb.sql(query=query)",
- ctx.globals,
- {"query": query, "duckdb": duckdb},
- )
+ relation = _wrapped_sql(query)
if not relation:
return None
@@ -116,7 +102,7 @@ def sql(
def _query_includes_limit(query: str) -> bool:
- import duckdb # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
+ import duckdb
try:
statements = duckdb.extract_statements(query.strip())
@@ -133,3 +119,25 @@ def _query_includes_limit(query: str) -> bool:
"LIMIT " in last_statement.query.upper()
or "LIMIT\n" in last_statement.query.upper()
)
+
+
+def _wrapped_sql(query: str) -> "duckdb.DuckDBPyRelation":
+ import duckdb
+
+ # In Python globals() are scoped to modules; since this function
+ # is in a different module than user code, globals() doesn't return
+ # the kernel globals, it just returns this module's global namespace.
+ #
+ # However, duckdb needs access to the kernel's globals. For this reason,
+ # we manually exec duckdb and provide it with the kernel's globals.
+ try:
+ ctx = get_context()
+ except ContextNotInitializedError:
+ relation = duckdb.sql(query=query)
+ else:
+ relation = eval(
+ "duckdb.sql(query=query)",
+ ctx.globals,
+ {"query": query, "duckdb": duckdb},
+ )
+ return relation
diff --git a/tests/_data/test_get_datasets.py b/tests/_data/test_get_datasets.py
index a018b59670..1757c19f71 100644
--- a/tests/_data/test_get_datasets.py
+++ b/tests/_data/test_get_datasets.py
@@ -2,7 +2,11 @@ from __future__ import annotations
import pytest
-from marimo._data.get_datasets import has_updates_to_datasource
+from marimo._data.get_datasets import (
+ get_datasets_from_duckdb,
+ has_updates_to_datasource,
+)
+from marimo._data.models import DataTable, DataTableColumn
from marimo._dependencies.dependencies import DependencyManager
HAS_DEPS = DependencyManager.duckdb.has()
@@ -14,3 +18,30 @@ def test_has_updates_to_datasource() -> None:
assert has_updates_to_datasource("ATTACH 'marimo.db'") is True
assert has_updates_to_datasource("DETACH marimo") is True
assert has_updates_to_datasource("CREATE TABLE cars (name TEXT)") is True
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_get_datasets() -> None:
+ assert get_datasets_from_duckdb() == []
+
+ import duckdb
+
+ duckdb.execute("CREATE TABLE cars (name TEXT, year INTEGER)")
+ assert get_datasets_from_duckdb() == [
+ DataTable(
+ name="memory.main.cars",
+ source_type="duckdb",
+ source="memory",
+ num_rows=None,
+ num_columns=2,
+ variable_name=None,
+ columns=[
+ DataTableColumn(
+ name="name", type="string", external_type="VARCHAR"
+ ),
+ DataTableColumn(
+ name="year", type="integer", external_type="INTEGER"
+ ),
+ ],
+ )
+ ]
diff --git a/tests/_data/test_preview_column.py b/tests/_data/test_preview_column.py
index 7b08ed67b7..d65f9e0677 100644
--- a/tests/_data/test_preview_column.py
+++ b/tests/_data/test_preview_column.py
@@ -4,7 +4,10 @@ import sys
import pytest
-from marimo._data.preview_column import get_column_preview
+from marimo._data.preview_column import (
+ get_column_preview_dataframe,
+ get_column_preview_for_sql,
+)
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._impl.charts.altair_transformer import (
register_transformers,
@@ -12,17 +15,20 @@ from marimo._plugins.ui._impl.charts.altair_transformer import (
from marimo._runtime.requests import PreviewDatasetColumnRequest
from tests.mocks import snapshotter
-HAS_DEPS = DependencyManager.pandas.has() and DependencyManager.altair.has()
+HAS_DF_DEPS = DependencyManager.pandas.has() and DependencyManager.altair.has()
+HAS_SQL_DEPS = DependencyManager.duckdb.has()
snapshot = snapshotter(__file__)
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ not HAS_DF_DEPS, reason="optional dependencies not installed"
+)
@pytest.mark.skipif(
sys.platform == "win32",
reason="Windows encodes base64 differently",
)
-def test_get_column_preview() -> None:
+def test_get_column_preview_dataframe() -> None:
import pandas as pd
register_transformers()
@@ -38,7 +44,7 @@ def test_get_column_preview() -> None:
],
}
)
- result = get_column_preview(
+ result = get_column_preview_dataframe(
df,
request=PreviewDatasetColumnRequest(
source="source",
@@ -57,7 +63,7 @@ def test_get_column_preview() -> None:
snapshot("column_preview_chart_code.txt", result.chart_code)
snapshot("column_preview_chart_spec.txt", result.chart_spec)
- result = get_column_preview(
+ result = get_column_preview_dataframe(
df,
request=PreviewDatasetColumnRequest(
source="source",
@@ -75,3 +81,167 @@ def test_get_column_preview() -> None:
snapshot("column_preview_date_chart_code.txt", result.chart_code)
snapshot("column_preview_date_chart_spec.txt", result.chart_spec)
+
+
+ not HAS_SQL_DEPS, reason="optional dependencies not installed"
+)
+ sys.platform == "win32",
+ reason="Windows encodes base64 differently",
+)
+def test_get_column_preview_for_duckdb() -> None:
+ import duckdb
+
+ # Create a table with a deterministic pattern
+ duckdb.execute("""
+ CREATE OR REPLACE TABLE tbl AS
+ SELECT
+ range AS id,
+ CAST(range % 2 AS INTEGER) AS outcome
+ FROM range(100)
+ """)
+
+ # Test preview for the 'outcome' column (alternating 0 and 1)
+ result = get_column_preview_for_sql(
+ table_name="tbl",
+ column_name="outcome",
+ )
+ assert result is not None
+ assert result.summary is not None
+ assert result.error is None
+
+ # Check if summary contains expected statistics for the alternating pattern
+ assert result.summary.total == 100
+ assert result.summary.unique == 2
+ assert result.summary.mean == 0.5 # Exactly 0.5 due to alternating pattern
+
+ # Test preview for the 'id' column (for comparison)
+ result_id = get_column_preview_for_sql(
+ table_name="tbl",
+ column_name="id",
+ )
+ assert result_id is not None
+ assert result_id.summary is not None
+ assert result_id.error is None
+
+ # Not implemented yet
+ assert result.chart_code is None
+ assert result.chart_spec is None
+
+
+ not HAS_SQL_DEPS, reason="optional dependencies not installed"
+)
+ sys.platform == "win32",
+ reason="Windows encodes base64 differently",
+)
+def test_get_column_preview_for_duckdb_categorical() -> None:
+ import duckdb
+
+ # Test preview for a categorical column
+ duckdb.execute("""
+ CREATE OR REPLACE TABLE tbl AS
+ SELECT
+ CASE
+ WHEN range % 4 = 0 THEN 'A'
+ WHEN range % 4 = 1 THEN 'B'
+ WHEN range % 4 = 2 THEN 'C'
+ ELSE 'D'
+ END AS category
+ FROM range(100)
+ """)
+
+ result_categorical = get_column_preview_for_sql(
+ table_name="tbl",
+ column_name="category",
+ )
+ assert result_categorical is not None
+ assert result_categorical.summary is not None
+ assert result_categorical.error is None
+
+ # Check if summary contains expected statistics for the categorical pattern
+ assert result_categorical.summary.total == 100
+ assert result_categorical.summary.unique == 4
+ assert result_categorical.summary.nulls == 0
+
+ # Not implemented yet
+ assert result_categorical.chart_code is None
+ assert result_categorical.chart_spec is None
+
+
+ not HAS_SQL_DEPS, reason="optional dependencies not installed"
+)
+ sys.platform == "win32",
+ reason="Windows encodes base64 differently",
+)
+def test_get_column_preview_for_duckdb_date() -> None:
+ import datetime
+
+ import duckdb
+
+ # Test preview for a date column
+ duckdb.execute("""
+ CREATE OR REPLACE TABLE date_tbl AS
+ SELECT DATE '2023-01-01' + INTERVAL (range % 365) DAY AS date_col
+ FROM range(100)
+ """)
+
+ result_date = get_column_preview_for_sql(
+ table_name="date_tbl",
+ column_name="date_col",
+ )
+ assert result_date is not None
+ assert result_date.summary is not None
+ assert result_date.error is None
+
+ # Check if summary contains expected statistics for the date pattern
+ assert result_date.summary.total == 100
+ assert result_date.summary.unique == 100
+ assert result_date.summary.nulls == 0
+ assert result_date.summary.min == datetime.datetime(2023, 1, 1, 0, 0)
+ assert result_date.summary.max == datetime.datetime(2023, 4, 10, 0, 0)
+
+ # Not implemented yet
+ assert result_date.chart_code is None
+ assert result_date.chart_spec is None
+
+
+ not HAS_SQL_DEPS, reason="optional dependencies not installed"
+)
+ sys.platform == "win32",
+ reason="Windows encodes base64 differently",
+)
+def test_get_column_preview_for_duckdb_bool() -> None:
+ import duckdb
+
+ # Test preview for a boolean column
+ duckdb.execute("""
+ CREATE OR REPLACE TABLE bool_tbl AS
+ SELECT range % 2 = 0 AS bool_col
+ FROM range(100)
+ """)
+
+ result_bool = get_column_preview_for_sql(
+ table_name="bool_tbl",
+ column_name="bool_col",
+ )
+ assert result_bool is not None
+ assert result_bool.summary is not None
+ assert result_bool.error is None
+
+ # Check if summary contains expected statistics for the boolean pattern
+ assert result_bool.summary.total == 100
+ assert result_bool.summary.unique == 2
+ assert result_bool.summary.nulls == 0
+ assert result_bool.summary.true == 50
+ assert result_bool.summary.false == 50
+
+ # Not implemented yet
+ assert result_bool.chart_code is None
+ assert result_bool.chart_spec is None
diff --git a/tests/_data/test_sql_summaries.py b/tests/_data/test_sql_summaries.py
new file mode 100644
index 0000000000..7907a7edd9
--- /dev/null
+++ b/tests/_data/test_sql_summaries.py
@@ -0,0 +1,108 @@
+from __future__ import annotations
+
+import datetime
+from typing import Any
+
+import pytest
+
+from marimo._data.models import ColumnSummary
+from marimo._data.sql_summaries import get_column_type, get_sql_summary
+from marimo._dependencies.dependencies import DependencyManager
+
+HAS_DEPS = DependencyManager.duckdb.has()
+
+
+def setup_test_db():
+ if not HAS_DEPS:
+ pytest.skip("optional dependencies not installed")
+
+ import duckdb
+
+ # Create a test database and table
+ duckdb.execute("""
+ CREATE OR REPLACE TABLE test_table_3 (
+ id INTEGER,
+ name VARCHAR,
+ age INTEGER,
+ salary DECIMAL(10, 2),
+ is_active BOOLEAN,
+ birth_date DATE
+ )
+ """)
+
+ # Insert some test data
+ duckdb.execute("""
+ INSERT INTO test_table_3 VALUES
+ (1, 'Alice', 30, 50000.00, true, '1993-01-15'),
+ (2, 'Bob', 35, 60000.00, false, '1988-05-20'),
+ (3, 'Charlie', 28, 45000.00, true, '1995-11-30'),
+ (4, 'David', NULL, 55000.00, true, '1990-08-10'),
+ (5, 'Eve', 32, NULL, false, '1991-03-25')
+ """)
+
+ yield duckdb
+
+ duckdb.execute("DROP TABLE test_table_3")
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_get_column_type(setup_test_db: Any):
+ del setup_test_db
+
+ assert get_column_type("test_table_3", "id") == "integer"
+ assert get_column_type("test_table_3", "name") == "string"
+ assert get_column_type("test_table_3", "salary") == "number"
+ assert get_column_type("test_table_3", "is_active") == "boolean"
+ assert get_column_type("test_table_3", "birth_date") == "date"
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_get_sql_summary_integer(setup_test_db: Any):
+ del setup_test_db
+
+ summary = get_sql_summary("test_table_3", "age", "integer")
+ assert isinstance(summary, ColumnSummary)
+ assert summary.total == 5
+ assert summary.unique == 4
+ assert summary.nulls == 1
+ assert summary.min == 28
+ assert summary.max == 35
+ assert summary.mean == 31.25 # (30 + 35 + 28 + 32) / 4
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_get_sql_summary_string(setup_test_db: Any):
+ del setup_test_db
+
+ summary = get_sql_summary("test_table_3", "name", "string")
+ assert isinstance(summary, ColumnSummary)
+ assert summary.total == 5
+ assert summary.unique == 5
+ assert summary.nulls == 0
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_get_sql_summary_boolean(setup_test_db: Any):
+ del setup_test_db
+
+ summary = get_sql_summary("test_table_3", "is_active", "boolean")
+ assert isinstance(summary, ColumnSummary)
+ assert summary.total == 5
+ assert summary.unique == 2
+ assert summary.nulls == 0
+ assert summary.true == 3
+ assert summary.false == 2
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_get_sql_summary_date(setup_test_db: Any):
+ del setup_test_db
+
+ summary = get_sql_summary("test_table_3", "birth_date", "date")
+ assert isinstance(summary, ColumnSummary)
+ assert summary.total == 5
+ assert summary.unique == 5
+ assert summary.nulls == 0
+ assert summary.min == datetime.date(1988, 5, 20)
+ assert summary.max == datetime.date(1995, 11, 30)
diff --git a/tests/_sql/test_sql.py b/tests/_sql/test_sql.py
index ddea39ce82..7840dc9588 100644
--- a/tests/_sql/test_sql.py
+++ b/tests/_sql/test_sql.py
@@ -38,7 +38,7 @@ def test_applies_limit(mock_replace: MagicMock) -> None:
try:
os.environ["MARIMO_SQL_DEFAULT_LIMIT"] = "300"
- duckdb.sql("CREATE TABLE t AS SELECT * FROM range(1000)")
+ duckdb.sql("CREATE OR REPLACE TABLE t AS SELECT * FROM range(1000)")
mock_replace.assert_not_called()
table: ui.table
@@ -74,7 +74,9 @@ def test_applies_limit(mock_replace: MagicMock) -> None:
# Limit above 20_0000 (which is the mo.ui.table cutoff)
mock_replace.reset_mock()
- duckdb.sql("CREATE TABLE big_table AS SELECT * FROM range(30_000)")
+ duckdb.sql(
+ "CREATE OR REPLACE TABLE big_table AS SELECT * FROM range(30_000)"
+ )
assert len(sql("SELECT * FROM big_table LIMIT 25_000")) == 25_000
mock_replace.assert_called_once()
table = mock_replace.call_args[0][0]
@@ -103,25 +105,27 @@ def test_sql_output_flag(mock_replace: MagicMock) -> None:
from marimo._sql.sql import sql
# Create a test table
- duckdb.sql("CREATE TABLE test_table AS SELECT * FROM range(10)")
+ duckdb.sql(
+ "CREATE OR REPLACE TABLE test_table_2 AS SELECT * FROM range(10)"
+ )
# Test when output is None (default, True)
- result = sql("SELECT * FROM test_table")
+ result = sql("SELECT * FROM test_table_2")
assert isinstance(result, pl.DataFrame)
mock_replace.assert_called_once()
mock_replace.reset_mock()
# Test when output is False
- result = sql("SELECT * FROM test_table", output=False)
+ result = sql("SELECT * FROM test_table_2", output=False)
assert isinstance(result, pl.DataFrame)
mock_replace.assert_not_called()
mock_replace.reset_mock()
# Test when output is True
- result = sql("SELECT * FROM test_table", output=True)
+ result = sql("SELECT * FROM test_table_2", output=True)
assert isinstance(result, pl.DataFrame)
mock_replace.assert_called_once()
mock_replace.reset_mock()
# Clean up
- duckdb.sql("DROP TABLE test_table")
+ duckdb.sql("DROP TABLE test_table_2")