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: Add download parquet to table (#4542)
Myles Scolnickca68742fb696
diff --git a/frontend/src/components/data-table/download-actions.tsx b/frontend/src/components/data-table/download-actions.tsxindex ac9e692da4..118fd03a95 100644--- a/frontend/src/components/data-table/download-actions.tsx+++ b/frontend/src/components/data-table/download-actions.tsx@@ -9,15 +9,33 @@ import {} from "../ui/dropdown-menu";import { toast } from "../ui/use-toast";import { downloadByURL } from "@/utils/download";-import { ChevronDownIcon } from "lucide-react";+import {+ BracesIcon,+ BrickWallIcon,+ ChevronDownIcon,+ TableIcon,+} from "lucide-react";export interface DownloadActionProps {- downloadAs: (req: { format: "csv" | "json" }) => Promise<string>;+ downloadAs: (req: { format: "csv" | "json" | "parquet" }) => Promise<string>;}const options = [- { label: "CSV", format: "csv" },- { label: "JSON", format: "json" },+ {+ label: "CSV",+ format: "csv",+ icon: TableIcon,+ },+ {+ label: "JSON",+ format: "json",+ icon: BracesIcon,+ },+ {+ label: "Parquet",+ format: "parquet",+ icon: BrickWallIcon,+ },] as const;export const DownloadAs: React.FC<DownloadActionProps> = (props) => {@@ -49,9 +67,11 @@ export const DownloadAs: React.FC<DownloadActionProps> = (props) => {if (!downloadUrl) {return;}- downloadByURL(downloadUrl, "download");+ const ext = option.format;+ downloadByURL(downloadUrl, `download.${ext}`);}}>+ <option.icon className="mo-dropdown-icon" />{option.label}</DropdownMenuItem>))}diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex e1c118d74a..c8fdc22a80 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -101,7 +101,7 @@ interface Data<T> {// eslint-disable-next-line @typescript-eslint/consistent-type-definitionstype DataTableFunctions = {- download_as: (req: { format: "csv" | "json" }) => Promise<string>;+ download_as: (req: { format: "csv" | "json" | "parquet" }) => Promise<string>;get_column_summaries: <T>(opts: {}) => Promise<ColumnSummaries<T>>;search: <T>(req: {sort?: {@@ -171,7 +171,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")).withFunctions<DataTableFunctions>({download_as: rpc- .input(z.object({ format: z.enum(["csv", "json"]) }))+ .input(z.object({ format: z.enum(["csv", "json", "parquet"]) })).output(z.string()),get_column_summaries: rpc.input(z.object({}).passthrough()).output(z.object({diff --git a/marimo/_output/data/data.py b/marimo/_output/data/data.pyindex 67150d1f48..f54d82835e 100644--- a/marimo/_output/data/data.py+++ b/marimo/_output/data/data.py@@ -82,6 +82,20 @@ def arrow(data: bytes) -> VirtualFile:return any_data(data, ext="arrow") # type: ignore+def parquet(data: bytes) -> VirtualFile:+ """Create a virtual file for Parquet data.++ **Args.**++ - data: Parquet data in bytes++ **Returns.**++ A `VirtualFile` object.+ """+ return any_data(data, ext="parquet") # type: ignore++def json(data: Union[str, bytes, io.BytesIO]) -> VirtualFile:"""Create a virtual file for JSON data.diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex bc549c904e..9e79041421 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -71,7 +71,7 @@ LOGGER = _loggers.marimo_logger()@dataclassclass DownloadAsArgs:- format: Literal["csv", "json"]+ format: Literal["csv", "json", "parquet"]@dataclass@@ -719,6 +719,8 @@ class table(return mo_data.csv(manager.to_csv()).urlelif ext == "json":return mo_data.json(manager.to_json()).url+ elif ext == "parquet":+ return mo_data.parquet(manager.to_parquet()).urlelse:raise ValueError("format must be one of 'csv' or 'json'.")else:diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.pyindex 579ce651fd..a62e11a4e6 100644--- a/marimo/_plugins/ui/_impl/tables/default_table.py+++ b/marimo/_plugins/ui/_impl/tables/default_table.py@@ -107,6 +107,13 @@ class DefaultTableManager(TableManager[JsonTableData]):).to_json_str(format_mapping)return self._as_table_manager().to_json_str(format_mapping)+ def to_parquet(self) -> bytes:+ if isinstance(self.data, dict) and not self.is_column_oriented:+ return DefaultTableManager(+ self._normalize_data(self.data)+ ).to_parquet()+ return self._as_table_manager().to_parquet()+def select_rows(self, indices: list[int]) -> DefaultTableManager:if isinstance(self.data, dict):# Column major datadiff --git a/marimo/_plugins/ui/_impl/tables/ibis_table.py b/marimo/_plugins/ui/_impl/tables/ibis_table.pyindex c590862054..718517e92e 100644--- a/marimo/_plugins/ui/_impl/tables/ibis_table.py+++ b/marimo/_plugins/ui/_impl/tables/ibis_table.py@@ -50,6 +50,9 @@ class IbisTableManagerFactory(TableManagerFactory):) -> str:return self._as_table_manager().to_json_str(format_mapping)+ def to_parquet(self) -> bytes:+ return self._as_table_manager().to_parquet()+def supports_download(self) -> bool:return Falsediff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.pyindex c1e401dd51..9855d377d0 100644--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py@@ -1,6 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import iofrom functools import cached_propertyfrom typing import Any, Optional, Union, cast@@ -83,6 +84,11 @@ class NarwhalsTableManager(csv_reader = csv.DictReader(csv_str.splitlines())return sanitize_json_bigint([row for row in csv_reader])+ def to_parquet(self) -> bytes:+ stream = io.BytesIO()+ self.as_frame().write_parquet(stream)+ return stream.getvalue()+def apply_formatting(self, format_mapping: Optional[FormatMapping]) -> NarwhalsTableManager[Any]:diff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.pyindex 72a2f743a8..858d74ce18 100644--- a/marimo/_plugins/ui/_impl/tables/table_manager.py+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py@@ -118,6 +118,10 @@ class TableManager(abc.ABC, Generic[T]):def to_json(self, format_mapping: Optional[FormatMapping] = None) -> bytes:return self.to_json_str(format_mapping).encode("utf-8")+ @abc.abstractmethod+ def to_parquet(self) -> bytes:+ raise NotImplementedError+@abc.abstractmethoddef select_rows(self, indices: list[int]) -> TableManager[Any]:passdiff --git a/tests/_plugins/ui/_impl/tables/test_default_table.py b/tests/_plugins/ui/_impl/tables/test_default_table.pyindex dbcac3684a..b2a802286c 100644--- a/tests/_plugins/ui/_impl/tables/test_default_table.py+++ b/tests/_plugins/ui/_impl/tables/test_default_table.py@@ -689,6 +689,12 @@ class TestColumnarDefaultTable(unittest.TestCase):)assert manager.to_json() == b'[{"a":1,"b":3},{"a":2,"b":4}]'+ @pytest.mark.skipif(+ not HAS_DEPS, reason="optional dependencies not installed"+ )+ def test_to_parquet(self) -> None:+ assert isinstance(self.manager.to_parquet(), bytes)+class TestDictionaryDefaultTable(unittest.TestCase):def setUp(self) -> None:@@ -895,3 +901,9 @@ class TestListDefaultTable(unittest.TestCase):assert selected_cells == [TableCell(row=2, column="value", value=6),]++ @pytest.mark.skipif(+ not HAS_DEPS, reason="optional dependencies not installed"+ )+ def test_to_parquet(self) -> None:+ assert isinstance(self.manager.to_parquet(), bytes)diff --git a/tests/_plugins/ui/_impl/tables/test_ibis_table.py b/tests/_plugins/ui/_impl/tables/test_ibis_table.pyindex 76df55f067..c2e1153393 100644--- a/tests/_plugins/ui/_impl/tables/test_ibis_table.py+++ b/tests/_plugins/ui/_impl/tables/test_ibis_table.py@@ -175,6 +175,9 @@ class TestIbisTableManagerFactory(unittest.TestCase):== b'[{"A":3}]')+ def test_to_parquet(self) -> None:+ assert isinstance(self.manager.to_parquet(), bytes)+def test_take_zero(self) -> None:limited_manager = self.manager.take(0, 0)assert limited_manager.data.count().execute() == 0diff --git a/tests/_plugins/ui/_impl/tables/test_narwhals.py b/tests/_plugins/ui/_impl/tables/test_narwhals.pyindex 06bbd5e8e2..fac64ab6f0 100644--- a/tests/_plugins/ui/_impl/tables/test_narwhals.py+++ b/tests/_plugins/ui/_impl/tables/test_narwhals.py@@ -767,6 +767,23 @@ def test_to_csv(df: Any) -> None:assert isinstance(manager.to_csv(), bytes)[email protected](not HAS_DEPS, reason="optional dependencies not installed")+ "df",+ create_dataframes(+ {+ "A": [1, 2, 3],+ "B": ["a", "b", "c"],+ "C": [1.0, 2.0, 3.0],+ },+ exclude=["ibis", "duckdb"],+ ),+)+def test_to_parquet(df: Any) -> None:+ manager = NarwhalsTableManager.from_dataframe(df)+ assert isinstance(manager.to_parquet(), bytes)++@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")@pytest.mark.parametrize("df",diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.pyindex 4ba10411c7..e0826edc1b 100644--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py@@ -157,6 +157,9 @@ class TestPandasTableManager(unittest.TestCase):manager = self.factory.create()(df)return json.loads(manager.to_json().decode("utf-8"))+ def test_to_parquet(self) -> None:+ assert isinstance(self.manager.to_parquet(), bytes)+def test_to_json(self) -> None:expected_json = self.data.to_json(orient="records", date_format="iso"diff --git a/tests/_plugins/ui/_impl/tables/test_polars_table.py b/tests/_plugins/ui/_impl/tables/test_polars_table.pyindex aa94a852d3..074c7c21cb 100644--- a/tests/_plugins/ui/_impl/tables/test_polars_table.py+++ b/tests/_plugins/ui/_impl/tables/test_polars_table.py@@ -179,6 +179,9 @@ class TestPolarsTableManagerFactory(unittest.TestCase):manager = self.factory.create()(df)assert isinstance(manager.to_csv(), bytes)+ def test_to_parquet(self) -> None:+ assert isinstance(self.manager.to_parquet(), bytes)+def test_to_json(self) -> None:assert isinstance(self.manager.to_json(), bytes)diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.pyindex a91ff21f54..3fa1ee6bac 100644--- a/tests/_plugins/ui/_impl/test_table.py+++ b/tests/_plugins/ui/_impl/test_table.py@@ -1049,6 +1049,9 @@ def test_show_download():assert table_false._component_args["show-download"] is False+DOWNLOAD_FORMATS = ["csv", "json", "parquet"]++@pytest.mark.skipif(not DependencyManager.pandas.has(), reason="Pandas not installed")@@ -1070,20 +1073,20 @@ def test_download_as_pandas() -> None:return _convert_data_bytes_to_pandas_df(download_str, format_type)# Test base downloads (full data)- for format_type in ["csv", "json"]:+ for format_type in DOWNLOAD_FORMATS:downloaded_df = download_and_convert(format_type, table)assert_frame_equal(data, downloaded_df)# Test downloads with search filtertable._search(SearchTableArgs(query="New", page_size=10, page_number=0))- for format_type in ["csv", "json"]:+ for format_type in DOWNLOAD_FORMATS:filtered_df = download_and_convert(format_type, table)assert len(filtered_df) == 2assert all(filtered_df["cities"].isin(["Newark", "New York"]))# Test downloads with selection (includes search from before)table._convert_value(["1"])- for format_type in ["csv", "json"]:+ for format_type in DOWNLOAD_FORMATS:selected_df = download_and_convert(format_type, table)assert len(selected_df) == 1assert selected_df["cities"].iloc[0] == "New York"@@ -1111,23 +1114,27 @@ def test_download_as_polars() -> None:if format_type == "json":return pl.read_json(data_bytes)- return pl.read_csv(data_bytes)+ if format_type == "parquet":+ return pl.read_parquet(data_bytes)+ if format_type == "csv":+ return pl.read_csv(data_bytes)+ raise ValueError(f"Unsupported format: {format_type}")# Test base downloads (full data)- for format_type in ["csv", "json"]:+ for format_type in DOWNLOAD_FORMATS:downloaded_df = download_and_convert(format_type, table)assert_frame_equal(data, downloaded_df)# Test downloads with search filtertable._search(SearchTableArgs(query="New", page_size=10, page_number=0))- for format_type in ["csv", "json"]:+ for format_type in DOWNLOAD_FORMATS:filtered_df = download_and_convert(format_type, table)assert len(filtered_df) == 2assert all(filtered_df["cities"].is_in(["Newark", "New York"]))# Test downloads with selection (includes search from before)table._convert_value(["1"])- for format_type in ["csv", "json"]:+ for format_type in DOWNLOAD_FORMATS:selected_df = download_and_convert(format_type, table)assert len(selected_df) == 1assert selected_df["cities"][0] == "New York"@@ -1151,6 +1158,22 @@ def test_download_as_for_supported_cell_selection() -> None:table._download_as(DownloadAsArgs(format="csv"))+ not DependencyManager.polars.has(),+ reason="Polars not installed",+)+ "fmt",+ ["csv", "json", "parquet"],+)+def test_download_as_for_dataframes(fmt: str) -> None:+ import polars as pl++ df = pl.DataFrame({"a": [1, 2, 3], "b": ["x", "y", "z"]})+ table = ui.table(df)+ table._download_as(DownloadAsArgs(format=fmt))++def test_pagination_behavior() -> None:# Test with default page_size=10data = {"a": list(range(8))}@@ -1636,5 +1659,7 @@ def _convert_data_bytes_to_pandas_df(return dfelif data_format == "json":return pd.read_json(io.BytesIO(data_bytes))+ elif data_format == "parquet":+ return pd.read_parquet(io.BytesIO(data_bytes))else:raise ValueError(f"Unsupported data_format: {data_format}")