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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: support column charts for duckdb tables (#4072)
Myles Scolnick236782c91bc6
diff --git a/examples/sql/read_csv.py b/examples/sql/read_csv.pyindex f6d94bf1d3..5e963a1431 100644--- a/examples/sql/read_csv.py+++ b/examples/sql/read_csv.py@@ -11,7 +11,7 @@import marimo-__generated_with = "0.10.7"+__generated_with = "0.11.18"app = marimo.App(width="medium")@@ -70,7 +70,7 @@ def _(mo):-- or '/path/**/to/*.csv'SELECT * FROM "data.csv"""",- output=False,+ output=False)return (result,)diff --git a/frontend/src/components/datasources/__tests__/utils.test.ts b/frontend/src/components/datasources/__tests__/utils.test.tsnew file mode 100644index 0000000000..d87e56eea7--- /dev/null+++ b/frontend/src/components/datasources/__tests__/utils.test.ts@@ -0,0 +1,116 @@+/* Copyright 2024 Marimo. All rights reserved. */+import {+ DEFAULT_ENGINE,+ type SQLTableContext,+} from "@/core/datasets/data-source-connections";+import type { DataTable, DataTableColumn } from "@/core/kernel/messages";+import { describe, it, expect } from "vitest";+import { sqlCode } from "../utils";++describe("sqlCode", () => {+ const mockTable: DataTable = {+ name: "users" as const,+ columns: [],+ source: "local",+ source_type: "local",+ type: "table",+ };+ const mockColumn = {+ name: "email" as const,+ } as DataTableColumn;++ it("should generate basic SQL without sqlTableContext", () => {+ const result = sqlCode(mockTable, mockColumn.name);+ expect(result).toBe(+ "_df = mo.sql(f'SELECT \"email\" FROM users LIMIT 100')",+ );+ });++ it("should generate SQL with default schema", () => {+ const sqlTableContext: SQLTableContext = {+ engine: DEFAULT_ENGINE,+ schema: "public",+ defaultSchema: "public",+ defaultDatabase: "mydb",+ database: "mydb",+ };++ const result = sqlCode(mockTable, mockColumn.name, sqlTableContext);+ expect(result).toBe('_df = mo.sql(f"SELECT email FROM users LIMIT 100")');+ });++ it("should generate SQL with non-default schema", () => {+ const sqlTableContext: SQLTableContext = {+ engine: DEFAULT_ENGINE,+ schema: "analytics",+ defaultSchema: "public",+ defaultDatabase: "mydb",+ database: "mydb",+ };++ const result = sqlCode(mockTable, mockColumn.name, sqlTableContext);+ expect(result).toBe(+ '_df = mo.sql(f"SELECT email FROM analytics.users LIMIT 100")',+ );+ });++ it("should generate SQL with non-default engine", () => {+ const sqlTableContext: SQLTableContext = {+ engine: "snowflake",+ schema: "public",+ defaultSchema: "public",+ defaultDatabase: "mydb",+ database: "mydb",+ };++ const result = sqlCode(mockTable, mockColumn.name, sqlTableContext);+ expect(result).toBe(+ '_df = mo.sql(f"SELECT email FROM users LIMIT 100", engine=snowflake)',+ );+ });++ it("should generate SQL with non-default schema and non-default engine", () => {+ const sqlTableContext: SQLTableContext = {+ engine: "bigquery",+ schema: "sales",+ defaultSchema: "public",+ defaultDatabase: "mydb",+ database: "mydb",+ };++ const result = sqlCode(mockTable, mockColumn.name, sqlTableContext);+ expect(result).toBe(+ '_df = mo.sql(f"SELECT email FROM sales.users LIMIT 100", engine=bigquery)',+ );+ });++ it("should generate SQL with non-default database", () => {+ const sqlTableContext: SQLTableContext = {+ engine: DEFAULT_ENGINE,+ schema: "public",+ defaultSchema: "public",+ defaultDatabase: "memory",+ database: "remote",+ };++ const result = sqlCode(mockTable, mockColumn.name, sqlTableContext);+ expect(result).toBe(+ '_df = mo.sql(f"SELECT email FROM remote.users LIMIT 100")',+ );+ });++ it("should generate SQL with non-default database and non-default schema", () => {+ const sqlTableContext: SQLTableContext = {+ engine: "bigquery",+ schema: "sales",+ defaultSchema: "public",+ defaultDatabase: "mydb",+ database: "remote",+ };++ const result = sqlCode(mockTable, mockColumn.name, sqlTableContext);+ expect(result).toBe(+ '_df = mo.sql(f"SELECT email FROM remote.sales.users LIMIT 100", engine=bigquery)',+ );+ });+});diff --git a/frontend/src/components/datasources/datasources.tsx b/frontend/src/components/datasources/datasources.tsxindex 018f1486ee..c677a0cd24 100644--- a/frontend/src/components/datasources/datasources.tsx+++ b/frontend/src/components/datasources/datasources.tsx@@ -74,6 +74,8 @@ import {RotatingChevron,} from "./components";import { InstallPackageButton } from "./install-package-button";+import { sqlCode } from "./utils";+import { useOnMount } from "@/hooks/useLifecycle";const sortedTablesAtom = atom((get) => {const tables = get(datasetTablesAtom);@@ -197,6 +199,7 @@ export const DataSources: React.FC = () => {<SchemaListschemas={database.schemas}defaultSchema={connection.default_schema}+ defaultDatabase={connection.default_database}engineName={connection.name}databaseName={database.name}hasSearch={hasSearch}@@ -297,6 +300,7 @@ const DatabaseItem: React.FC<{const SchemaList: React.FC<{schemas: DatabaseSchema[];defaultSchema?: string | null;+ defaultDatabase?: string | null;engineName: string;databaseName: string;hasSearch: boolean;@@ -304,6 +308,7 @@ const SchemaList: React.FC<{}> = ({schemas,defaultSchema,+ defaultDatabase,engineName,databaseName,hasSearch,@@ -339,6 +344,7 @@ const SchemaList: React.FC<{database: databaseName,schema: schema.name,defaultSchema: defaultSchema,+ defaultDatabase: defaultDatabase,}}/></SchemaItem>@@ -504,20 +510,15 @@ const DatasetTableItem: React.FC<{maybeAddMarimoImport(autoInstantiate, createNewCell, lastFocusedCellId);let code = "";if (sqlTableContext) {- const { engine, schema, defaultSchema } = sqlTableContext;- const tableName =- defaultSchema === schema ? table.name : `${schema}.${table.name}`;- code = `_df = mo.sql(f"SELECT * FROM ${tableName} LIMIT 100", engine=${engine})`;+ code = sqlCode(table, "*", sqlTableContext);} else {switch (table.source_type) {case "local":code = `mo.ui.table(${table.name})`;break;case "duckdb":- code = `_df = mo.sql(f"SELECT * FROM ${table.name} LIMIT 100")`;- break;case "connection":- code = `_df = mo.sql(f"SELECT * FROM ${table.name} LIMIT 100", engine=${table.engine})`;+ code = sqlCode(table, "*", sqlTableContext);break;default:logNever(table.source_type);@@ -734,7 +735,11 @@ const DatasetColumnItem: React.FC<{table={table}column={column}onAddColumnChart={handleAddColumn}- preview={columnsPreviews.get(`${table.name}:${column.name}`)}+ preview={columnsPreviews.get(+ sqlTableContext+ ? `${sqlTableContext.database}.${sqlTableContext.schema}.${table.name}:${column.name}`+ : `${table.name}:${column.name}`,+ )}sqlTableContext={sqlTableContext}/></ErrorBoundary>@@ -757,12 +762,24 @@ const DatasetColumnPreview: React.FC<{}> = ({ table, column, preview, onAddColumnChart, sqlTableContext }) => {const { theme } = useTheme();+ useOnMount(() => {+ if (preview) {+ return;+ }++ previewDatasetColumn({+ source: table.source,+ tableName: table.name,+ columnName: column.name,+ sourceType: table.source_type,+ fullyQualifiedTableName: sqlTableContext+ ? `${sqlTableContext.database}.${sqlTableContext.schema}.${table.name}`+ : table.name,+ });+ });+// Do not fetch previews for custom SQL connections- // or if the table is In-Memory duckdb, but not in the main schema- if (- table.source_type === "connection" ||- (table.source_type === "duckdb" && sqlTableContext?.schema !== "main")- ) {+ if (table.source_type === "connection") {return (<span className="text-xs text-muted-foreground gap-2 flex items-center justify-between pl-7">{column.name} ({column.external_type})@@ -770,7 +787,7 @@ const DatasetColumnPreview: React.FC<{variant="outline"size="xs"onClick={Events.stopPropagation(() => {- onAddColumnChart(sqlCode(table, column, sqlTableContext));+ onAddColumnChart(sqlCode(table, column.name, sqlTableContext));})}><PlusSquareIcon className="h-3 w-3 mr-1" /> Add SQL cell@@ -779,15 +796,6 @@ const DatasetColumnPreview: React.FC<{);}- if (!preview) {- previewDatasetColumn({- source: table.source,- tableName: table.name,- columnName: column.name,- sourceType: table.source_type,- });- }-if (!preview) {return <span className="text-xs text-muted-foreground">Loading...</span>;}@@ -865,7 +873,7 @@ const DatasetColumnPreview: React.FC<{size="icon"className="z-10 bg-background absolute right-1 -top-1"onClick={Events.stopPropagation(() => {- onAddColumnChart(sqlCode(table, column, sqlTableContext));+ onAddColumnChart(sqlCode(table, column.name, sqlTableContext));})}><PlusSquareIcon className="h-3 w-3" />@@ -894,17 +902,3 @@ const DatasetColumnPreview: React.FC<{</div>);};--function sqlCode(- table: DataTable,- column: DataTableColumn,- sqlTableContext?: SQLTableContext,-) {- if (sqlTableContext) {- const { engine, schema, defaultSchema } = sqlTableContext;- const tableName =- defaultSchema === schema ? table.name : `${schema}.${table.name}`;- return `_df = mo.sql(f"SELECT ${column.name} FROM ${tableName} LIMIT 100", engine=${engine})`;- }- return `_df = mo.sql(f'SELECT "${column.name}" FROM ${table.name} LIMIT 100')`;-}diff --git a/frontend/src/components/datasources/utils.ts b/frontend/src/components/datasources/utils.tsnew file mode 100644index 0000000000..cb9dbb5a76--- /dev/null+++ b/frontend/src/components/datasources/utils.ts@@ -0,0 +1,35 @@+/* Copyright 2024 Marimo. All rights reserved. */+import {+ type SQLTableContext,+ DEFAULT_ENGINE,+} from "@/core/datasets/data-source-connections";+import type { DataTable } from "@/core/kernel/messages";++export function sqlCode(+ table: DataTable,+ columnName: string,+ sqlTableContext?: SQLTableContext,+) {+ if (sqlTableContext) {+ const { engine, schema, defaultSchema, defaultDatabase, database } =+ sqlTableContext;+ let tableName = table.name;++ // If the schema is not the default schema, we need to include the schema in the table name+ if (schema !== defaultSchema) {+ tableName = `${schema}.${tableName}`;+ }+ // If the database is not the default database, we need to include the database in the table name+ if (database !== defaultDatabase) {+ tableName = `${database}.${tableName}`;+ }++ if (engine === DEFAULT_ENGINE) {+ return `_df = mo.sql(f"SELECT ${columnName} FROM ${tableName} LIMIT 100")`;+ }++ return `_df = mo.sql(f"SELECT ${columnName} FROM ${tableName} LIMIT 100", engine=${engine})`;+ }++ return `_df = mo.sql(f'SELECT "${columnName}" FROM ${table.name} LIMIT 100')`;+}diff --git a/frontend/src/core/datasets/data-source-connections.ts b/frontend/src/core/datasets/data-source-connections.tsindex d99cc9f432..c9023e635e 100644--- a/frontend/src/core/datasets/data-source-connections.ts+++ b/frontend/src/core/datasets/data-source-connections.ts@@ -31,6 +31,7 @@ export interface SQLTableContext {database: string;schema: string;defaultSchema?: string | null;+ defaultDatabase?: string | null;}function initialState(): DataSourceState {diff --git a/marimo/_data/get_datasets.py b/marimo/_data/get_datasets.pyindex f08ea60d18..0799557054 100644--- a/marimo/_data/get_datasets.py+++ b/marimo/_data/get_datasets.py@@ -199,13 +199,18 @@ def _db_type_to_data_type(db_type: str) -> DataType:"uhugeint",]:return "integer"- if db_type in [- "float",- "real",- "double",- "decimal",- "numeric",- ] or db_type.startswith("decimal"):+ if (+ db_type+ in [+ "float",+ "real",+ "double",+ "decimal",+ "numeric",+ ]+ or db_type.startswith("decimal")+ or db_type.startswith("float")+ ):return "number"# Boolean typeif db_type == "boolean":@@ -242,5 +247,7 @@ def _db_type_to_data_type(db_type: str) -> DataType:return "string" # Representing bit as stringif db_type == "enum":return "string" # Representing enum as string++ LOGGER.warning("Unknown DuckDB type: %s", db_type)# Unknown typereturn "unknown"diff --git a/marimo/_data/models.py b/marimo/_data/models.pyindex 4efd2c862e..0d8c3b12b9 100644--- a/marimo/_data/models.py+++ b/marimo/_data/models.py@@ -41,6 +41,9 @@ class DataTableColumn:sample_values: list[Any]+# Local -> Python dataframes+# DuckDB -> DuckDB tables using the global in-memory DuckDB instance+# Connection -> SQL tables using a named data source connection (e.g. SQLAlchemy, or a custom DuckDB connection)DataTableSource = Literal["local", "duckdb", "connection"]DataTableType = Literal["table", "view"]diff --git a/marimo/_data/preview_column.py b/marimo/_data/preview_column.pyindex efde5b3e95..a08c4a6898 100644--- a/marimo/_data/preview_column.py+++ b/marimo/_data/preview_column.py@@ -8,19 +8,24 @@ from marimo._data.charts import get_chart_builderfrom marimo._data.models import ColumnSummaryfrom marimo._data.sql_summaries import (get_column_type,- get_histogram_data,get_sql_summary,)from marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.ops import DataColumnPreview-from marimo._plugins.ui._impl.tables.table_manager import TableManager+from marimo._plugins.ui._impl.tables.table_manager import (+ FieldType,+ TableManager,+)from marimo._plugins.ui._impl.tables.utils import get_table_manager_or_nonefrom marimo._runtime.requests import PreviewDatasetColumnRequest+from marimo._sql.utils import wrapped_sqlLOGGER = _loggers.marimo_logger()+CHART_MAX_ROWS = 20_000+-def get_column_preview_dataframe(+def get_column_preview_for_dataframe(item: object,request: PreviewDatasetColumnRequest,) -> DataColumnPreview | None:@@ -117,13 +122,17 @@ def get_column_preview_dataframe()-def get_column_preview_for_sql(- table_name: str,+def get_column_preview_for_duckdb(+ *,+ fully_qualified_table_name: str,column_name: str,) -> Optional[DataColumnPreview]:- column_type = get_column_type(table_name, column_name)- summary = get_sql_summary(table_name, column_name, column_type)- histogram_data = get_histogram_data(table_name, column_name)+ DependencyManager.duckdb.require(why="previewing DuckDB columns")++ column_type = get_column_type(fully_qualified_table_name, column_name)+ summary = get_sql_summary(+ fully_qualified_table_name, column_name, column_type+ )# Generate Altair chartchart_spec = None@@ -131,16 +140,38 @@ def get_column_preview_for_sql(chart_max_rows_errors = Falseerror = Nonemissing_packages = None+ should_limit_to_10_items = True++ if DependencyManager.altair.has():+ from altair import MaxRowsError # type: ignore[import-not-found]- 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)+ total_rows: int = wrapped_sql(+ f"SELECT COUNT(*) FROM {fully_qualified_table_name}",+ connection=None,+ ).fetchone()[0] # type: ignore[index]++ if total_rows <= CHART_MAX_ROWS:+ relation = wrapped_sql(+ f"SELECT {column_name} FROM {fully_qualified_table_name}",+ connection=None,+ )+ chart_spec = _get_chart_spec(+ column_data=relation,+ column_type=column_type,+ column_name=column_name,+ should_limit_to_10_items=should_limit_to_10_items,+ )+ else:+ chart_max_rows_errors = True+ except MaxRowsError:+ chart_spec = None+ chart_max_rows_errors = Trueexcept Exception as e:LOGGER.warning(f"Failed to generate Altair chart: {str(e)}")return DataColumnPreview(- table_name=table_name,+ table_name=fully_qualified_table_name,column_name=column_name,chart_max_rows_errors=chart_max_rows_errors,chart_spec=chart_spec,@@ -160,10 +191,7 @@ def _get_altair_chart(if not DependencyManager.altair.has() or not table.supports_altair():return None, None, False- import altair as alt # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501- from altair import ( # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501- MaxRowsError,- )+ from altair import MaxRowsError # type: ignore[import-not-found](column_type, _external_type) = table.get_field_type(request.column_name)@@ -188,45 +216,60 @@ def _get_altair_chart(chart_max_rows_errors = False- def get_chart_json() -> str:+ try:# Filter the data to the column we wantcolumn_data = table.select_columns([request.column_name]).data+ chart_spec = _get_chart_spec(+ column_data=column_data,+ column_type=column_type,+ column_name=request.column_name,+ should_limit_to_10_items=should_limit_to_10_items,+ )+ except MaxRowsError:+ chart_spec = None+ chart_max_rows_errors = True- # If we have vegafusion and vl-convert-python, use it- if (- DependencyManager.vegafusion.has()- and DependencyManager.vl_convert_python.has()- ):- with alt.data_transformers.enable("vegafusion"):- return chart_builder.altair_json(- column_data,- request.column_name,- )+ return chart_spec, code, chart_max_rows_errors- # Date types don't serialize well to csv,- # so we don't transform them- dont_use_csv = (- column_type == "date"- or column_type == "datetime"- or column_type == "time"- )- if dont_use_csv:- # Default max_rows is 5_000, but we can support more.- with alt.data_transformers.enable("default", max_rows=20_000):- return chart_builder.altair_json(- column_data,- request.column_name,- )- with alt.data_transformers.enable("marimo_inline_csv"):++def _get_chart_spec(+ *,+ column_data: Any,+ column_type: FieldType,+ column_name: str,+ should_limit_to_10_items: bool,+) -> str:+ import altair as alt # type: ignore[import-not-found]++ chart_builder = get_chart_builder(column_type, should_limit_to_10_items)++ # If we have vegafusion and vl-convert-python, use it+ if (+ DependencyManager.vegafusion.has()+ and DependencyManager.vl_convert_python.has()+ ):+ with alt.data_transformers.enable("vegafusion"):return chart_builder.altair_json(column_data,- request.column_name,+ column_name,)- try:- chart_json = get_chart_json()- except MaxRowsError:- chart_json = None- chart_max_rows_errors = True-- return chart_json, code, chart_max_rows_errors+ # Date types don't serialize well to csv,+ # so we don't transform them+ dont_use_csv = (+ column_type == "date"+ or column_type == "datetime"+ or column_type == "time"+ )+ if dont_use_csv:+ # Default max_rows is 5_000, but we can support more.+ with alt.data_transformers.enable("default", max_rows=CHART_MAX_ROWS):+ return chart_builder.altair_json(+ column_data,+ column_name,+ )+ with alt.data_transformers.enable("marimo_inline_csv"):+ return chart_builder.altair_json(+ column_data,+ column_name,+ )diff --git a/marimo/_data/sql_summaries.py b/marimo/_data/sql_summaries.pyindex 74721570f2..a8287cf06b 100644--- a/marimo/_data/sql_summaries.py+++ b/marimo/_data/sql_summaries.py@@ -128,18 +128,36 @@ def get_sql_summary(return ColumnSummary(total=count, unique=unique, nulls=null_count)-def get_column_type(table_name: str, column_name: str) -> DataType:+def get_column_type(+ fully_qualified_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}'- """+ if "." in fully_qualified_table_name:+ # Fully qualified table name+ db_name, schema_name, table_name = _parse_fully_qualified_table_name(+ fully_qualified_table_name+ )+ column_info_query = f"""+ SELECT data_type+ FROM information_schema.columns+ WHERE table_name = '{table_name}'+ AND table_schema = '{schema_name}'+ AND table_catalog = '{db_name}'+ AND column_name = '{column_name}'+ """+ else:+ # Simple table name+ table_name = fully_qualified_table_name+ 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, connection=None@@ -163,3 +181,17 @@ def get_histogram_data(# TODO: Implement thisreturn []+++def _parse_fully_qualified_table_name(+ fully_qualified_table_name: str,+) -> tuple[str, str, str]:+ """+ Parse a fully qualified table name into a database name, schema name, and table name.+ """+ parts = fully_qualified_table_name.split(".")+ if len(parts) != 3:+ raise ValueError(+ f"Invalid fully qualified table name: {fully_qualified_table_name}"+ )+ return parts[0], parts[1], parts[2]diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.pyindex 62fbc19dbb..94456f3bc3 100644--- a/marimo/_runtime/requests.py+++ b/marimo/_runtime/requests.py@@ -295,10 +295,14 @@ class PreviewDatasetColumnRequest:# The source of the datasetsource: str# The name of the dataset- # This currently corresponds to the variable name+ # If this is a Python dataframe, this is the variable name+ # If this is an SQL table, this is the table nametable_name: str# The name of the columncolumn_name: str+ # The fully qualified name of the table+ # This is the database.schema.table name+ fully_qualified_table_name: Optional[str] = None@dataclassdiff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 83138ed46d..9311bd3170 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -28,8 +28,8 @@ from marimo._ast.visitor import ImportData, Name, VariableDatafrom marimo._config.config import ExecutionType, MarimoConfig, OnCellChangeTypefrom marimo._config.settings import GLOBAL_SETTINGSfrom marimo._data.preview_column import (- get_column_preview_dataframe,- get_column_preview_for_sql,+ get_column_preview_for_dataframe,+ get_column_preview_for_duckdb,)from marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.cell_output import CellChannel@@ -2083,13 +2083,16 @@ class Kernel:try:if source_type == "duckdb":- column_preview = get_column_preview_for_sql(- table_name=table_name,+ column_preview = get_column_preview_for_duckdb(+ fully_qualified_table_name=request.fully_qualified_table_name+ or table_name,column_name=column_name,)elif source_type == "local":dataset = self.globals[table_name]- column_preview = get_column_preview_dataframe(dataset, request)+ column_preview = get_column_preview_for_dataframe(+ dataset, request+ )elif source_type == "connection":DataColumnPreview(error="Column preview for connection data sources is not supported",diff --git a/marimo/_smoke_tests/sql.py b/marimo/_smoke_tests/sql.pyindex c37c26163f..c2319d7595 100644--- a/marimo/_smoke_tests/sql.py+++ b/marimo/_smoke_tests/sql.py@@ -11,12 +11,12 @@import marimo-__generated_with = "0.8.14"+__generated_with = "0.11.18"app = marimo.App(width="medium")@app.cell-def __():+def _():import altair as altfrom vega_datasets import dataimport duckdb@@ -25,13 +25,13 @@ def __():@app.cell(hide_code=True)-def __(mo):+def _(mo):mo.md("""## Cars""")return@app.cell-def __(data, mo):+def _(data, mo):# Create a slider with the range of car cylinderscars = data.cars()cylinders = mo.ui.slider.from_series(cars["Cylinders"])@@ -40,7 +40,7 @@ def __(data, mo):@app.cell-def __(cars, cylinders, mo):+def _(cars, cylinders, mo):df = mo.sql(f"""SELECT "Name", "Miles_per_Gallon", "Cylinders", "Horsepower"@@ -48,11 +48,11 @@ def __(cars, cylinders, mo):WHERE "Cylinders" = {cylinders.value}""")- return df,+ return (df,)@app.cell-def __(alt, df, mo):+def _(alt, df, mo):# Chart the filtered carsmo.ui.altair_chart(alt.Chart(df)@@ -64,65 +64,65 @@ def __(alt, df, mo):@app.cell(hide_code=True)-def __(mo):+def _(mo):mo.md("""## Airports""")return@app.cell-def __(data):+def _(data):airports = data.airports()- return airports,+ return (airports,)@app.cell-def __(airports, mo):+def _(airports, mo):less_airports = mo.sql(f"""select * from airports limit 2""")- return less_airports,+ return (less_airports,)@app.cell-def __(less_airports):+def _(less_airports):len(less_airports)return@app.cell-def __(mo):+def _(mo):mo.md("""## Google Sheets""")return@app.cell-def __():+def _():sheet = "https://docs.google.com/spreadsheets/export?format=csv&id=1GuEPkwjdICgJ31Ji3iUoarirZNDbPxQj_kf7fd4h4Ro"- return sheet,+ return (sheet,)@app.cell-def __(mo, sheet):+def _(mo, sheet):job_types = mo.sql(f"""SELECT DISTINCT current_job_titleFROM read_csv_auto('{sheet}', normalize_names=True)""")- return job_types,+ return (job_types,)@app.cell-def __(job_types, mo):+def _(job_types, mo):job_title = mo.ui.dropdown.from_series(job_types["current_job_title"])job_title- return job_title,+ return (job_title,)@app.cell-def __(job_title, mo, sheet):+def _(job_title, mo, sheet):_df = mo.sql(f"""SELECT *@@ -134,13 +134,13 @@ def __(job_title, mo, sheet):@app.cell(hide_code=True)-def __(mo):+def _(mo):mo.md("""Debug""")return@app.cell(hide_code=True)-def __(duckdb):+def _(duckdb):duckdb.get_table_names(f"""SELECT "Name", "Miles_per_Gallon", "Cylinders", "Horsepower"@@ -151,7 +151,7 @@ def __(duckdb):@app.cell(hide_code=True)-def __(duckdb, job_title, sheet):+def _(duckdb, job_title, sheet):duckdb.get_table_names(f"""SELECT *@@ -163,16 +163,16 @@ def __(duckdb, job_title, sheet):@app.cell-def __(cars, mo):+def _(cars, mo):grouped_cars_by_origin = mo.sql(- """+ f"""SELECT "Origin", COUNT(*) AS "Count"FROM carsGROUP BY "Origin"LIMIT 100""")- return grouped_cars_by_origin,+ return (grouped_cars_by_origin,)if __name__ == "__main__":diff --git a/openapi/api.yaml b/openapi/api.yamlindex 986c1bf48c..457247c3a8 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -366,10 +366,10 @@ components:nullable: truetype: stringmissing_packages:- nullable: true- type: arrayitems:type: string+ nullable: true+ type: arrayname:enum:- data-column-preview@@ -1708,6 +1708,9 @@ components:properties:columnName:type: string+ fullyQualifiedTableName:+ nullable: true+ type: stringsource:type: stringsourceType:@@ -2281,7 +2284,7 @@ components:type: objectinfo:title: marimo API- version: 0.11.17+ version: 0.11.18openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex f74fbc63b9..66f253de54 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -2881,6 +2881,7 @@ export interface components {};PreviewDatasetColumnRequest: {columnName: string;+ fullyQualifiedTableName?: string | null;source: string;/** @enum {string} */sourceType: "local" | "duckdb" | "connection";diff --git a/tests/_data/snapshots/column_preview_duckdb_bool_chart_spec.txt b/tests/_data/snapshots/column_preview_duckdb_bool_chart_spec.txtnew file mode 100644index 0000000000..136e5a9480--- /dev/null+++ b/tests/_data/snapshots/column_preview_duckdb_bool_chart_spec.txt@@ -0,0 +1,173 @@+{+ "$schema": "https://vega.github.io/schema/vega/v5.json",+ "autosize": {+ "contains": "padding",+ "type": "fit-x"+ },+ "axes": [+ {+ "aria": false,+ "domain": false,+ "grid": true,+ "gridScale": "x",+ "labels": false,+ "maxExtent": 0,+ "minExtent": 0,+ "orient": "left",+ "scale": "y",+ "tickCount": {+ "signal": "ceil(height/40)"+ },+ "ticks": false,+ "zindex": 0+ },+ {+ "grid": false,+ "labelAlign": "right",+ "labelAngle": 270,+ "labelBaseline": "middle",+ "orient": "bottom",+ "scale": "x",+ "title": "bool_col",+ "zindex": 0+ },+ {+ "grid": false,+ "labelOverlap": true,+ "orient": "left",+ "scale": "y",+ "tickCount": {+ "signal": "ceil(height/40)"+ },+ "title": "Count of Records",+ "zindex": 0+ }+ ],+ "background": "white",+ "data": [+ {+ "name": "data-834341051d0a090d8e3ab71fa64b81b9"+ },+ {+ "name": "data_0",+ "values": [+ {+ "__count": 50,+ "bool_col": true+ },+ {+ "__count": 50,+ "bool_col": false+ }+ ]+ },+ {+ "name": "data_0_x_domain_bool_col",+ "values": [+ {+ "bool_col": true+ },+ {+ "bool_col": false+ }+ ]+ },+ {+ "name": "data_0_y_domain___count",+ "values": [+ {+ "max": 50,+ "min": 50+ }+ ]+ }+ ],+ "height": 300,+ "marks": [+ {+ "encode": {+ "update": {+ "fill": {+ "value": "#4c78a8"+ },+ "width": {+ "signal": "max(0.25, bandwidth('x'))"+ },+ "x": {+ "field": "bool_col",+ "scale": "x"+ },+ "y": {+ "field": "__count",+ "scale": "y"+ },+ "y2": {+ "scale": "y",+ "value": 0+ }+ }+ },+ "from": {+ "data": "data_0"+ },+ "name": "marks",+ "style": [+ "bar"+ ],+ "type": "rect"+ }+ ],+ "padding": 5,+ "scales": [+ {+ "domain": {+ "data": "data_0_x_domain_bool_col",+ "field": "bool_col",+ "sort": true+ },+ "name": "x",+ "paddingInner": 0.1,+ "paddingOuter": 0.05,+ "range": [+ 0,+ {+ "signal": "width"+ }+ ],+ "type": "band"+ },+ {+ "domain": [+ {+ "signal": "(data(\"data_0_y_domain___count\")[0] || {}).min"+ },+ {+ "signal": "(data(\"data_0_y_domain___count\")[0] || {}).max"+ }+ ],+ "name": "y",+ "nice": true,+ "range": [+ {+ "signal": "height"+ },+ 0+ ],+ "type": "linear",+ "zero": true+ }+ ],+ "signals": [+ {+ "init": "isFinite(containerSize()[0]) ? containerSize()[0] : 300",+ "name": "width",+ "on": [+ {+ "events": "window:resize",+ "update": "isFinite(containerSize()[0]) ? containerSize()[0] : 300"+ }+ ]+ }+ ],+ "style": "cell"+}\ No newline at end of filediff --git a/tests/_data/snapshots/column_preview_duckdb_categorical_chart_spec.txt b/tests/_data/snapshots/column_preview_duckdb_categorical_chart_spec.txtnew file mode 100644index 0000000000..5030eff9e6--- /dev/null+++ b/tests/_data/snapshots/column_preview_duckdb_categorical_chart_spec.txt@@ -0,0 +1,200 @@+{+ "$schema": "https://vega.github.io/schema/vega/v5.json",+ "autosize": {+ "contains": "padding",+ "type": "fit-x"+ },+ "axes": [+ {+ "aria": false,+ "domain": false,+ "grid": true,+ "gridScale": "y",+ "labels": false,+ "maxExtent": 0,+ "minExtent": 0,+ "orient": "bottom",+ "scale": "x",+ "tickCount": {+ "signal": "ceil(width/40)"+ },+ "ticks": false,+ "zindex": 0+ },+ {+ "grid": false,+ "labelFlush": true,+ "labelOverlap": true,+ "orient": "bottom",+ "scale": "x",+ "tickCount": {+ "signal": "ceil(width/40)"+ },+ "title": "count",+ "zindex": 0+ },+ {+ "grid": false,+ "orient": "left",+ "scale": "y",+ "title": "category",+ "zindex": 0+ }+ ],+ "background": "white",+ "data": [+ {+ "name": "data-6f2678becc24b5ff9fbec3e85cf09cd0"+ },+ {+ "name": "data_0"+ },+ {+ "name": "data_1",+ "values": [+ {+ "category": "A",+ "count_end": 25.0,+ "count_start": 0.0+ },+ {+ "category": "B",+ "count_end": 25.0,+ "count_start": 0.0+ },+ {+ "category": "C",+ "count_end": 25.0,+ "count_start": 0.0+ },+ {+ "category": "D",+ "count_end": 25.0,+ "count_start": 0.0+ }+ ]+ },+ {+ "name": "data_0_y_domain_category",+ "values": [+ {+ "category": "A",+ "sort_field": 25+ },+ {+ "category": "B",+ "sort_field": 25+ },+ {+ "category": "C",+ "sort_field": 25+ },+ {+ "category": "D",+ "sort_field": 25+ }+ ]+ }+ ],+ "marks": [+ {+ "encode": {+ "update": {+ "fill": {+ "value": "#4c78a8"+ },+ "height": {+ "signal": "max(0.25, bandwidth('y'))"+ },+ "x": {+ "field": "count_end",+ "scale": "x"+ },+ "x2": {+ "field": "count_start",+ "scale": "x"+ },+ "y": {+ "field": "category",+ "scale": "y"+ }+ }+ },+ "from": {+ "data": "data_1"+ },+ "name": "marks",+ "style": [+ "bar"+ ],+ "type": "rect"+ }+ ],+ "padding": 5,+ "scales": [+ {+ "domain": {+ "data": "data_1",+ "fields": [+ "count_start",+ "count_end"+ ]+ },+ "name": "x",+ "nice": true,+ "range": [+ 0,+ {+ "signal": "width"+ }+ ],+ "type": "linear",+ "zero": true+ },+ {+ "domain": {+ "data": "data_0_y_domain_category",+ "field": "category",+ "sort": {+ "field": "sort_field",+ "op": "max",+ "order": "descending"+ }+ },+ "name": "y",+ "paddingInner": 0.1,+ "paddingOuter": 0.05,+ "range": {+ "step": {+ "signal": "y_step"+ }+ },+ "type": "band"+ }+ ],+ "signals": [+ {+ "init": "isFinite(containerSize()[0]) ? containerSize()[0] : 300",+ "name": "width",+ "on": [+ {+ "events": "window:resize",+ "update": "isFinite(containerSize()[0]) ? containerSize()[0] : 300"+ }+ ]+ },+ {+ "name": "y_step",+ "value": 20+ },+ {+ "name": "height",+ "update": "bandspace(domain('y').length, 0.1, 0.05) * y_step"+ }+ ],+ "style": "cell",+ "title": {+ "frame": "group",+ "text": "Top 10 category"+ }+}\ No newline at end of filediff --git a/tests/_data/test_preview_column.py b/tests/_data/test_preview_column.pyindex 42ab4bcf0a..fc98b665d0 100644--- a/tests/_data/test_preview_column.py+++ b/tests/_data/test_preview_column.py@@ -6,8 +6,8 @@ from unittest.mock import patchimport pytestfrom marimo._data.preview_column import (- get_column_preview_dataframe,- get_column_preview_for_sql,+ get_column_preview_for_dataframe,+ get_column_preview_for_duckdb,)from marimo._dependencies.dependencies import DependencyManagerfrom marimo._plugins.ui._impl.charts.altair_transformer import (@@ -21,7 +21,9 @@ if TYPE_CHECKING:from collections.abc import GeneratorHAS_DF_DEPS = DependencyManager.pandas.has() and DependencyManager.altair.has()-HAS_SQL_DEPS = DependencyManager.duckdb.has()+HAS_SQL_DEPS = (+ DependencyManager.duckdb.has() and DependencyManager.altair.has()+)snapshot = snapshotter(__file__)@@ -38,6 +40,7 @@ def cleanup() -> Generator[None, None, None]:DROP TABLE IF EXISTS datetime_tbl;DROP TABLE IF EXISTS time_tbl;DROP TABLE IF EXISTS bool_tbl;+ DROP TABLE IF EXISTS large_tbl;""")@@ -56,7 +59,7 @@ def cleanup() -> Generator[None, None, None]:("category_col", "column_preview_categorical"),],)-def test_get_column_preview_dataframe(+def test_get_column_preview_for_dataframe(column_name: str, snapshot_prefix: str) -> None:import pandas as pd@@ -85,7 +88,7 @@ def test_get_column_preview_dataframe(mock_dm.vegafusion.has.return_value = Falsemock_dm.vl_convert_python.has.return_value = True- result = get_column_preview_dataframe(+ result = get_column_preview_for_dataframe(df,request=PreviewDatasetColumnRequest(source="source",@@ -108,7 +111,7 @@ def test_get_column_preview_dataframe(# Verify vegafusion was checkedmock_dm.vegafusion.has.assert_called_once()- result_with_vegafusion = get_column_preview_dataframe(+ result_with_vegafusion = get_column_preview_for_dataframe(df,request=PreviewDatasetColumnRequest(source="source",@@ -151,8 +154,8 @@ def test_get_column_preview_for_duckdb() -> None:""")# Test preview for the 'outcome' column (alternating 0 and 1)- result = get_column_preview_for_sql(- table_name="tbl",+ result = get_column_preview_for_duckdb(+ fully_qualified_table_name="tbl",column_name="outcome",)assert result is not None@@ -163,19 +166,20 @@ def test_get_column_preview_for_duckdb() -> None:assert result.summary.total == 100assert result.summary.unique == 2assert result.summary.mean == 0.5 # Exactly 0.5 due to alternating pattern+ assert result.chart_spec is not None# Test preview for the 'id' column (for comparison)- result_id = get_column_preview_for_sql(- table_name="tbl",+ result_id = get_column_preview_for_duckdb(+ fully_qualified_table_name="tbl",column_name="id",)assert result_id is not Noneassert result_id.summary is not Noneassert result_id.error is None+ assert result_id.chart_spec is not None# Not implemented yetassert result.chart_code is None- assert result.chart_spec is None@pytest.mark.skipif(@@ -198,8 +202,8 @@ def test_get_column_preview_for_duckdb_categorical() -> None:FROM range(100)""")- result_categorical = get_column_preview_for_sql(- table_name="tbl",+ result_categorical = get_column_preview_for_duckdb(+ fully_qualified_table_name="tbl",column_name="category",)assert result_categorical is not None@@ -210,10 +214,27 @@ def test_get_column_preview_for_duckdb_categorical() -> None:assert result_categorical.summary.total == 100assert result_categorical.summary.unique == 4assert result_categorical.summary.nulls == 0+ assert result_categorical.chart_spec is not None++ snapshot(+ "column_preview_duckdb_categorical_chart_spec.txt",+ result_categorical.chart_spec,+ )# Not implemented yetassert result_categorical.chart_code is None- assert result_categorical.chart_spec is None++ # Test works when fully qualified+ assert (+ get_column_preview_for_duckdb(+ fully_qualified_table_name="tbl",+ column_name="category",+ ).summary+ == get_column_preview_for_duckdb(+ fully_qualified_table_name="memory.main.tbl",+ column_name="category",+ ).summary+ )@pytest.mark.skipif(@@ -232,8 +253,8 @@ def test_get_column_preview_for_duckdb_date() -> None:FROM range(100)""")- result_date = get_column_preview_for_sql(- table_name="date_tbl",+ result_date = get_column_preview_for_duckdb(+ fully_qualified_table_name="date_tbl",column_name="date_col",)assert result_date is not None@@ -246,10 +267,24 @@ def test_get_column_preview_for_duckdb_date() -> None:assert result_date.summary.nulls == 0assert result_date.summary.min == datetime.datetime(2023, 1, 1, 0, 0)assert result_date.summary.max == datetime.datetime(2023, 4, 10, 0, 0)+ assert result_date.chart_spec is not None++ # No chart_spec snapshot because of date timezone# Not implemented yetassert result_date.chart_code is None- assert result_date.chart_spec is None++ # Test works when fully qualified+ assert (+ get_column_preview_for_duckdb(+ fully_qualified_table_name="date_tbl",+ column_name="date_col",+ ).summary+ == get_column_preview_for_duckdb(+ fully_qualified_table_name="memory.main.date_tbl",+ column_name="date_col",+ ).summary+ )@pytest.mark.skipif(@@ -271,8 +306,8 @@ def test_get_column_preview_for_duckdb_datetime() -> None:FROM range(100)""")- result_datetime = get_column_preview_for_sql(- table_name="datetime_tbl",+ result_datetime = get_column_preview_for_duckdb(+ fully_qualified_table_name="datetime_tbl",column_name="datetime_col",)assert result_datetime is not None@@ -285,10 +320,24 @@ def test_get_column_preview_for_duckdb_datetime() -> None:assert result_datetime.summary.nulls == 0assert result_datetime.summary.min == datetime.datetime(2023, 1, 1, 0, 0)assert result_datetime.summary.max == datetime.datetime(2023, 4, 10, 3, 39)+ assert result_datetime.chart_spec is not None# Not implemented yetassert result_datetime.chart_code is None- assert result_datetime.chart_spec is None++ # No chart_spec snapshot because of date timezone++ # Test works when fully qualified+ assert (+ get_column_preview_for_duckdb(+ fully_qualified_table_name="datetime_tbl",+ column_name="datetime_col",+ ).summary+ == get_column_preview_for_duckdb(+ fully_qualified_table_name="memory.main.datetime_tbl",+ column_name="datetime_col",+ ).summary+ )@pytest.mark.skipif(@@ -309,8 +358,8 @@ def test_get_column_preview_for_duckdb_time() -> None:FROM range(100)""")- result_time = get_column_preview_for_sql(- table_name="time_tbl",+ result_time = get_column_preview_for_duckdb(+ fully_qualified_table_name="time_tbl",column_name="time_col",)assert result_time is not None@@ -324,9 +373,11 @@ def test_get_column_preview_for_duckdb_time() -> None:assert result_time.summary.min == datetime.time(0, 0)assert result_time.summary.max == datetime.time(23, 47)+ # Time is not handled yet+ assert result_time.chart_spec is None+# Not implemented yetassert result_time.chart_code is None- assert result_time.chart_spec is None@pytest.mark.skipif(@@ -343,8 +394,8 @@ def test_get_column_preview_for_duckdb_bool() -> None:FROM range(100)""")- result_bool = get_column_preview_for_sql(- table_name="bool_tbl",+ result_bool = get_column_preview_for_duckdb(+ fully_qualified_table_name="bool_tbl",column_name="bool_col",)assert result_bool is not None@@ -357,7 +408,45 @@ def test_get_column_preview_for_duckdb_bool() -> None:assert result_bool.summary.nulls == 0assert result_bool.summary.true == 50assert result_bool.summary.false == 50+ assert result_bool.chart_spec is not None++ snapshot(+ "column_preview_duckdb_bool_chart_spec.txt", result_bool.chart_spec+ )# Not implemented yetassert result_bool.chart_code is None- assert result_bool.chart_spec is None+++ not HAS_SQL_DEPS, reason="optional dependencies not installed"+)[email protected](is_windows(), reason="Windows encodes base64 differently")+def test_get_column_preview_for_duckdb_over_limit() -> None:+ import duckdb++ from marimo._data.preview_column import CHART_MAX_ROWS++ # Create a table with more rows than the chart limit+ duckdb.execute(f"""+ CREATE OR REPLACE TABLE large_tbl AS+ SELECT+ range AS id,+ range % 5 AS category+ FROM range({CHART_MAX_ROWS + 100})+ """)++ # Test preview for a column in a table that exceeds the row limit+ result = get_column_preview_for_duckdb(+ fully_qualified_table_name="large_tbl",+ column_name="category",+ )++ assert result is not None+ assert result.summary is not None+ assert result.error is None+ assert result.chart_max_rows_errors is True+ assert result.chart_spec is None++ # Not implemented yet+ assert result.chart_code is None