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: export Arrow geometry as GeoJSON and GeoParquet (#11129)

Kiran Gadhave21eb4b72640c
diff --git a/marimo/_plugins/ui/_impl/tables/geometry_export.py b/marimo/_plugins/ui/_impl/tables/geometry_export.py
index 207057c668..aa8c43b0a8 100644
--- a/marimo/_plugins/ui/_impl/tables/geometry_export.py
+++ b/marimo/_plugins/ui/_impl/tables/geometry_export.py
@@ -67,6 +67,23 @@ class GeometryExportError(Exception):
self.missing_packages = missing_packages
+@dataclass(frozen=True)
+class ArrowGeometryDeclaration:
+ """Geometry semantics declared in GeoArrow field metadata.
+
+ Args:
+ crs (str | dict[str, Any] | None): Declared CRS or opaque identifier.
+ crs_type (str | None): Declared CRS representation.
+ edges (str | None): Declared non-planar edge interpretation.
+ error (str | None): Reason that the declaration is invalid.
+ """
+
+ crs: str | dict[str, Any] | None = None
+ crs_type: str | None = None
+ edges: str | None = None
+ error: str | None = None
+
+
@dataclass(frozen=True)
class GeometryExportColumn:
"""Geometry declared by the export source.
@@ -128,13 +145,14 @@ def get_export_metadata(manager: TableManager[Any]) -> ExportMetadata:
if not isinstance(manager, NarwhalsTableManager):
return ExportMetadata()
- info_by_name = find_geometry_columns(manager.data)
+ info_by_name = _export_geometry_columns(manager)
if not info_by_name:
return ExportMetadata()
source = manager.data
primary: str | None = None
columns: list[GeometryExportColumn] = []
+ source_reason: str | None = None
if source.implementation.is_pandas():
native = source.to_native()
candidate = getattr(native, "_geometry_column_name", None)
@@ -153,14 +171,26 @@ def get_export_metadata(manager: TableManager[Any]) -> ExportMetadata:
elif source.implementation.is_pyarrow():
native = source.to_native()
for name, info in info_by_name.items():
+ declaration = _arrow_geometry_declaration(
+ native.schema.field(name)
+ )
columns.append(
GeometryExportColumn(
name=name,
encoding=info.encoding,
- crs=_arrow_crs(native.schema.field(name).metadata),
+ crs=(
+ declaration.crs
+ if declaration.crs_type != "srid"
+ else None
+ ),
)
)
- is_supported_source = False
+ rejection = _arrow_geometry_rejection(
+ name, info.encoding, declaration
+ )
+ if source_reason is None and rejection is not None:
+ source_reason = rejection[1]
+ is_supported_source = DependencyManager.geopandas.has()
else:
columns = [
GeometryExportColumn(name=name, encoding=info.encoding, crs=None)
@@ -174,16 +204,15 @@ def get_export_metadata(manager: TableManager[Any]) -> ExportMetadata:
("parquet", "GeoParquet"),
("geojson", "GeoJSON"),
):
- if source.implementation.is_pandas():
- reason = (
- f"This pandas table needs geopandas to export {label}."
+ if (
+ source.implementation.is_pandas()
+ or source.implementation.is_pyarrow()
+ ):
+ source_label = (
+ "pandas" if source.implementation.is_pandas() else "Arrow"
)
+ reason = f"This {source_label} table needs geopandas to export {label}."
missing_packages = ["geopandas"]
- elif source.implementation.is_pyarrow():
- reason = (
- f"{label} export from Arrow tables is not supported yet."
- )
- missing_packages = []
else:
reason = (
f"{label} export is not supported for this table type."
@@ -219,6 +248,14 @@ def get_export_metadata(manager: TableManager[Any]) -> ExportMetadata:
else:
formats["parquet"] = ExportFormatEligibility(available=True)
+ if source_reason is not None:
+ formats = {
+ name: ExportFormatEligibility(
+ available=False, reason=source_reason
+ )
+ for name in ("parquet", "geojson")
+ }
+
default = (
primary
if primary is not None
@@ -232,22 +269,102 @@ def get_export_metadata(manager: TableManager[Any]) -> ExportMetadata:
)
-def _arrow_crs(
- metadata: dict[bytes, bytes] | None,
-) -> str | dict[str, Any] | None:
+def _arrow_geometry_declaration(
+ field: pa.Field[Any],
+) -> ArrowGeometryDeclaration:
+ field = _arrow_storage_field(field)
+ metadata = field.metadata
if not metadata:
- return None
+ return ArrowGeometryDeclaration()
raw = metadata.get(b"ARROW:extension:metadata")
if raw is None:
- return None
+ return ArrowGeometryDeclaration()
+
+ def invalid(reason: str) -> ArrowGeometryDeclaration:
+ return ArrowGeometryDeclaration(
+ error=f"Geometry column {field.name!r} has invalid GeoArrow metadata: {reason}"
+ )
+
try:
- declaration = json.loads(raw)
+ declaration = json.loads(
+ raw.decode("utf-8"), parse_constant=_reject_json_constant
+ )
except (ValueError, UnicodeDecodeError):
- return None
+ return invalid("expected a UTF-8 JSON object.")
if not isinstance(declaration, dict):
- return None
+ return invalid("expected a JSON object.")
crs = declaration.get("crs")
- return crs if isinstance(crs, (str, dict)) else None
+ if "crs" in declaration and not isinstance(crs, (str, dict)):
+ return invalid("crs must be a string or PROJJSON object.")
+ crs_type = declaration.get("crs_type")
+ if "crs_type" in declaration and crs_type not in (
+ "projjson",
+ "wkt2:2019",
+ "authority_code",
+ "srid",
+ ):
+ return invalid("unknown crs_type.")
+ if crs is not None and crs_type is not None:
+ if crs_type == "projjson" and not isinstance(crs, dict):
+ return invalid("projjson crs must be an object.")
+ if crs_type != "projjson" and not isinstance(crs, str):
+ return invalid(f"{crs_type} crs must be a string.")
+ edges = declaration.get("edges")
+ if "edges" in declaration and edges not in (
+ "spherical",
+ "vincenty",
+ "thomas",
+ "andoyer",
+ "karney",
+ ):
+ return invalid("unknown edges interpretation.")
+ if (
+ crs is not None
+ and crs_type != "srid"
+ and DependencyManager.geopandas.has()
+ ):
+ from pyproj import CRS # type: ignore[import-not-found,import-untyped,unused-ignore]
+ from pyproj.exceptions import CRSError # type: ignore[import-not-found,import-untyped,unused-ignore]
+
+ try:
+ if crs_type == "projjson":
+ CRS.from_json_dict(crs)
+ elif crs_type == "wkt2:2019":
+ CRS.from_wkt(crs)
+ elif crs_type == "authority_code":
+ authority, code = crs.split(":", 1)
+ CRS.from_authority(authority, code)
+ else:
+ CRS.from_user_input(crs)
+ except (CRSError, ValueError):
+ return invalid("crs cannot be resolved.")
+ return ArrowGeometryDeclaration(crs=crs, crs_type=crs_type, edges=edges)
+
+
+def _arrow_geometry_rejection(
+ name: str,
+ encoding: GeometryEncoding,
+ declaration: ArrowGeometryDeclaration,
+) -> tuple[GeometryExportErrorCode, str] | None:
+ if declaration.error is not None:
+ return "invalid_metadata", declaration.error
+ if declaration.edges is not None:
+ return (
+ "unsupported_representation",
+ (
+ f"Geometry column {name!r} declares {declaration.edges!r} "
+ "edges, which geographic exports cannot preserve."
+ ),
+ )
+ if encoding not in ("wkb", "wkt"):
+ return (
+ "unsupported_representation",
+ (
+ f"Geometry column {name!r} uses a native GeoArrow layout. "
+ "Geographic exports require WKB or WKT."
+ ),
+ )
+ return None
def has_geometry_columns(manager: TableManager[Any]) -> bool:
@@ -257,7 +374,119 @@ def has_geometry_columns(manager: TableManager[Any]) -> bool:
manager (TableManager[Any]): Manager for the export source.
"""
return isinstance(manager, NarwhalsTableManager) and bool(
- find_geometry_columns(manager.data)
+ _export_geometry_columns(manager)
+ )
+
+
+def _arrow_storage_field(field: pa.Field[Any]) -> pa.Field[Any]:
+ import pyarrow as pa
+
+ if not isinstance(field.type, pa.ExtensionType):
+ return field
+ extension = field.type
+ if not (
+ extension.extension_name.startswith("geoarrow.")
+ or extension.extension_name == "ogc.wkb"
+ ):
+ return field
+ metadata: dict[bytes | str, bytes | str] = {
+ key: value for key, value in (field.metadata or {}).items()
+ }
+ metadata[b"ARROW:extension:name"] = extension.extension_name.encode()
+ serialized = extension.__arrow_ext_serialize__()
+ if extension.extension_name == "ogc.wkb" and not serialized:
+ metadata.pop(b"ARROW:extension:metadata", None)
+ else:
+ metadata[b"ARROW:extension:metadata"] = serialized
+ return field.with_type(extension.storage_type).with_metadata(metadata)
+
+
+def _export_geometry_columns(
+ manager: NarwhalsTableManager[Any, Any],
+) -> dict[str, GeometryColumnInfo]:
+ if not manager.data.implementation.is_pyarrow():
+ return find_geometry_columns(manager.data)
+
+ import pyarrow as pa
+
+ schema = pa.schema(
+ [
+ _arrow_storage_field(field)
+ for field in manager.data.to_native().schema
+ ]
+ )
+ schema_view = pa.Table.from_batches([], schema=schema)
+ return find_geometry_columns(nw.from_native(schema_view))
+
+
+def _arrow_to_geodataframe(
+ table: pa.Table, columns: list[GeometryExportColumn]
+) -> Any:
+ import geopandas as gpd # type: ignore[import-not-found,import-untyped,unused-ignore]
+ import pandas as pd
+ import pyarrow as pa
+
+ if len(set(table.column_names)) != len(table.column_names):
+ raise GeometryExportError(
+ "invalid_metadata",
+ "Geographic exports require unique column names.",
+ )
+ for column in columns:
+ declaration = _arrow_geometry_declaration(
+ table.schema.field(column.name)
+ )
+ rejection = _arrow_geometry_rejection(
+ column.name, column.encoding, declaration
+ )
+ if rejection is not None:
+ raise GeometryExportError(
+ rejection[0], rejection[1], column=column.name
+ )
+
+ try:
+ ordinary = table.drop([column.name for column in columns]).to_pandas(
+ ignore_metadata=True, types_mapper=pd.ArrowDtype
+ )
+ frame = gpd.GeoDataFrame(ordinary)
+ for index, column in enumerate(columns):
+ values = table.column(column.name)
+ decoded = [
+ value
+ for chunk in values.chunks
+ for value in (
+ chunk.storage
+ if isinstance(chunk, pa.ExtensionArray)
+ else chunk
+ ).to_pylist()
+ ]
+ parser = (
+ gpd.GeoSeries.from_wkb
+ if column.encoding == "wkb"
+ else gpd.GeoSeries.from_wkt
+ )
+ geometry = parser(decoded, crs=column.crs, index=frame.index)
+ if index == 0:
+ frame = frame.set_geometry(geometry.rename(column.name))
+ else:
+ frame[column.name] = geometry
+ return frame[table.column_names]
+ except Exception as e:
+ raise GeometryExportError(
+ "conversion_failed", f"Could not convert Arrow geometry: {e}"
+ ) from e
+
+
+def _export_geodataframe(
+ manager: NarwhalsTableManager[Any, Any], metadata: ExportMetadata
+) -> Any:
+ native = manager.as_frame().to_native()
+ if manager.data.implementation.is_pandas():
+ return native
+ if manager.data.implementation.is_pyarrow():
+ return _arrow_to_geodataframe(native, metadata.geometry_columns)
+ raise GeometryExportError(
+ "unsupported_representation",
+ "Geographic export from this table type is not supported yet.",
)
@@ -284,9 +513,9 @@ def serialize_geojson(
"GeoJSON export requires a declared geometry column.",
column=geometry_column,
)
- if (
- not isinstance(manager, NarwhalsTableManager)
- or not manager.data.implementation.is_pandas()
+ if not isinstance(manager, NarwhalsTableManager) or not (
+ manager.data.implementation.is_pandas()
+ or manager.data.implementation.is_pyarrow()
):
raise GeometryExportError(
"unsupported_representation",
@@ -317,9 +546,12 @@ def serialize_geojson(
"Choose a geometry column for GeoJSON export.",
)
if not DependencyManager.geopandas.has():
+ source_label = (
+ "pandas" if manager.data.implementation.is_pandas() else "Arrow"
+ )
raise GeometryExportError(
"missing_packages",
- "This pandas table needs geopandas to export GeoJSON.",
+ f"This {source_label} table needs geopandas to export GeoJSON.",
missing_packages=["geopandas"],
)
if not DependencyManager.shapely.has_at_version(
@@ -338,7 +570,7 @@ def serialize_geojson(
_trivial_range_index,
)
- native = manager.as_frame().to_native()
+ native = _export_geodataframe(manager, metadata)
if not native.columns.is_unique:
raise GeometryExportError(
"invalid_metadata", "GeoJSON export requires unique column names."
@@ -376,8 +608,10 @@ def serialize_geojson(
crs=projected.crs,
)
export = gpd.GeoDataFrame(geometry=projected)
- properties_manager = prepare_geometry_text_export(
- manager.drop_columns([primary])
+ properties_manager = (
+ _prepare_arrow_geojson_properties(manager, native, primary, names)
+ if manager.data.implementation.is_pyarrow()
+ else prepare_geometry_text_export(manager.drop_columns([primary]))
)
properties: list[dict[str, Any]]
if len(native.columns) == 1 and not exports_index:
@@ -454,6 +688,40 @@ def serialize_geojson(
) from e
+def _prepare_arrow_geojson_properties(
+ manager: NarwhalsTableManager[Any, Any],
+ frame: Any,
+ primary: str,
+ geometry_columns: set[str],
+) -> TableManager[Any]:
+ import pyarrow as pa
+
+ source: pa.Table = manager.as_frame().to_native()
+ properties = source.drop([primary])
+ for name in geometry_columns - {primary}:
+ index = properties.schema.get_field_index(name)
+ original = properties.schema.field(index)
+ metadata = {
+ key: value
+ for key, value in (original.metadata or {}).items()
+ if key
+ not in (b"ARROW:extension:name", b"ARROW:extension:metadata")
+ }
+ field = pa.field(
+ name,
+ pa.string(),
+ nullable=original.nullable,
+ metadata=metadata or None,
+ )
+ values = pa.array(
+ frame[name].to_wkt(rounding_precision=-1),
+ type=pa.string(),
+ from_pandas=True,
+ )
+ properties = properties.set_column(index, field, values)
+ return _with_native_data(manager, properties)
+
+
def _reject_json_constant(value: str) -> Any:
raise ValueError(f"Invalid JSON constant: {value}")
@@ -608,7 +876,7 @@ def _validate_geojson_geometry(geometry: dict[str, Any]) -> None:
def serialize_geoparquet(
manager: TableManager[Any], geometry_column: str | None
) -> bytes | None:
- """Write declared GeoPandas geometry as GeoParquet 1.0.0.
+ """Write declared geometry as GeoParquet 1.0.0.
Args:
manager (TableManager[Any]): Manager for the effective export rows.
@@ -630,9 +898,9 @@ def serialize_geoparquet(
)
return None
- if (
- not isinstance(manager, NarwhalsTableManager)
- or not manager.data.implementation.is_pandas()
+ if not isinstance(manager, NarwhalsTableManager) or not (
+ manager.data.implementation.is_pandas()
+ or manager.data.implementation.is_pyarrow()
):
raise GeometryExportError(
"unsupported_representation",
@@ -640,12 +908,12 @@ def serialize_geoparquet(
column=geometry_column,
)
- native = manager.as_frame().to_native()
- if not native.columns.is_unique:
- raise GeometryExportError(
- "invalid_metadata",
- "GeoParquet export requires unique column names.",
- )
+ if manager.data.implementation.is_pandas():
+ if not manager.as_frame().to_native().columns.is_unique:
+ raise GeometryExportError(
+ "invalid_metadata",
+ "GeoParquet export requires unique column names.",
+ )
try:
metadata = get_export_metadata(manager)
@@ -673,9 +941,12 @@ def serialize_geoparquet(
)
if not DependencyManager.geopandas.has():
+ source_label = (
+ "pandas" if manager.data.implementation.is_pandas() else "Arrow"
+ )
raise GeometryExportError(
"missing_packages",
- "This pandas table needs geopandas to export GeoParquet.",
+ f"This {source_label} table needs geopandas to export GeoParquet.",
missing_packages=["geopandas"],
)
if not DependencyManager.geopandas.has_at_version(
@@ -693,6 +964,13 @@ def serialize_geoparquet(
import geopandas as gpd # type: ignore[import-not-found,import-untyped,unused-ignore]
+ native = _export_geodataframe(manager, metadata)
+ if not native.columns.is_unique:
+ raise GeometryExportError(
+ "invalid_metadata",
+ "GeoParquet export requires unique column names.",
+ )
+
for name in names:
for geometry in native[name].array:
if geometry is not None and getattr(geometry, "has_m", False):
@@ -771,7 +1049,9 @@ def _validate_geoparquet(
or not isinstance(column.get("geometry_types"), list)
or "crs" not in column
or name not in schema.names
- or not pa.types.is_binary(schema.field(name).type)
+ or not pa.types.is_binary(
+ _arrow_storage_field(schema.field(name)).type
+ )
):
raise GeometryExportError(
"invalid_metadata",
diff --git a/tests/_cli/test_cli_development.py b/tests/_cli/test_cli_development.py
index 9cc089a9b3..3794e669ef 100644
--- a/tests/_cli/test_cli_development.py
+++ b/tests/_cli/test_cli_development.py
@@ -1,11 +1,31 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import json
import subprocess
+from typing import Any
import yaml
+def _normalize_union_order(schema: Any) -> Any:
+ if isinstance(schema, list):
+ return [_normalize_union_order(value) for value in schema]
+ if isinstance(schema, dict):
+ result = {
+ key: _normalize_union_order(value) for key, value in schema.items()
+ }
+ # msgspec versions can emit equivalent union alternatives in a different order.
+ for key in ("anyOf", "oneOf"):
+ if isinstance(result.get(key), list):
+ result[key] = sorted(
+ result[key],
+ key=lambda value: json.dumps(value, sort_keys=True),
+ )
+ return result
+ return schema
+
+
def test_cli_development_openapi() -> None:
p = subprocess.run(
["marimo", "development", "openapi"],
@@ -33,6 +53,8 @@ def test_openapi_up_to_date() -> None:
generated_content["info"].pop("version", None)
cmd = "marimo development openapi > packages/openapi/api.yaml && make fe-codegen"
- assert current_content == generated_content, (
+ assert _normalize_union_order(current_content) == _normalize_union_order(
+ generated_content
+ ), (
f"packages/openapi/api.yaml is not up to date. Run '{cmd}' to update it."
)
diff --git a/tests/_plugins/ui/_impl/tables/geometry_fixtures.py b/tests/_plugins/ui/_impl/tables/geometry_fixtures.py
index e2c9f9ba43..2a80e21b97 100644
--- a/tests/_plugins/ui/_impl/tables/geometry_fixtures.py
+++ b/tests/_plugins/ui/_impl/tables/geometry_fixtures.py
@@ -14,6 +14,7 @@ when the extension cannot load.
from __future__ import annotations
import datetime
+import json
from typing import TYPE_CHECKING, Any
import pytest
@@ -217,6 +218,82 @@ def arrow_other_geoarrow() -> pa_mod.Table:
)
+def arrow_multi_geometry() -> pa_mod.Table:
+ import pyarrow as pa
+ from pyproj import CRS
+ from shapely.geometry import Point
+
+ fields: list[pa.Field[Any]] = [
+ pa.field("name", pa.string()),
+ pa.field(
+ "geom_a",
+ pa.binary(),
+ metadata={
+ b"ARROW:extension:name": b"geoarrow.wkb",
+ b"ARROW:extension:metadata": b'{"crs":"EPSG:3857"}',
+ },
+ ),
+ pa.field(
+ "geom_b",
+ pa.string(),
+ metadata={
+ b"ARROW:extension:name": b"geoarrow.wkt",
+ b"ARROW:extension:metadata": json.dumps(
+ {"crs": CRS.from_epsg(4326).to_json_dict()}
+ ).encode(),
+ },
+ ),
+ ]
+ schema = pa.schema(fields)
+ return pa.table(
+ {
+ "name": ["projected", "null"],
+ "geom_a": [Point(1113194.9079327357, 0).wkb, None],
+ "geom_b": ["POINT (20 5)", None],
+ },
+ schema=schema,
+ )
+
+
+def arrow_wkb_projected() -> pa_mod.Table:
+ return arrow_multi_geometry().select(["name", "geom_a"])
+
+
+def _arrow_with_geometry_metadata(raw: bytes) -> pa_mod.Table:
+ source = arrow_wkb_known_crs()
+ field = source.schema.field("geom").with_metadata(
+ {
+ b"ARROW:extension:name": b"geoarrow.wkb",
+ b"ARROW:extension:metadata": raw,
+ }
+ )
+ return source.cast(source.schema.set(1, field))
+
+
+def arrow_malformed_metadata() -> pa_mod.Table:
+ return _arrow_with_geometry_metadata(b"[]")
+
+
+def arrow_spherical_edges() -> pa_mod.Table:
+ return _arrow_with_geometry_metadata(
+ b'{"crs":"EPSG:4326","edges":"spherical"}'
+ )
+
+
+def arrow_srid_crs() -> pa_mod.Table:
+ return _arrow_with_geometry_metadata(
+ b'{"crs":"EPSG:4326","crs_type":"srid"}'
+ )
+
+
+def arrow_invalid_wkb() -> pa_mod.Table:
+ import pyarrow as pa
+
+ return _arrow_table_with_extension(
+ "geoarrow.wkb", [b"invalid", None], pa.binary(), crs=True
+ )
+
+
# --- DuckDB spatial ----------------------------------------------------
diff --git a/tests/_plugins/ui/_impl/test_export_metadata.py b/tests/_plugins/ui/_impl/test_export_metadata.py
index 3a502ddbed..4ba671036d 100644
--- a/tests/_plugins/ui/_impl/test_export_metadata.py
+++ b/tests/_plugins/ui/_impl/test_export_metadata.py
@@ -185,22 +185,16 @@ def test_old_shapely_disables_only_geojson(widget: Any) -> None:
assert result.formats["parquet"].available
[email protected]("geopandas", "pyarrow")
def test_arrow_crs_comes_from_field_metadata(widget: Any) -> None:
subject = widget(fixtures.arrow_wkb_known_crs())
result = subject._get_export_metadata(EmptyArgs())
assert [asdict(column) for column in result.geometry_columns] == [
{"name": "geom", "encoding": "wkb", "crs": "EPSG:4326"},
]
- assert asdict(result.formats["parquet"]) == {
- "available": False,
- "reason": "GeoParquet export from Arrow tables is not supported yet.",
- "missing_packages": [],
- }
- assert asdict(result.formats["geojson"]) == {
- "available": False,
- "reason": "GeoJSON export from Arrow tables is not supported yet.",
- "missing_packages": [],
+ assert {name: asdict(value) for name, value in result.formats.items()} == {
+ name: {"available": True, "reason": None, "missing_packages": []}
+ for name in ("parquet", "geojson")
}
diff --git a/tests/_plugins/ui/_impl/test_geojson_export.py b/tests/_plugins/ui/_impl/test_geojson_export.py
index 0ff08d06b3..b04c02cd59 100644
--- a/tests/_plugins/ui/_impl/test_geojson_export.py
+++ b/tests/_plugins/ui/_impl/test_geojson_export.py
@@ -2,7 +2,7 @@
from __future__ import annotations
import json
-from typing import Any
+from typing import Any, Literal
from unittest.mock import patch
import pytest
@@ -10,6 +10,10 @@ import pytest
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins import ui
from marimo._plugins.ui._impl.table import DownloadAsArgs, DownloadGeoJSONArgs
+from marimo._plugins.ui._impl.tables.geometry_export import (
+ ExportFormatEligibility,
+)
+from marimo._runtime.functions import EmptyArgs
from marimo._utils.data_uri import from_data_uri
from tests._plugins.ui._impl.tables import geometry_fixtures as fixtures
@@ -686,11 +690,484 @@ def test_invalid_choice_is_rejected_atomically(
publish.assert_not_called()
-def test_arrow_geometry_is_not_exported_as_geojson(widget: Any) -> None:
[email protected]("geopandas", "pyarrow")
+ "factory",
+ [
+ fixtures.arrow_wkb_known_crs,
+ fixtures.arrow_wkt,
+ fixtures.arrow_multi_geometry,
+ ],
+)
+def test_arrow_geometry_is_eligible_for_geojson(
+ widget: Any, factory: Any
+) -> None:
+ metadata = widget(factory())._get_export_metadata(EmptyArgs())
+ assert metadata.formats["geojson"] == ExportFormatEligibility(
+ available=True
+ )
+
+
[email protected]("geopandas", "pyarrow")
+def test_arrow_geojson_checks_shapely_version(widget: Any) -> None:
subject = widget(fixtures.arrow_wkb_known_crs())
- response = subject._download_geojson(DownloadGeoJSONArgs(format="geojson"))
- assert (response.url, response.code) == ("", "unsupported_representation")
+ with patch.object(
+ DependencyManager.shapely, "has_at_version", return_value=False
+ ):
+ metadata = subject._get_export_metadata(EmptyArgs())
+ assert metadata.formats["geojson"] == ExportFormatEligibility(
+ available=False,
+ reason="Update shapely to 2.0 or newer to export GeoJSON.",
+ )
+
+
[email protected]("geopandas", "pyarrow")
[email protected]("choice", ["geom_a", "geom_b"])
[email protected]("wrapped", [False, True], ids=["native", "narwhals"])
+def test_arrow_geojson_reprojects_and_preserves_source_properties(
+ widget: Any, choice: str, wrapped: bool
+) -> None:
+ import datetime
+
+ import narwhals.stable.v2 as nw
+ import pyarrow as pa
+ from shapely import from_wkt
+
+ source = fixtures.arrow_multi_geometry()
+ source = source.append_column(
+ "count", pa.array([2**63 + 1, None], type=pa.uint64())
+ )
+ source = source.append_column("float", pa.array([1.25, None]))
+ source = source.append_column(
+ "date", pa.array([datetime.date(2026, 10, 5), None])
+ )
+ source = source.append_column(
+ "nested", pa.array([{"items": [1, 2]}, None])
+ )
+ subject = widget(nw.from_native(source) if wrapped else source)
+ before = pa.BufferOutputStream()
+ with pa.ipc.new_stream(before, source.schema) as writer:
+ writer.write_table(source)
+ original_bytes = before.getvalue().to_pybytes()
+ ordinary = subject._download_as(DownloadAsArgs(format="json"))
+ assert ordinary.error is None
+ expected = json.loads(
+ from_data_uri(ordinary.url)[1], parse_constant=_reject_constant
+ )
+ for row in expected:
+ del row[choice]
+
+ document = _artifact(subject, choice)
+ assert document["type"] == "FeatureCollection"
+ assert [
+ feature["properties"] for feature in document["features"]
+ ] == expected
+ assert document["features"][0]["geometry"] == {
+ "type": "Point",
+ "coordinates": pytest.approx(
+ [10, 0] if choice == "geom_a" else [20, 5]
+ ),
+ }
+ assert document["features"][1]["geometry"] is None
+ secondary = "geom_b" if choice == "geom_a" else "geom_a"
+ text = document["features"][0]["properties"][secondary]
+ restored = from_wkt(text)
+ expected_coordinates: list[float] = (
+ [20, 5] if choice == "geom_a" else [1113194.9079327357, 0]
+ )
+ assert next(iter(restored.coords)) == pytest.approx(expected_coordinates)
+ assert document["features"][1]["properties"][secondary] is None
+ after = pa.BufferOutputStream()
+ with pa.ipc.new_stream(after, source.schema) as writer:
+ writer.write_table(source)
+ assert after.getvalue().to_pybytes() == original_bytes
+
+
[email protected]("geopandas", "pyarrow")
+def test_arrow_geojson_projected_wkb_uses_sole_geometry(widget: Any) -> None:
+ document = _artifact(widget(fixtures.arrow_wkb_projected()))
+ assert document == {
+ "type": "FeatureCollection",
+ "features": [
+ {
+ "type": "Feature",
+ "geometry": {
+ "type": "Point",
+ "coordinates": pytest.approx([10, 0]),
+ },
+ "properties": {"name": "projected"},
+ },
+ {
+ "type": "Feature",
+ "geometry": None,
+ "properties": {"name": "null"},
+ },
+ ],
+ }
+
+
[email protected]("geopandas", "pyarrow")
+def test_arrow_geojson_nonfinite_properties_publish_no_artifact(
+ widget: Any,
+) -> None:
+ import pyarrow as pa
+
+ source = fixtures.arrow_wkb_projected().append_column(
+ "value", pa.array([float("nan"), None])
+ )
+ subject = widget(source)
+ function = next(
+ function
+ for function in subject._args.functions
+ if function.name == "download_geojson"
+ )
+ with patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish:
+ response = function({"format": "geojson"})
+ assert (response.url, response.filename, response.code) == (
+ "",
+ "",
+ "conversion_failed",
+ )
+ publish.assert_not_called()
+
+
[email protected]("geopandas", "pyarrow")
[email protected]("encoding", ["wkb", "wkt"])
+def test_arrow_geojson_secondary_wkt_is_complete(
+ widget: Any, encoding: str
+) -> None:
+ import numpy as np
+ import pyarrow as pa
+ from shapely import from_wkt
+ from shapely.geometry import LineString
+
+ geometry = LineString([(i, i / 7) for i in range(4000)])
+ value = geometry.wkb if encoding == "wkb" else geometry.wkt
+ source = fixtures.arrow_wkb_projected()
+ field = pa.field(
+ "secondary",
+ pa.binary() if encoding == "wkb" else pa.string(),
+ metadata={b"ARROW:extension:name": f"geoarrow.{encoding}".encode()},
+ )
+ source = source.append_column(
+ field, pa.array([value, None], type=field.type)
+ )
+ properties = _artifact(widget(source), "geom_a")["features"][0][
+ "properties"
+ ]
+ assert len(properties["secondary"]) > 40_000
+ assert np.asarray(
+ from_wkt(properties["secondary"]).coords
+ ) == pytest.approx(np.asarray(geometry.coords), rel=1e-15, abs=0)
+
+
[email protected]("geopandas", "pyarrow")
[email protected]("srid", [False, True])
+def test_arrow_geojson_known_alternate_crs_can_be_chosen(
+ widget: Any, srid: bool
+) -> None:
+ source = fixtures.arrow_multi_geometry()
+ raw = b'{"crs":"local-id","crs_type":"srid"}' if srid else b"{}"
+ field = source.schema.field("geom_a").with_metadata(
+ {
+ b"ARROW:extension:name": b"geoarrow.wkb",
+ b"ARROW:extension:metadata": raw,
+ }
+ )
+ subject = widget(source.cast(source.schema.set(1, field)))
+ function = next(
+ function
+ for function in subject._args.functions
+ if function.name == "download_geojson"
+ )
+ response = function({"format": "geojson", "geometry_column": "geom_a"})
+ assert (response.url, response.code, response.column) == (
+ "",
+ "missing_crs",
+ "geom_a",
+ )
+ features = _artifact(subject, "geom_b")["features"]
+ assert features[0]["geometry"]["coordinates"] == [20, 5]
+ assert (
+ features[0]["properties"]["geom_a"] == "POINT (1113194.9079327357 0)"
+ )
+
+
[email protected]("geopandas", "pyarrow")
[email protected]("empty", [False, True])
+def test_arrow_geojson_geometry_only_keeps_rows_and_z(
+ widget: Any, empty: bool
+) -> None:
+ source = fixtures.arrow_wkt().select(["geom"])
+ if empty:
+ source = source.slice(0, 0)
+ expected = (
+ []
+ if empty
+ else [
+ {
+ "type": "Feature",
+ "geometry": {"type": "Point", "coordinates": [1, 2]},
+ "properties": {},
+ },
+ {
+ "type": "Feature",
+ "geometry": {"type": "Point", "coordinates": [1, 2, 3]},
+ "properties": {},
+ },
+ {"type": "Feature", "geometry": None, "properties": {}},
+ ]
+ )
+ assert _artifact(widget(source)) == {
+ "type": "FeatureCollection",
+ "features": expected,
+ }
+
+
[email protected]("geopandas", "pyarrow")
[email protected]("empty", [False, True])
+ "factory", [fixtures.arrow_wkb_missing_crs, fixtures.arrow_srid_crs]
+)
+def test_arrow_geojson_unknown_crs_rejects_before_reprojection(
+ widget: Any, factory: Any, empty: bool
+) -> None:
+ import geopandas as gpd
+
+ source = factory()
+ if empty:
+ source = source.slice(0, 0)
+ subject = widget(source)
+ function = next(
+ function
+ for function in subject._args.functions
+ if function.name == "download_geojson"
+ )
+ with (
+ patch.object(gpd.GeoSeries, "to_crs") as reproject,
+ patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish,
+ ):
+ response = function({"format": "geojson"})
+ assert (
+ response.url,
+ response.filename,
+ response.code,
+ response.column,
+ ) == ("", "", "missing_crs", "geom")
+ assert (
+ response.error
+ == "Geometry column 'geom' needs a CRS for GeoJSON export. Declare its source CRS in Python before exporting."
+ )
+ reproject.assert_not_called()
+ publish.assert_not_called()
+
+
[email protected]("geopandas", "pyarrow")
+ ("factory", "code"),
+ [
+ (fixtures.arrow_malformed_metadata, "invalid_metadata"),
+ (fixtures.arrow_spherical_edges, "unsupported_representation"),
+ (fixtures.arrow_other_geoarrow, "unsupported_representation"),
+ (fixtures.arrow_invalid_wkb, "conversion_failed"),
+ ],
+)
+def test_arrow_geojson_failures_publish_no_artifact(
+ widget: Any, factory: Any, code: str
+) -> None:
+ subject = widget(factory())
+ function = next(
+ function
+ for function in subject._args.functions
+ if function.name == "download_geojson"
+ )
+ with patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish:
+ response = function({"format": "geojson"})
+ assert (response.url, response.filename, response.code) == ("", "", code)
+ publish.assert_not_called()
+
+
[email protected]("geopandas", "pyarrow")
[email protected]("choice", [None, "name", "missing"])
+def test_arrow_geojson_requires_valid_geometry_choice(
+ widget: Any, choice: str | None
+) -> None:
+ subject = widget(fixtures.arrow_multi_geometry())
+ function = next(
+ function
+ for function in subject._args.functions
+ if function.name == "download_geojson"
+ )
+ with patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish:
+ response = function({"format": "geojson", "geometry_column": choice})
+ assert (response.url, response.filename, response.code) == (
+ "",
+ "",
+ "geometry_required" if choice is None else "invalid_geometry",
+ )
+ publish.assert_not_called()
+
+
[email protected]("geopandas", "pyarrow")
+def test_arrow_geojson_selected_table_rows_only() -> None:
+ subject = ui.table(fixtures.arrow_multi_geometry(), selection="multi")
+ subject._convert_value(["1"])
+ assert _artifact(subject, "geom_a") == {
+ "type": "FeatureCollection",
+ "features": [
+ {
+ "type": "Feature",
+ "geometry": None,
+ "properties": {"name": "null", "geom_b": None},
+ }
+ ],
+ }
+
+
[email protected]("geopandas", "pyarrow")
+def test_arrow_geojson_uses_transformed_dataframe_value() -> None:
+ import pyarrow as pa
+
+ subject = ui.dataframe(fixtures.arrow_multi_geometry())
+ subject._update(
+ {
+ "transforms": [
+ {"type": "select_columns", "column_ids": ["name", "geom_b"]}
+ ]
+ }
+ )
+ assert _artifact(subject) == {
+ "type": "FeatureCollection",
+ "features": [
+ {
+ "type": "Feature",
+ "geometry": {"type": "Point", "coordinates": [20, 5]},
+ "properties": {"name": "projected"},
+ },
+ {
+ "type": "Feature",
+ "geometry": None,
+ "properties": {"name": "null"},
+ },
+ ],
+ }
+ transformed = subject._value
+ assert isinstance(transformed, pa.Table)
+ subject._value = transformed.slice(1, 1)
+ assert len(_artifact(subject)["features"]) == 1
+ response = subject._download_geojson(
+ DownloadGeoJSONArgs(format="geojson", geometry_column="geom_a")
+ )
+ assert (response.url, response.code, response.column) == (
+ "",
+ "invalid_geometry",
+ "geom_a",
+ )
+
+
[email protected]("geopandas", "pyarrow")
[email protected]("encoding", ["wkb", "wkt"])
[email protected]("choice", ["geom_a", "registered"])
+def test_arrow_geojson_registered_primary_and_secondary_geometry(
+ widget: Any, encoding: Literal["wkb", "wkt"], choice: str
+) -> None:
+ import pyarrow as pa
+ from shapely import from_wkt
+
+ name = f"geoarrow.{encoding}"
+ storage_type = pa.binary() if encoding == "wkb" else pa.string()
+
+ class GeometryType(pa.ExtensionType):
+ def __init__(self) -> None:
+ super().__init__(storage_type, name)
+
+ def __arrow_ext_serialize__(self) -> bytes:
+ return b'{"crs":"EPSG:4326"}'
+
+ @classmethod
+ def __arrow_ext_deserialize__(
+ cls, _storage_type: Any, _serialized: bytes
+ ) -> Any:
+ return cls()
+
+ extension = GeometryType()
+ pa.register_extension_type(extension) # type: ignore[arg-type]
+ try:
+ value = fixtures.WKB_POINT_1_2 if encoding == "wkb" else "POINT (1 2)"
+ values = pa.ExtensionArray.from_storage(
+ extension, pa.array([value, None], type=storage_type)
+ )
+ source = fixtures.arrow_multi_geometry().append_column(
+ "registered", values
+ )
+ subject = widget(source)
+ features = _artifact(subject, choice)["features"]
+ assert features[0]["geometry"]["coordinates"] == pytest.approx(
+ [10, 0] if choice == "geom_a" else [1, 2]
+ )
+ secondary = "registered" if choice == "geom_a" else "geom_a"
+ assert next(
+ iter(from_wkt(features[0]["properties"][secondary]).coords)
+ ) == pytest.approx(
+ [1, 2] if choice == "geom_a" else [1113194.9079327357, 0]
+ )
+ assert features[1]["geometry"] is None
+ assert features[1]["properties"][secondary] is None
+ assert source["registered"].to_pylist() == [value, None]
+ finally:
+ pa.unregister_extension_type(name)
+
+
[email protected]("geopandas", "pyarrow")
[email protected]("missing", ["geopandas", "shapely"])
+def test_arrow_geojson_rechecks_dependencies_before_conversion(
+ widget: Any, missing: str
+) -> None:
+ import geopandas as gpd
+
+ subject = widget(fixtures.arrow_wkb_projected())
+ function = next(
+ function
+ for function in subject._args.functions
+ if function.name == "download_geojson"
+ )
+ dependency = (
+ DependencyManager.geopandas
+ if missing == "geopandas"
+ else DependencyManager.shapely
+ )
+ method = "has" if missing == "geopandas" else "has_at_version"
+ with (
+ patch.object(dependency, method, return_value=False),
+ patch.object(gpd.GeoSeries, "from_wkb") as parse,
+ patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish,
+ ):
+ response = function({"format": "geojson"})
+ assert (
+ response.url,
+ response.filename,
+ response.code,
+ response.missing_packages,
+ ) == (
+ "",
+ "",
+ "missing_packages"
+ if missing == "geopandas"
+ else "unsupported_version",
+ ["geopandas"] if missing == "geopandas" else None,
+ )
+ parse.assert_not_called()
+ publish.assert_not_called()
def test_table_selection_search_and_cell_scope() -> None:
diff --git a/tests/_plugins/ui/_impl/test_geoparquet_export.py b/tests/_plugins/ui/_impl/test_geoparquet_export.py
index 540b4c2c0d..fbfbaead20 100644
--- a/tests/_plugins/ui/_impl/test_geoparquet_export.py
+++ b/tests/_plugins/ui/_impl/test_geoparquet_export.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import io
import json
-from typing import Any
+from typing import Any, Literal
from unittest.mock import patch
import pytest
@@ -11,6 +11,10 @@ import pytest
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins import ui
from marimo._plugins.ui._impl.table import DownloadAsArgs
+from marimo._plugins.ui._impl.tables.geometry_export import (
+ ExportFormatEligibility,
+ GeometryExportColumn,
+)
from marimo._runtime.functions import EmptyArgs
from marimo._utils.data_uri import from_data_uri
from tests._plugins.ui._impl.tables import geometry_fixtures as fixtures
@@ -70,8 +74,10 @@ def test_geoparquet_keeps_every_geometry_and_crs(
@pytest.mark.requires("geopandas", "pyarrow")
[email protected]("arrow", [False, True], ids=["pandas", "arrow"])
def test_geoparquet_uses_writer_supported_by_geopandas_0141(
widget: Any,
+ arrow: bool,
) -> None:
import geopandas as gpd
import pyarrow.parquet as pq
@@ -88,7 +94,12 @@ def test_geoparquet_uses_writer_supported_by_geopandas_0141(
original_writer(self, path, index=index, schema_version=schema_version)
with patch.object(gpd.GeoDataFrame, "to_parquet", compatible_writer):
- artifact, _ = _artifact(widget(fixtures.gdf_multi_geometry()))
+ source = (
+ fixtures.arrow_multi_geometry()
+ if arrow
+ else fixtures.gdf_multi_geometry()
+ )
+ artifact, _ = _artifact(widget(source), "geom_a")
geo = json.loads(pq.read_metadata(io.BytesIO(artifact)).metadata[b"geo"])
assert geo["version"] == "1.0.0"
@@ -252,15 +263,648 @@ def test_missing_pyarrow_is_a_structured_failure(widget: Any) -> None:
)
[email protected]("geopandas", "pyarrow")
+ "factory",
+ [
+ fixtures.arrow_wkb_known_crs,
+ fixtures.arrow_wkt,
+ fixtures.arrow_multi_geometry,
+ fixtures.arrow_wkb_projected,
+ fixtures.arrow_invalid_wkb,
+ ],
+)
+def test_declared_arrow_geometry_is_eligible_for_geoparquet(
+ widget: Any, factory: Any
+) -> None:
+ metadata = widget(factory())._get_export_metadata(EmptyArgs())
+ assert metadata.formats["parquet"] == ExportFormatEligibility(
+ available=True
+ )
+
+
[email protected]("geopandas", "pyarrow")
+ ("factory", "reason"),
+ [
+ (fixtures.arrow_malformed_metadata, "invalid GeoArrow metadata"),
+ (fixtures.arrow_spherical_edges, "edges"),
+ (fixtures.arrow_other_geoarrow, "native GeoArrow layout"),
+ ],
+)
+def test_arrow_declaration_blocks_both_geographic_formats(
+ widget: Any, factory: Any, reason: str
+) -> None:
+ metadata = widget(factory())._get_export_metadata(EmptyArgs())
+ for format_name in ("parquet", "geojson"):
+ eligibility = metadata.formats[format_name]
+ assert not eligibility.available
+ assert eligibility.reason is not None
+ assert reason in eligibility.reason
+ assert eligibility.missing_packages == []
+
+
[email protected]("geopandas", "pyarrow")
+ ("raw", "reason"),
+ [
+ (b"not json", "expected a UTF-8 JSON object"),
+ (b"\xff", "expected a UTF-8 JSON object"),
+ (b"null", "expected a JSON object"),
+ (b'{"crs":null}', "crs must be a string or PROJJSON object"),
+ (b'{"crs":4326}', "crs must be a string or PROJJSON object"),
+ (b'{"crs":[]}', "crs must be a string or PROJJSON object"),
+ (b'{"crs":"not a CRS"}', "crs cannot be resolved"),
+ (b'{"crs":{}}', "crs cannot be resolved"),
+ (b'{"crs_type":"unknown"}', "unknown crs_type"),
+ (b'{"crs_type":[]}', "unknown crs_type"),
+ (b'{"crs_type":null}', "unknown crs_type"),
+ (b'{"edges":"planar"}', "unknown edges interpretation"),
+ (b'{"edges":null}', "unknown edges interpretation"),
+ (b'{"edges":{}}', "unknown edges interpretation"),
+ ],
+)
+def test_invalid_arrow_metadata_reports_a_reason(
+ widget: Any, raw: bytes, reason: str
+) -> None:
+ source = fixtures.arrow_wkb_known_crs()
+ field = source.schema.field("geom").with_metadata(
+ {
+ b"ARROW:extension:name": b"geoarrow.wkb",
+ b"ARROW:extension:metadata": raw,
+ }
+ )
+ source = source.cast(source.schema.set(1, field))
+ metadata = widget(source)._get_export_metadata(EmptyArgs())
+ expected = ExportFormatEligibility(
+ available=False,
+ reason=f"Geometry column 'geom' has invalid GeoArrow metadata: {reason}.",
+ )
+ assert metadata.formats == {"parquet": expected, "geojson": expected}
+
+
[email protected]("geopandas", "pyarrow")
+ "edges", ["spherical", "vincenty", "thomas", "andoyer", "karney"]
+)
+def test_arrow_secondary_edges_block_both_formats(
+ widget: Any, edges: str
+) -> None:
+ source = fixtures.arrow_multi_geometry()
+ field = source.schema.field("geom_b").with_metadata(
+ {
+ b"ARROW:extension:name": b"geoarrow.wkt",
+ b"ARROW:extension:metadata": json.dumps(
+ {"crs": "EPSG:4326", "edges": edges}
+ ).encode(),
+ }
+ )
+ source = source.cast(source.schema.set(2, field))
+ metadata = widget(source)._get_export_metadata(EmptyArgs())
+ expected = ExportFormatEligibility(
+ available=False,
+ reason=f"Geometry column 'geom_b' declares {edges!r} edges, "
+ "which geographic exports cannot preserve.",
+ )
+ assert metadata.formats == {"parquet": expected, "geojson": expected}
+
+
[email protected]("geopandas", "pyarrow")
+def test_arrow_secondary_native_geometry_blocks_both_formats(
+ widget: Any,
+) -> None:
+ source = fixtures.arrow_wkb_known_crs()
+ other = fixtures.arrow_other_geoarrow()
+ source = source.append_column(
+ other.schema.field("geom").with_name("native"), other["geom"]
+ )
+ metadata = widget(source)._get_export_metadata(EmptyArgs())
+ expected = ExportFormatEligibility(
+ available=False,
+ reason="Geometry column 'native' uses a native GeoArrow layout. "
+ "Geographic exports require WKB or WKT.",
+ )
+ assert metadata.formats == {"parquet": expected, "geojson": expected}
+
+
[email protected]("geopandas", "pyarrow")
+ "factory", [fixtures.arrow_wkb_missing_crs, fixtures.arrow_srid_crs]
+)
+def test_arrow_unknown_crs_stays_unknown(widget: Any, factory: Any) -> None:
+ metadata = widget(factory())._get_export_metadata(EmptyArgs())
+ assert metadata.geometry_columns == [
+ GeometryExportColumn(name="geom", encoding="wkb", crs=None)
+ ]
+ assert metadata.primary_geometry_column is None
+ assert metadata.default_geometry_column == "geom"
+ assert metadata.formats["parquet"] == ExportFormatEligibility(
+ available=True
+ )
+
+
[email protected]("geopandas", "pyarrow")
+def test_arrow_metadata_keeps_separate_crs_without_parsing_values(
+ widget: Any,
+) -> None:
+ import geopandas as gpd
+ import narwhals.stable.v2 as nw
+ from pyproj import CRS
+
+ subject = widget(fixtures.arrow_multi_geometry())
+ with (
+ patch.object(
+ nw.DataFrame,
+ "to_pandas",
+ side_effect=AssertionError("materialized rows"),
+ ),
+ patch.object(
+ nw.DataFrame,
+ "to_dict",
+ side_effect=AssertionError("materialized rows"),
+ ),
+ patch.object(
+ gpd.GeoSeries,
+ "from_wkb",
+ side_effect=AssertionError("materialized WKB"),
+ ),
+ patch.object(
+ gpd.GeoSeries,
+ "from_wkt",
+ side_effect=AssertionError("materialized WKT"),
+ ),
+ ):
+ metadata = subject._get_export_metadata(EmptyArgs())
+ assert metadata.geometry_columns == [
+ GeometryExportColumn(name="geom_a", encoding="wkb", crs="EPSG:3857"),
+ GeometryExportColumn(
+ name="geom_b",
+ encoding="wkt",
+ crs=CRS.from_epsg(4326).to_json_dict(),
+ ),
+ ]
+ assert metadata.primary_geometry_column is None
+ assert metadata.default_geometry_column is None
+
+
[email protected]("geopandas", "pyarrow")
+ "crs_type", [None, "projjson", "wkt2:2019", "authority_code"]
+)
+def test_arrow_crs_representations_are_eligible(
+ widget: Any, crs_type: str | None
+) -> None:
+ from pyproj import CRS
+
+ crs = CRS.from_epsg(4326)
+ value = (
+ crs.to_json_dict()
+ if crs_type == "projjson"
+ else crs.to_wkt(version="WKT2_2019")
+ if crs_type == "wkt2:2019"
+ else "EPSG:4326"
+ )
+ declaration = {"crs": value}
+ if crs_type is not None:
+ declaration["crs_type"] = crs_type
+ source = fixtures.arrow_wkb_known_crs()
+ field = source.schema.field("geom").with_metadata(
+ {
+ b"ARROW:extension:name": b"geoarrow.wkb",
+ b"ARROW:extension:metadata": json.dumps(declaration).encode(),
+ }
+ )
+ metadata = widget(
+ source.cast(source.schema.set(1, field))
+ )._get_export_metadata(EmptyArgs())
+ assert metadata.geometry_columns == [
+ GeometryExportColumn(name="geom", encoding="wkb", crs=value)
+ ]
+ assert metadata.formats == {
+ name: ExportFormatEligibility(available=True)
+ for name in ("parquet", "geojson")
+ }
+
+
@pytest.mark.requires("pyarrow")
-def test_declared_arrow_geometry_is_not_labeled_geoparquet(
+def test_arrow_missing_geopandas_reports_required_package(widget: Any) -> None:
+ subject = widget(fixtures.arrow_wkb_known_crs())
+ with patch.object(DependencyManager.geopandas, "has", return_value=False):
+ metadata = subject._get_export_metadata(EmptyArgs())
+ assert metadata.formats == {
+ name: ExportFormatEligibility(
+ available=False,
+ reason=f"This Arrow table needs geopandas to export {label}.",
+ missing_packages=["geopandas"],
+ )
+ for name, label in (("parquet", "GeoParquet"), ("geojson", "GeoJSON"))
+ }
+
+
[email protected]("geopandas", "pyarrow")
+def test_arrow_geoparquet_checks_writer_version(
widget: Any,
) -> None:
- response = widget(fixtures.arrow_wkb_known_crs())._download_as(
- DownloadAsArgs(format="parquet")
+ subject = widget(fixtures.arrow_wkb_known_crs())
+ with patch.object(
+ DependencyManager.geopandas, "get_version", return_value="0.14.0"
+ ):
+ metadata = subject._get_export_metadata(EmptyArgs())
+ assert metadata.formats["parquet"] == ExportFormatEligibility(
+ available=False,
+ reason="Update geopandas to 0.14.1 or newer to export GeoParquet.",
+ )
+
+
[email protected]("geopandas", "pyarrow")
+def test_arrow_geoparquet_checks_pyarrow_dependency(widget: Any) -> None:
+ subject = widget(fixtures.arrow_wkb_known_crs())
+ with patch.object(DependencyManager.pyarrow, "has", return_value=False):
+ metadata = subject._get_export_metadata(EmptyArgs())
+ assert metadata.formats["parquet"] == ExportFormatEligibility(
+ available=False,
+ reason="GeoParquet export requires pyarrow.",
+ missing_packages=["pyarrow"],
+ )
+
+
[email protected]("geopandas", "pyarrow")
[email protected]("choice", ["geom_a", "geom_b"])
+def test_arrow_geoparquet_keeps_geometry_crs_and_source(
+ widget: Any, choice: str
+) -> None:
+ import geopandas as gpd
+ import pyarrow as pa
+ import pyarrow.parquet as pq
+ from pyproj import CRS
+ from shapely import from_wkt
+
+ source = fixtures.arrow_multi_geometry()
+ source = source.append_column(
+ "count", pa.array([2**63 + 1, None], type=pa.uint64())
)
- assert response.code == "unsupported_representation"
- assert response.url == ""
+ before = pa.BufferOutputStream()
+ with pa.ipc.new_stream(before, source.schema) as writer:
+ writer.write_table(source)
+ original_bytes = before.getvalue().to_pybytes()
+
+ artifact, filename = _artifact(widget(source), choice)
+ reader = pq.ParquetFile(io.BytesIO(artifact))
+ file_metadata = reader.metadata.metadata
+ assert file_metadata is not None
+ geo = json.loads(file_metadata[b"geo"])
+ restored = reader.read()
+ assert filename.endswith(".parquet")
+ assert geo["version"] == "1.0.0"
+ assert geo["primary_column"] == choice
+ assert set(geo["columns"]) == {"geom_a", "geom_b"}
+ for name, crs in (("geom_a", 3857), ("geom_b", 4326)):
+ assert geo["columns"][name]["encoding"] == "WKB"
+ assert CRS.from_json_dict(
+ geo["columns"][name]["crs"]
+ ) == CRS.from_epsg(crs)
+ assert restored.column_names == source.column_names
+ assert restored.to_pylist() == [
+ {
+ "name": "projected",
+ "geom_a": source["geom_a"][0].as_py(),
+ "geom_b": from_wkt("POINT (20 5)").wkb,
+ "count": 2**63 + 1,
+ },
+ {"name": "null", "geom_a": None, "geom_b": None, "count": None},
+ ]
+ frame = gpd.read_parquet(io.BytesIO(artifact))
+ assert frame.geometry.name == choice
+ assert frame["geom_a"].crs == CRS.from_epsg(3857)
+ assert frame["geom_b"].crs == CRS.from_epsg(4326)
+ after = pa.BufferOutputStream()
+ with pa.ipc.new_stream(after, source.schema) as writer:
+ writer.write_table(source)
+ assert after.getvalue().to_pybytes() == original_bytes
+
+
[email protected]("geopandas", "pyarrow")
+ "factory",
+ [
+ fixtures.arrow_wkb_known_crs,
+ fixtures.arrow_wkt,
+ fixtures.arrow_wkb_projected,
+ ],
+)
+def test_arrow_geoparquet_sole_geometry_is_default(
+ widget: Any, factory: Any
+) -> None:
+ import geopandas as gpd
+ import pyarrow.parquet as pq
+
+ source = factory()
+ subject = widget(source)
+ metadata = subject._get_export_metadata(EmptyArgs())
+ artifact, _ = _artifact(subject)
+ file_metadata = pq.read_metadata(io.BytesIO(artifact)).metadata
+ assert file_metadata is not None
+ geo = json.loads(file_metadata[b"geo"])
+ frame = gpd.read_parquet(io.BytesIO(artifact))
+ assert geo["primary_column"] == metadata.default_geometry_column
+ assert frame.geometry.name == metadata.default_geometry_column
+ assert len(frame) == source.num_rows
+
+
[email protected]("geopandas", "pyarrow")
[email protected]("empty", [False, True])
[email protected]("geometry_only", [False, True])
+ "factory", [fixtures.arrow_wkb_missing_crs, fixtures.arrow_srid_crs]
+)
+def test_arrow_geoparquet_unknown_crs_is_explicit(
+ widget: Any, factory: Any, empty: bool, geometry_only: bool
+) -> None:
+ import geopandas as gpd
+ import pyarrow.parquet as pq
+
+ source = factory()
+ if geometry_only:
+ source = source.select(["geom"])
+ if empty:
+ source = source.slice(0, 0)
+ artifact, _ = _artifact(widget(source))
+ reader = pq.ParquetFile(io.BytesIO(artifact))
+ file_metadata = reader.metadata.metadata
+ assert file_metadata is not None
+ geo = json.loads(file_metadata[b"geo"])
+ frame = gpd.read_parquet(io.BytesIO(artifact))
+ assert geo["columns"]["geom"]["crs"] is None
+ assert frame.crs is None
+ assert reader.read()["geom"].to_pylist() == source["geom"].to_pylist()
+ assert reader.metadata.num_rows == source.num_rows
+ assert len(frame) == source.num_rows
+
+
[email protected]("geopandas", "pyarrow")
+ ("factory", "code", "column"),
+ [
+ (fixtures.arrow_malformed_metadata, "invalid_metadata", "geom"),
+ (fixtures.arrow_spherical_edges, "unsupported_representation", "geom"),
+ (fixtures.arrow_other_geoarrow, "unsupported_representation", "geom"),
+ ],
+)
+def test_arrow_geoparquet_metadata_rejects_before_conversion(
+ widget: Any, factory: Any, code: str, column: str
+) -> None:
+ import geopandas as gpd
+
+ subject = widget(factory())
+ with (
+ patch.object(gpd.GeoSeries, "from_wkb") as parse_wkb,
+ patch.object(gpd.GeoSeries, "from_wkt") as parse_wkt,
+ patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish,
+ ):
+ response = subject._download_as(DownloadAsArgs(format="parquet"))
+ assert (
+ response.url,
+ response.filename,
+ response.code,
+ response.column,
+ ) == (
+ "",
+ "",
+ code,
+ column,
+ )
+ parse_wkb.assert_not_called()
+ parse_wkt.assert_not_called()
+ publish.assert_not_called()
+
+
[email protected]("geopandas", "pyarrow")
+ ("raw", "code"),
+ [
+ (b"[]", "invalid_metadata"),
+ (b'{"edges":"spherical"}', "unsupported_representation"),
+ ],
+)
+def test_arrow_geoparquet_rejects_secondary_metadata_atomically(
+ widget: Any, raw: bytes, code: str
+) -> None:
+ import geopandas as gpd
+
+ source = fixtures.arrow_multi_geometry()
+ field = source.schema.field("geom_b").with_metadata(
+ {
+ b"ARROW:extension:name": b"geoarrow.wkt",
+ b"ARROW:extension:metadata": raw,
+ }
+ )
+ subject = widget(source.cast(source.schema.set(2, field)))
+ with (
+ patch.object(gpd.GeoSeries, "from_wkb") as parse,
+ patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish,
+ ):
+ response = subject._download_as(
+ DownloadAsArgs(format="parquet", geometry_column="geom_a")
+ )
+ assert (
+ response.url,
+ response.filename,
+ response.code,
+ response.column,
+ ) == ("", "", code, "geom_b")
+ parse.assert_not_called()
+ publish.assert_not_called()
+
+
[email protected]("geopandas", "pyarrow")
[email protected]("encoding", ["wkb", "wkt"])
+def test_arrow_geoparquet_rejects_secondary_m_geometry(
+ widget: Any, encoding: str
+) -> None:
+ import pyarrow as pa
+ from shapely import from_wkt
+
+ measured = from_wkt("POINT M (1 2 3)")
+ if not getattr(measured, "has_m", False):
+ pytest.skip("Installed Shapely cannot represent M coordinates")
+ source = fixtures.arrow_multi_geometry()
+ field = pa.field(
+ "measured",
+ pa.binary() if encoding == "wkb" else pa.string(),
+ metadata={b"ARROW:extension:name": f"geoarrow.{encoding}".encode()},
+ )
+ value = measured.wkb if encoding == "wkb" else "POINT M (1 2 3)"
+ source = source.append_column(
+ field, pa.array([value, None], type=field.type)
+ )
+ subject = widget(source)
+ with patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish:
+ response = subject._download_as(
+ DownloadAsArgs(format="parquet", geometry_column="geom_a")
+ )
+ assert (
+ response.url,
+ response.filename,
+ response.code,
+ response.column,
+ ) == ("", "", "unsupported_representation", "measured")
+ publish.assert_not_called()
+
+
[email protected]("geopandas", "pyarrow")
[email protected]("encoding", ["wkb", "wkt"])
+def test_arrow_geoparquet_invalid_geometry_publishes_no_artifact(
+ widget: Any, encoding: str
+) -> None:
+ import pyarrow as pa
+
+ source = fixtures.arrow_invalid_wkb()
+ if encoding == "wkt":
+ source = fixtures.arrow_wkt()
+ source = source.set_column(
+ 1, source.schema.field("geom"), pa.array(["invalid", None, None])
+ )
+ subject = widget(source)
+ with patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish:
+ response = subject._download_as(DownloadAsArgs(format="parquet"))
+ assert (response.url, response.filename, response.code) == (
+ "",
+ "",
+ "conversion_failed",
+ )
+ publish.assert_not_called()
+
+
[email protected]("geopandas", "pyarrow")
+def test_arrow_geoparquet_ambiguous_geometry_requires_choice(
+ widget: Any,
+) -> None:
+ subject = widget(fixtures.arrow_multi_geometry())
+ response = subject._download_as(DownloadAsArgs(format="parquet"))
+ assert (response.url, response.filename, response.code) == (
+ "",
+ "",
+ "geometry_required",
+ )
+
+
[email protected]("geopandas", "pyarrow")
+def test_arrow_geoparquet_exports_only_selected_rows() -> None:
+ import pyarrow.parquet as pq
+
+ source = fixtures.arrow_multi_geometry()
+ subject = ui.table(source, selection="multi")
+ subject._convert_value(["1"])
+ artifact, _ = _artifact(subject, "geom_b")
+ restored = pq.read_table(io.BytesIO(artifact))
+ assert restored.to_pylist() == [
+ {"name": "null", "geom_a": None, "geom_b": None}
+ ]
+
+
[email protected]("geopandas", "pyarrow")
[email protected]("encoding", ["wkb", "wkt"])
+def test_arrow_geoparquet_registered_extension_storage(
+ widget: Any, encoding: Literal["wkb", "wkt"]
+) -> None:
+ import geopandas as gpd
+ import pyarrow as pa
+ import pyarrow.parquet as pq
+
+ name = f"geoarrow.{encoding}"
+ storage_type = pa.binary() if encoding == "wkb" else pa.string()
+
+ class GeometryType(pa.ExtensionType):
+ def __init__(self) -> None:
+ super().__init__(storage_type, name)
+
+ def __arrow_ext_serialize__(self) -> bytes:
+ return b'{"crs":"EPSG:4326"}'
+
+ @classmethod
+ def __arrow_ext_deserialize__(
+ cls, _storage_type: Any, _serialized: bytes
+ ) -> Any:
+ return cls()
+
+ extension = GeometryType()
+ pa.register_extension_type(extension) # type: ignore[arg-type]
+ try:
+ value = fixtures.WKB_POINT_1_2 if encoding == "wkb" else "POINT (1 2)"
+ chunks = [
+ pa.ExtensionArray.from_storage(
+ extension, pa.array([value], type=storage_type)
+ ),
+ pa.ExtensionArray.from_storage(
+ extension, pa.array([None], type=storage_type)
+ ),
+ ]
+ source = pa.Table.from_arrays(
+ [pa.array(["point", "null"]), pa.chunked_array(chunks)],
+ names=["name", "geom"],
+ )
+ subject = widget(source)
+ metadata = subject._get_export_metadata(EmptyArgs())
+ assert metadata.geometry_columns == [
+ GeometryExportColumn("geom", encoding, "EPSG:4326")
+ ]
+ artifact, _ = _artifact(subject)
+ assert pq.read_table(io.BytesIO(artifact))["geom"].to_pylist() == [
+ fixtures.WKB_POINT_1_2,
+ None,
+ ]
+ frame = gpd.read_parquet(io.BytesIO(artifact))
+ assert frame.geometry.name == "geom"
+ assert frame.crs.to_epsg() == 4326
+ assert source["geom"].num_chunks == 2
+ assert source["geom"].to_pylist() == [value, None]
+ finally:
+ pa.unregister_extension_type(name)
+
+
[email protected]("geopandas", "pyarrow")
[email protected]("missing", ["geopandas", "pyarrow", "version"])
+def test_arrow_geoparquet_rechecks_dependencies_before_conversion(
+ widget: Any, missing: str
+) -> None:
+ import geopandas as gpd
+
+ subject = widget(fixtures.arrow_wkb_known_crs())
+ dependency = (
+ DependencyManager.pyarrow
+ if missing == "pyarrow"
+ else DependencyManager.geopandas
+ )
+ method = "has_at_version" if missing == "version" else "has"
+ with (
+ patch.object(dependency, method, return_value=False),
+ patch.object(gpd.GeoSeries, "from_wkb") as parse,
+ patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish,
+ ):
+ response = subject._download_as(DownloadAsArgs(format="parquet"))
+ assert (
+ response.url,
+ response.filename,
+ response.code,
+ response.missing_packages,
+ ) == (
+ "",
+ "",
+ "unsupported_version" if missing == "version" else "missing_packages",
+ None if missing == "version" else [missing],
+ )
+ parse.assert_not_called()
+ publish.assert_not_called()
@pytest.mark.requires("geopandas", "pyarrow")
@@ -399,3 +1043,170 @@ def test_ordinary_parquet_bytes_remain_unchanged() -> None:
).to_parquet()
artifact, _ = _artifact(subject)
assert artifact == expected
+
+
[email protected]("geopandas", "pyarrow")
+ "raw",
+ [
+ '{"crs":"EPSG:4326"}'.encode("utf-16"),
+ '{"crs":"EPSG:4326"}'.encode("utf-32"),
+ b'{"extra":{"value":NaN}}',
+ b'{"extra":{"value":Infinity}}',
+ b'{"extra":{"value":-Infinity}}',
+ b'{"crs":"EPSG:4326","crs_type":"projjson"}',
+ b'{"crs":{},"crs_type":"srid"}',
+ b'{"crs":{},"crs_type":"authority_code"}',
+ b'{"crs":{},"crs_type":"wkt2:2019"}',
+ b'{"crs":"EPSG:4326","crs_type":"wkt2:2019"}',
+ b'{"crs":"+proj=longlat +datum=WGS84","crs_type":"authority_code"}',
+ ],
+)
+def test_arrow_invalid_serialized_declarations_publish_no_artifact(
+ widget: Any, raw: bytes
+) -> None:
+ from marimo._plugins.ui._impl.table import DownloadGeoJSONArgs
+
+ source = fixtures.arrow_wkb_known_crs()
+ field = source.schema.field("geom").with_metadata(
+ {
+ b"ARROW:extension:name": b"geoarrow.wkb",
+ b"ARROW:extension:metadata": raw,
+ }
+ )
+ subject = widget(source.cast(source.schema.set(1, field)))
+ metadata = subject._get_export_metadata(EmptyArgs())
+ assert all(not value.available for value in metadata.formats.values())
+ with patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish:
+ parquet = subject._download_as(DownloadAsArgs(format="parquet"))
+ geojson = subject._download_geojson(
+ DownloadGeoJSONArgs(format="geojson")
+ )
+ assert [(r.code, r.url, r.filename) for r in (parquet, geojson)] == [
+ ("invalid_metadata", "", ""),
+ ("invalid_metadata", "", ""),
+ ]
+ publish.assert_not_called()
+
+
[email protected]("geopandas", "pyarrow")
[email protected]("payload", [b"", b"not json"])
+def test_registered_ogc_wkb_metadata(widget: Any, payload: bytes) -> None:
+ import pyarrow as pa
+ import pyarrow.parquet as pq
+
+ from marimo._plugins.ui._impl.table import DownloadGeoJSONArgs
+
+ class OGCType(pa.ExtensionType):
+ def __init__(self) -> None:
+ super().__init__(pa.binary(), "ogc.wkb")
+
+ def __arrow_ext_serialize__(self) -> bytes:
+ return payload
+
+ @classmethod
+ def __arrow_ext_deserialize__(
+ cls, _storage: Any, _serialized: bytes
+ ) -> Any:
+ return cls()
+
+ extension = OGCType()
+ pa.register_extension_type(extension) # type: ignore[arg-type]
+ try:
+ values = pa.ExtensionArray.from_storage(
+ extension,
+ pa.array([fixtures.WKB_POINT_1_2, None], type=pa.binary()),
+ )
+ source = pa.Table.from_arrays([values], names=["geom"])
+ subject = widget(source)
+ if payload:
+ response = subject._download_as(DownloadAsArgs(format="parquet"))
+ assert (response.code, response.url) == ("invalid_metadata", "")
+ else:
+ artifact, _ = _artifact(subject)
+ file_metadata = pq.read_metadata(io.BytesIO(artifact)).metadata
+ assert file_metadata is not None
+ metadata = json.loads(file_metadata[b"geo"])
+ assert metadata["columns"]["geom"]["crs"] is None
+ assert pq.read_table(io.BytesIO(artifact))["geom"].to_pylist() == [
+ fixtures.WKB_POINT_1_2,
+ None,
+ ]
+ response = subject._download_geojson(
+ DownloadGeoJSONArgs(format="geojson")
+ )
+ assert (response.code, response.url) == ("missing_crs", "")
+ assert source["geom"].to_pylist() == [fixtures.WKB_POINT_1_2, None]
+ finally:
+ pa.unregister_extension_type("ogc.wkb")
+
+
[email protected]("geopandas", "pyarrow")
+def test_arrow_geometry_named_geometry_has_no_future_warning(
+ widget: Any,
+) -> None:
+ import warnings
+
+ source = fixtures.arrow_wkb_known_crs().rename_columns(
+ ["name", "geometry"]
+ )
+ with warnings.catch_warnings():
+ warnings.simplefilter("error", FutureWarning)
+ _artifact(widget(source))
+
+
[email protected]("geopandas", "pyarrow")
+def test_arrow_first_rejection_matches_conversion(widget: Any) -> None:
+ from marimo._plugins.ui._impl.tables.geometry_export import (
+ GeometryExportError,
+ _arrow_to_geodataframe,
+ )
+
+ source = fixtures.arrow_multi_geometry()
+ for index, raw in [(1, b'{"edges":"spherical"}'), (2, b"[]")]:
+ field = source.schema.field(index)
+ field_metadata: dict[bytes | str, bytes | str] = {
+ key: value for key, value in (field.metadata or {}).items()
+ }
+ field_metadata[b"ARROW:extension:metadata"] = raw
+ source = source.cast(
+ source.schema.set(index, field.with_metadata(field_metadata))
+ )
+ metadata = widget(source)._get_export_metadata(EmptyArgs())
+ reason = "Geometry column 'geom_a' declares 'spherical' edges, which geographic exports cannot preserve."
+ assert metadata.formats["parquet"].reason == reason
+ with pytest.raises(GeometryExportError) as error:
+ _arrow_to_geodataframe(source, metadata.geometry_columns)
+ assert (error.value.code, str(error.value), error.value.column) == (
+ "unsupported_representation",
+ reason,
+ "geom_a",
+ )
+
+
[email protected]("geopandas")
+def test_pandas_duplicate_columns_precede_dependency_errors() -> None:
+ from marimo._plugins.ui._impl.tables.geometry_export import (
+ GeometryExportError,
+ serialize_geoparquet,
+ )
+ from marimo._plugins.ui._impl.tables.utils import get_table_manager
+
+ source = fixtures.gdf_multi_geometry()
+ manager = get_table_manager(source)
+ source.columns = ["geom_a", "geom_a"]
+ with (
+ patch(
+ "marimo._plugins.ui._impl.tables.geometry_export.has_geometry_columns",
+ return_value=True,
+ ),
+ patch.object(DependencyManager.geopandas, "has", return_value=False),
+ pytest.raises(GeometryExportError) as error,
+ ):
+ serialize_geoparquet(manager, "geom_b")
+ assert (error.value.code, str(error.value)) == (
+ "invalid_metadata",
+ "GeoParquet export requires unique column names.",
+ )