Skip to content

Backends — geocatalog.backends

The catalog implementations behind the GeoCatalog protocol, the row they yield, and the errors they raise. geocatalog.open_catalog picks a backend for you.

In memory

geocatalog.backends.InMemoryGeoCatalog

A geopandas.GeoDataFrame-backed catalog.

Parameters:

Name Type Description Default
gdf GeoDataFrame

The catalog rows. Required columns: geometry (footprint polygons in crs) and either a row-level pd.IntervalIndex (preferred — set the index via gdf.set_index(IntervalIndex)) or start_time + end_time columns that this constructor will promote to the index. The geometry column's CRS is authoritative; gdf.crs must be set.

required
kind CatalogKind

"raster" / "xarray" / "vector" — the kind of data the catalog indexes. Drives the dispatching choice in geocatalog.load_*. (backend is the deprecated name.)

required
Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/memory.py
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
class InMemoryGeoCatalog:
    """A `geopandas.GeoDataFrame`-backed catalog.

    Args:
        gdf: The catalog rows. Required columns: ``geometry`` (footprint
            polygons in ``crs``) and either a row-level ``pd.IntervalIndex``
            (preferred — set the index via ``gdf.set_index(IntervalIndex)``)
            or ``start_time`` + ``end_time`` columns that this constructor
            will promote to the index. The ``geometry`` column's CRS is
            authoritative; ``gdf.crs`` must be set.
        kind: ``"raster"`` / ``"xarray"`` / ``"vector"`` — the kind of
            data the catalog indexes. Drives the dispatching choice in
            `geocatalog.load_*`. (``backend`` is the deprecated name.)
    """

    kind: CatalogKind
    backend = deprecated_alias("kind")

    @renamed_kwargs(backend="kind")
    def __init__(
        self,
        gdf: gpd.GeoDataFrame,
        *,
        kind: CatalogKind,
    ) -> None:
        if gdf.crs is None:
            raise ValueError("InMemoryGeoCatalog requires gdf.crs to be set; got None.")
        # Stored time contract: naive UTC (see `_timeutil`). Convert any
        # tz-aware / mixed time columns before they become the index so
        # naive and aware inputs never meet in a comparison.
        time_cols = {
            c: naive_utc_datetimes(gdf[c])
            for c in ("start_time", "end_time")
            if c in gdf.columns
        }
        if any(time_cols[c] is not gdf[c] for c in time_cols):
            gdf = gdf.assign(**time_cols)
        if not isinstance(gdf.index, pd.IntervalIndex):
            if "start_time" in gdf.columns and "end_time" in gdf.columns:
                idx = pd.IntervalIndex.from_arrays(
                    gdf["start_time"], gdf["end_time"], closed="both", name="datetime"
                )
                gdf = gdf.set_index(idx)
            else:
                raise ValueError(
                    "InMemoryGeoCatalog needs either an IntervalIndex row "
                    "index or 'start_time'+'end_time' columns; got "
                    f"index={type(gdf.index).__name__}, "
                    f"columns={list(gdf.columns)}."
                )
        normalized_index = naive_utc_interval_index(gdf.index)
        if normalized_index is not gdf.index:
            gdf = gdf.set_axis(normalized_index, axis=0)
        if gdf.index.closed != "both":
            # query() uses IntervalIndex.overlaps, whose endpoint semantics
            # follow ``closed``; GeoSlice intervals are always closed='both'.
            raise ValueError(
                "InMemoryGeoCatalog requires a closed='both' IntervalIndex; "
                f"got closed={gdf.index.closed!r}."
            )
        check_kind(kind, "InMemoryGeoCatalog")
        self.gdf = gdf
        self.kind = kind

    @property
    def crs(self) -> pyproj.CRS:
        """The catalog CRS (``gdf.crs``) as a ``pyproj.CRS``."""
        return pyproj.CRS.from_user_input(self.gdf.crs)

    @cached_property
    def total_bounds(self) -> tuple[float, float, float, float]:
        """Union bbox over all rows.

        Returns:
            ``(xmin, ymin, xmax, ymax)`` in catalog-CRS units, or four
            NaNs if the catalog is empty.
        """
        if len(self.gdf) == 0:
            return (np.nan, np.nan, np.nan, np.nan)
        return tuple(self.gdf.total_bounds.tolist())  # type: ignore[return-value]

    @cached_property
    def temporal_extent(self) -> pd.Interval | None:
        """Tightest interval spanning every row's time window.

        Returns:
            ``pd.Interval(min(start_times), max(end_times),
            closed='both')``, or ``None`` for an empty catalog
            (``pd.Interval`` cannot hold ``NaT`` endpoints).
        """
        if len(self.gdf) == 0:
            return None
        return pd.Interval(
            self.gdf.index.left.min(),
            self.gdf.index.right.max(),
            closed="both",
        )

    def __len__(self) -> int:
        """Number of rows in the catalog."""
        return len(self.gdf)

    def __repr__(self) -> str:
        return (
            f"InMemoryGeoCatalog(kind={self.kind!r}, "
            f"len={len(self)}, crs={self.gdf.crs!r})"
        )

    def query(
        self,
        slice_: GeoSlice | None = None,
        *,
        bounds: tuple[float, float, float, float] | None = None,
        crs: Any | None = None,
        time: tuple[Any, Any] | pd.Interval | None = None,
    ) -> InMemoryGeoCatalog:
        """Spatial + temporal filter on the catalog.

        Either pass a `GeoSlice` (carries bounds/time/crs together) or
        pass the parts. Bounds in a non-catalog CRS are reprojected
        internally — the canonical anti-footgun path (§10.1 of the
        design plan).
        """
        if slice_ is not None and (
            bounds is not None or time is not None or crs is not None
        ):
            raise TypeError(
                "query: pass either slice_ or (bounds + crs + time), not both; "
                "a GeoSlice carries its own crs"
            )
        if slice_ is not None:
            q_bounds = slice_.bounds
            q_crs = slice_.crs
            q_interval = slice_.interval
        else:
            if bounds is None and time is None:
                # No filter — return a copy view.
                return InMemoryGeoCatalog(self.gdf.copy(), kind=self.kind)
            q_bounds = bounds
            q_crs = crs
            q_interval = _coerce_interval(time) if time is not None else None

        out = self.gdf
        if q_interval is not None:
            out = out[out.index.overlaps(q_interval)]
        if q_bounds is not None:
            envelopes = _query_envelopes(q_bounds, q_crs, self.gdf.crs)
            if len(envelopes) == 1:
                xmin, ymin, xmax, ymax = envelopes[0]
                out = out.cx[xmin:xmax, ymin:ymax]
            else:
                # Antimeridian split: same predicate as `.cx` (geometry
                # intersects the box), OR-ed over both halves.
                out = out[
                    out.intersects(
                        shapely.MultiPolygon([shapely.box(*env) for env in envelopes])
                    )
                ]
        return InMemoryGeoCatalog(out, kind=self.kind)

    @renamed_kwargs(engine="join")
    def intersect(
        self,
        other: InMemoryGeoCatalog,
        *,
        spatial_only: bool = False,
        join: _JOIN_T = "sjoin",
    ) -> InMemoryGeoCatalog:
        """Cross-catalog AND — rows whose footprints and times overlap.

        Args:
            other: Another catalog, possibly of another kind. The
                returned catalog has ``self``'s `kind` (it indexes the
                same kind of file as ``self``).
            spatial_only: If True, ignore the temporal axis — useful for
                pairing imagery with static labels.
            join: Spatial-join method. ``"sjoin"`` uses the GeoPandas
                spatial index, while ``"overlay"`` preserves the legacy
                overlay implementation. (``engine=`` is the deprecated
                spelling; "engine" means the storage engine elsewhere.)
        """
        if other.gdf.crs != self.gdf.crs:
            right_gdf = other.gdf.to_crs(self.gdf.crs)
        else:
            right_gdf = other.gdf

        right_renamed = right_gdf.rename(
            columns={c: f"_right_{c}" for c in right_gdf.columns if c != "geometry"}
        )
        left = self.gdf.reset_index(names="_left_interval")
        right = right_renamed.reset_index(names="_right_interval")
        if join == "overlay":
            joined = gpd.overlay(left, right, how="intersection", keep_geom_type=True)
        elif join == "sjoin":
            joined = gpd.sjoin(left, right, how="inner", predicate="intersects")
            if not joined.empty:
                left_geometry = joined.geometry.reset_index(drop=True)
                right_geometry = right.geometry.iloc[joined["index_right"]].reset_index(
                    drop=True
                )
                # Mirror gpd.overlay's default ``make_valid=True``: GEOS will
                # raise on self-intersecting inputs to ``shapely.intersection``.
                # Pay the repair cost only on rows actually flagged invalid.
                left_array = _repair_invalid(left_geometry.to_numpy())
                right_array = _repair_invalid(right_geometry.to_numpy())
                clipped = gpd.GeoSeries(
                    _extract_same_family(
                        _symmetric_intersection(left_array, right_array),
                        left_geometry.to_numpy(),
                    ),
                    index=joined.index,
                    crs=self.gdf.crs,
                )
                keep_geom_mask = _keep_geom_type_mask(joined.geometry, clipped)
                joined = joined.loc[keep_geom_mask].copy()
                clipped = clipped.loc[keep_geom_mask]
                joined = joined.set_geometry(clipped)
                joined = joined.drop(columns=["index_right"], errors="ignore")
        else:
            raise ValueError(f"Unsupported intersect join: {join!r}")

        if joined.empty:
            return self._empty_intersect(right_renamed)

        if spatial_only:
            mint = joined["_left_interval"].apply(lambda i: i.left)
            maxt = joined["_left_interval"].apply(lambda i: i.right)
            keep_mask = pd.Series(True, index=joined.index)
        else:
            li = joined["_left_interval"]
            ri = joined["_right_interval"]
            mint = np.maximum(
                li.apply(lambda i: i.left).to_numpy(),
                ri.apply(lambda i: i.left).to_numpy(),
            )
            maxt = np.minimum(
                li.apply(lambda i: i.right).to_numpy(),
                ri.apply(lambda i: i.right).to_numpy(),
            )
            keep_mask = pd.Series(maxt >= mint, index=joined.index)
            joined = joined[keep_mask]
            mint = mint[keep_mask.to_numpy()]
            maxt = maxt[keep_mask.to_numpy()]

        if joined.empty:
            return self._empty_intersect(right_renamed)

        idx = pd.IntervalIndex.from_arrays(mint, maxt, closed="both", name="datetime")
        joined = joined.drop(
            columns=[
                "_left_interval",
                "_right_interval",
                # The right side's time columns duplicate the index.
                "_right_start_time",
                "_right_end_time",
            ],
            errors="ignore",
        ).set_index(idx)
        # Keep the time columns (if present) in step with the new,
        # clipped index rather than the left side's original times.
        if "start_time" in joined.columns:
            joined["start_time"] = idx.left
        if "end_time" in joined.columns:
            joined["end_time"] = idx.right
        return InMemoryGeoCatalog(joined, kind=self.kind)

    def _empty_intersect(self, right_renamed: gpd.GeoDataFrame) -> InMemoryGeoCatalog:
        """Zero-row intersect result with the same columns as a non-empty one.

        This catalog's columns plus the ``_right_``-prefixed columns of
        ``other`` (minus its time columns, which the index replaces), so
        the result schema does not depend on whether any rows matched —
        the DuckDB backend's join behaves the same way.
        """
        gdf = self.gdf.iloc[:0].copy()
        geom_name = right_renamed.geometry.name
        for col in right_renamed.columns:
            if col in (geom_name, "_right_start_time", "_right_end_time"):
                continue
            gdf[col] = right_renamed[col].iloc[:0].to_numpy()
        return InMemoryGeoCatalog(gdf, kind=self.kind)

    def union(self, other: InMemoryGeoCatalog) -> InMemoryGeoCatalog:
        """Cross-catalog OR — concatenate rows.

        ``self``'s CRS and kind win. If ``other`` is in a
        different CRS it's reprojected into ``self.crs`` first. The
        kinds are *not* required to match: the caller is
        responsible for ensuring it makes sense to treat the merged
        rows uniformly (e.g. unioning two raster catalogs is fine;
        unioning raster + vector would lie about what the result
        indexes, but no exception is raised — the downstream loader
        will catch it via its own kind check).
        """
        if other.gdf.crs != self.gdf.crs:
            right_gdf = other.gdf.to_crs(self.gdf.crs)
        else:
            right_gdf = other.gdf
        geom_name = str(self.gdf.geometry.name)
        if right_gdf.geometry.name != geom_name:
            # Otherwise concat puts other's footprints in a separate
            # column and the merged geometry is null for those rows.
            right_gdf = right_gdf.rename_geometry(geom_name, inplace=False)
        merged = gpd.GeoDataFrame(
            pd.concat([self.gdf, right_gdf], axis=0), crs=self.gdf.crs
        )
        return InMemoryGeoCatalog(merged, kind=self.kind)

    def iter_rows(self, *, batch_size: int = 1024) -> Iterator[CatalogRow]:
        """Yield each row as a backend-neutral `CatalogRow`.

        Streaming-friendly: rows are constructed lazily so a caller can
        short-circuit a large catalog. ``batch_size`` is accepted for
        Protocol parity with `DuckDBGeoCatalog` and is ignored here —
        in-memory iteration is row-at-a-time regardless.

        Args:
            batch_size: Accepted for Protocol parity, ignored.

        Yields:
            `CatalogRow` in catalog row order. ``filepath`` comes from
            the ``filepath`` column (or the row index as a fallback);
            ``extras`` carries every other non-geometry column.
        """
        del batch_size
        crs = pyproj.CRS.from_user_input(self.gdf.crs)
        # Mirror `DuckDBGeoCatalog.iter_rows`: drop the GeoParquet 1.1
        # `bbox` covering struct and any underscore-prefixed on-disk
        # schema column (e.g. `_backend`, `_schema_version`) so they
        # don't leak through `CatalogRow.extras` into downstream
        # consumers (STAC export, matchup, …).
        # The active geometry column may be named something else
        # (`rename_geometry`); it is the footprint, never an extra.
        reserved = {*RESERVED_COLUMNS, str(self.gdf.geometry.name)}
        extra_cols = [
            c for c in self.gdf.columns if c not in reserved and not c.startswith("_")
        ]
        # Use ``.array`` rather than ``.to_numpy(copy=False)`` so pandas
        # extension scalars (notably ``Timestamp``) survive iteration with
        # the same types DuckDB's ``Series.iloc[i]`` produces — going
        # through NumPy would silently coerce them to ``np.datetime64``
        # etc. and make ``CatalogRow.extras`` backend-dependent.
        geoms = self.gdf.geometry.array
        intervals = self.gdf.index.array
        paths = self.gdf["filepath"].array if "filepath" in self.gdf.columns else None
        extras_data = {c: self.gdf[c].array for c in extra_cols}
        extras_items = tuple(extras_data.items())
        n_rows = len(self.gdf)

        for i in range(n_rows):
            filepath = paths[i] if paths is not None else None
            if filepath is None:
                filepath = str(intervals[i])
            extras = {c: values[i] for c, values in extras_items}
            yield CatalogRow(
                filepath=str(filepath),
                geometry=geoms[i],
                interval=intervals[i],
                crs=crs,
                extras=extras,
            )

    def iter_slices(self, *, resolution: tuple[float, float]) -> Iterator[GeoSlice]:
        """Yield one `GeoSlice` per row, at the given target resolution.

        Lazy — each `GeoSlice` is constructed on demand so callers can
        short-circuit large catalogs. The slice's ``bounds`` come from
        the row's footprint polygon, its ``interval`` from the
        IntervalIndex entry, and ``crs`` from ``self.gdf.crs``.

        Args:
            resolution: ``(x_res, y_res)`` in CRS units, baked into
                every emitted slice. Drives the pixel shape the
                downstream loader will produce.

        Yields:
            `GeoSlice` instances in catalog row order. Point and line
            footprints with a zero-width axis get a one-pixel extent on
            that axis, centred on the footprint; rows with a missing or
            empty footprint are skipped with a single warning.
        """
        crs = self.crs
        yield from _footprint_slices(
            zip(self.gdf.geometry, self.gdf.index, strict=True), resolution, crs
        )

    def where(self, query: str) -> InMemoryGeoCatalog:
        """Filter by a non-geometric predicate — escape hatch via pandas ``.query()``.

        Useful when the catalog carries extra columns (sensor, cloud %,
        mission ID) and you want to filter on them without writing a
        boolean mask by hand. The geometry / time axes are unaffected;
        for those use `query`.

        Args:
            query: A pandas query string, e.g. ``"cloud_pct < 20 and
                sensor == 'S2A'"``. Column names available are whatever
                the underlying ``GeoDataFrame`` has.

        Returns:
            A new catalog with the matching rows; same kind,
            same CRS.

        Example:
            >>> imagery.where("mission == 'S2A' and cloud_pct < 20")
        """
        return InMemoryGeoCatalog(self.gdf.query(query), kind=self.kind)

    def get_config(self) -> dict[str, Any]:
        """JSON-serialisable summary — kind, row count, CRS.

        Returns:
            ``{"kind": str, "len": int, "crs": str, "engine": "memory"}``
            (plus ``"backend"``, the deprecated name of ``"kind"``).
            The CRS is `crs_config_string`: ``"AUTH:CODE"`` (``"EPSG:32629"``)
            when the CRS carries an authority id, else WKT2 — the same
            string `DuckDBGeoCatalog` reports for the same artifact, before
            and after a GeoParquet round trip.
        """
        return {
            "kind": self.kind,
            "len": len(self),
            "crs": crs_config_string(self.crs),
            "engine": "memory",
            "backend": self.kind,  # deprecated key, kept for one release
        }

crs property

The catalog CRS (gdf.crs) as a pyproj.CRS.

temporal_extent cached property

Tightest interval spanning every row's time window.

Returns:

Type Description
Interval | None

``pd.Interval(min(start_times), max(end_times),

Interval | None

closed='both'), orNone`` for an empty catalog

Interval | None

(pd.Interval cannot hold NaT endpoints).

total_bounds cached property

Union bbox over all rows.

Returns:

Type Description
float

(xmin, ymin, xmax, ymax) in catalog-CRS units, or four

float

NaNs if the catalog is empty.

__len__()

Number of rows in the catalog.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/memory.py
def __len__(self) -> int:
    """Number of rows in the catalog."""
    return len(self.gdf)

get_config()

JSON-serialisable summary — kind, row count, CRS.

Returns:

Type Description
``{"kind"

str, "len": int, "crs": str, "engine": "memory"}``

dict[str, Any]

(plus "backend", the deprecated name of "kind").

The CRS is `crs_config_string`

"AUTH:CODE" ("EPSG:32629")

dict[str, Any]

when the CRS carries an authority id, else WKT2 — the same

dict[str, Any]

string DuckDBGeoCatalog reports for the same artifact, before

dict[str, Any]

and after a GeoParquet round trip.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/memory.py
def get_config(self) -> dict[str, Any]:
    """JSON-serialisable summary — kind, row count, CRS.

    Returns:
        ``{"kind": str, "len": int, "crs": str, "engine": "memory"}``
        (plus ``"backend"``, the deprecated name of ``"kind"``).
        The CRS is `crs_config_string`: ``"AUTH:CODE"`` (``"EPSG:32629"``)
        when the CRS carries an authority id, else WKT2 — the same
        string `DuckDBGeoCatalog` reports for the same artifact, before
        and after a GeoParquet round trip.
    """
    return {
        "kind": self.kind,
        "len": len(self),
        "crs": crs_config_string(self.crs),
        "engine": "memory",
        "backend": self.kind,  # deprecated key, kept for one release
    }

intersect(other, *, spatial_only=False, join='sjoin')

Cross-catalog AND — rows whose footprints and times overlap.

Parameters:

Name Type Description Default
other InMemoryGeoCatalog

Another catalog, possibly of another kind. The returned catalog has self's kind (it indexes the same kind of file as self).

required
spatial_only bool

If True, ignore the temporal axis — useful for pairing imagery with static labels.

False
join _JOIN_T

Spatial-join method. "sjoin" uses the GeoPandas spatial index, while "overlay" preserves the legacy overlay implementation. (engine= is the deprecated spelling; "engine" means the storage engine elsewhere.)

'sjoin'
Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/memory.py
@renamed_kwargs(engine="join")
def intersect(
    self,
    other: InMemoryGeoCatalog,
    *,
    spatial_only: bool = False,
    join: _JOIN_T = "sjoin",
) -> InMemoryGeoCatalog:
    """Cross-catalog AND — rows whose footprints and times overlap.

    Args:
        other: Another catalog, possibly of another kind. The
            returned catalog has ``self``'s `kind` (it indexes the
            same kind of file as ``self``).
        spatial_only: If True, ignore the temporal axis — useful for
            pairing imagery with static labels.
        join: Spatial-join method. ``"sjoin"`` uses the GeoPandas
            spatial index, while ``"overlay"`` preserves the legacy
            overlay implementation. (``engine=`` is the deprecated
            spelling; "engine" means the storage engine elsewhere.)
    """
    if other.gdf.crs != self.gdf.crs:
        right_gdf = other.gdf.to_crs(self.gdf.crs)
    else:
        right_gdf = other.gdf

    right_renamed = right_gdf.rename(
        columns={c: f"_right_{c}" for c in right_gdf.columns if c != "geometry"}
    )
    left = self.gdf.reset_index(names="_left_interval")
    right = right_renamed.reset_index(names="_right_interval")
    if join == "overlay":
        joined = gpd.overlay(left, right, how="intersection", keep_geom_type=True)
    elif join == "sjoin":
        joined = gpd.sjoin(left, right, how="inner", predicate="intersects")
        if not joined.empty:
            left_geometry = joined.geometry.reset_index(drop=True)
            right_geometry = right.geometry.iloc[joined["index_right"]].reset_index(
                drop=True
            )
            # Mirror gpd.overlay's default ``make_valid=True``: GEOS will
            # raise on self-intersecting inputs to ``shapely.intersection``.
            # Pay the repair cost only on rows actually flagged invalid.
            left_array = _repair_invalid(left_geometry.to_numpy())
            right_array = _repair_invalid(right_geometry.to_numpy())
            clipped = gpd.GeoSeries(
                _extract_same_family(
                    _symmetric_intersection(left_array, right_array),
                    left_geometry.to_numpy(),
                ),
                index=joined.index,
                crs=self.gdf.crs,
            )
            keep_geom_mask = _keep_geom_type_mask(joined.geometry, clipped)
            joined = joined.loc[keep_geom_mask].copy()
            clipped = clipped.loc[keep_geom_mask]
            joined = joined.set_geometry(clipped)
            joined = joined.drop(columns=["index_right"], errors="ignore")
    else:
        raise ValueError(f"Unsupported intersect join: {join!r}")

    if joined.empty:
        return self._empty_intersect(right_renamed)

    if spatial_only:
        mint = joined["_left_interval"].apply(lambda i: i.left)
        maxt = joined["_left_interval"].apply(lambda i: i.right)
        keep_mask = pd.Series(True, index=joined.index)
    else:
        li = joined["_left_interval"]
        ri = joined["_right_interval"]
        mint = np.maximum(
            li.apply(lambda i: i.left).to_numpy(),
            ri.apply(lambda i: i.left).to_numpy(),
        )
        maxt = np.minimum(
            li.apply(lambda i: i.right).to_numpy(),
            ri.apply(lambda i: i.right).to_numpy(),
        )
        keep_mask = pd.Series(maxt >= mint, index=joined.index)
        joined = joined[keep_mask]
        mint = mint[keep_mask.to_numpy()]
        maxt = maxt[keep_mask.to_numpy()]

    if joined.empty:
        return self._empty_intersect(right_renamed)

    idx = pd.IntervalIndex.from_arrays(mint, maxt, closed="both", name="datetime")
    joined = joined.drop(
        columns=[
            "_left_interval",
            "_right_interval",
            # The right side's time columns duplicate the index.
            "_right_start_time",
            "_right_end_time",
        ],
        errors="ignore",
    ).set_index(idx)
    # Keep the time columns (if present) in step with the new,
    # clipped index rather than the left side's original times.
    if "start_time" in joined.columns:
        joined["start_time"] = idx.left
    if "end_time" in joined.columns:
        joined["end_time"] = idx.right
    return InMemoryGeoCatalog(joined, kind=self.kind)

iter_rows(*, batch_size=1024)

Yield each row as a backend-neutral CatalogRow.

Streaming-friendly: rows are constructed lazily so a caller can short-circuit a large catalog. batch_size is accepted for Protocol parity with DuckDBGeoCatalog and is ignored here — in-memory iteration is row-at-a-time regardless.

Parameters:

Name Type Description Default
batch_size int

Accepted for Protocol parity, ignored.

1024

Yields:

Type Description
CatalogRow

CatalogRow in catalog row order. filepath comes from

CatalogRow

the filepath column (or the row index as a fallback);

CatalogRow

extras carries every other non-geometry column.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/memory.py
def iter_rows(self, *, batch_size: int = 1024) -> Iterator[CatalogRow]:
    """Yield each row as a backend-neutral `CatalogRow`.

    Streaming-friendly: rows are constructed lazily so a caller can
    short-circuit a large catalog. ``batch_size`` is accepted for
    Protocol parity with `DuckDBGeoCatalog` and is ignored here —
    in-memory iteration is row-at-a-time regardless.

    Args:
        batch_size: Accepted for Protocol parity, ignored.

    Yields:
        `CatalogRow` in catalog row order. ``filepath`` comes from
        the ``filepath`` column (or the row index as a fallback);
        ``extras`` carries every other non-geometry column.
    """
    del batch_size
    crs = pyproj.CRS.from_user_input(self.gdf.crs)
    # Mirror `DuckDBGeoCatalog.iter_rows`: drop the GeoParquet 1.1
    # `bbox` covering struct and any underscore-prefixed on-disk
    # schema column (e.g. `_backend`, `_schema_version`) so they
    # don't leak through `CatalogRow.extras` into downstream
    # consumers (STAC export, matchup, …).
    # The active geometry column may be named something else
    # (`rename_geometry`); it is the footprint, never an extra.
    reserved = {*RESERVED_COLUMNS, str(self.gdf.geometry.name)}
    extra_cols = [
        c for c in self.gdf.columns if c not in reserved and not c.startswith("_")
    ]
    # Use ``.array`` rather than ``.to_numpy(copy=False)`` so pandas
    # extension scalars (notably ``Timestamp``) survive iteration with
    # the same types DuckDB's ``Series.iloc[i]`` produces — going
    # through NumPy would silently coerce them to ``np.datetime64``
    # etc. and make ``CatalogRow.extras`` backend-dependent.
    geoms = self.gdf.geometry.array
    intervals = self.gdf.index.array
    paths = self.gdf["filepath"].array if "filepath" in self.gdf.columns else None
    extras_data = {c: self.gdf[c].array for c in extra_cols}
    extras_items = tuple(extras_data.items())
    n_rows = len(self.gdf)

    for i in range(n_rows):
        filepath = paths[i] if paths is not None else None
        if filepath is None:
            filepath = str(intervals[i])
        extras = {c: values[i] for c, values in extras_items}
        yield CatalogRow(
            filepath=str(filepath),
            geometry=geoms[i],
            interval=intervals[i],
            crs=crs,
            extras=extras,
        )

iter_slices(*, resolution)

Yield one GeoSlice per row, at the given target resolution.

Lazy — each GeoSlice is constructed on demand so callers can short-circuit large catalogs. The slice's bounds come from the row's footprint polygon, its interval from the IntervalIndex entry, and crs from self.gdf.crs.

Parameters:

Name Type Description Default
resolution tuple[float, float]

(x_res, y_res) in CRS units, baked into every emitted slice. Drives the pixel shape the downstream loader will produce.

required

Yields:

Type Description
GeoSlice

GeoSlice instances in catalog row order. Point and line

GeoSlice

footprints with a zero-width axis get a one-pixel extent on

GeoSlice

that axis, centred on the footprint; rows with a missing or

GeoSlice

empty footprint are skipped with a single warning.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/memory.py
def iter_slices(self, *, resolution: tuple[float, float]) -> Iterator[GeoSlice]:
    """Yield one `GeoSlice` per row, at the given target resolution.

    Lazy — each `GeoSlice` is constructed on demand so callers can
    short-circuit large catalogs. The slice's ``bounds`` come from
    the row's footprint polygon, its ``interval`` from the
    IntervalIndex entry, and ``crs`` from ``self.gdf.crs``.

    Args:
        resolution: ``(x_res, y_res)`` in CRS units, baked into
            every emitted slice. Drives the pixel shape the
            downstream loader will produce.

    Yields:
        `GeoSlice` instances in catalog row order. Point and line
        footprints with a zero-width axis get a one-pixel extent on
        that axis, centred on the footprint; rows with a missing or
        empty footprint are skipped with a single warning.
    """
    crs = self.crs
    yield from _footprint_slices(
        zip(self.gdf.geometry, self.gdf.index, strict=True), resolution, crs
    )

query(slice_=None, *, bounds=None, crs=None, time=None)

Spatial + temporal filter on the catalog.

Either pass a GeoSlice (carries bounds/time/crs together) or pass the parts. Bounds in a non-catalog CRS are reprojected internally — the canonical anti-footgun path (§10.1 of the design plan).

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/memory.py
def query(
    self,
    slice_: GeoSlice | None = None,
    *,
    bounds: tuple[float, float, float, float] | None = None,
    crs: Any | None = None,
    time: tuple[Any, Any] | pd.Interval | None = None,
) -> InMemoryGeoCatalog:
    """Spatial + temporal filter on the catalog.

    Either pass a `GeoSlice` (carries bounds/time/crs together) or
    pass the parts. Bounds in a non-catalog CRS are reprojected
    internally — the canonical anti-footgun path (§10.1 of the
    design plan).
    """
    if slice_ is not None and (
        bounds is not None or time is not None or crs is not None
    ):
        raise TypeError(
            "query: pass either slice_ or (bounds + crs + time), not both; "
            "a GeoSlice carries its own crs"
        )
    if slice_ is not None:
        q_bounds = slice_.bounds
        q_crs = slice_.crs
        q_interval = slice_.interval
    else:
        if bounds is None and time is None:
            # No filter — return a copy view.
            return InMemoryGeoCatalog(self.gdf.copy(), kind=self.kind)
        q_bounds = bounds
        q_crs = crs
        q_interval = _coerce_interval(time) if time is not None else None

    out = self.gdf
    if q_interval is not None:
        out = out[out.index.overlaps(q_interval)]
    if q_bounds is not None:
        envelopes = _query_envelopes(q_bounds, q_crs, self.gdf.crs)
        if len(envelopes) == 1:
            xmin, ymin, xmax, ymax = envelopes[0]
            out = out.cx[xmin:xmax, ymin:ymax]
        else:
            # Antimeridian split: same predicate as `.cx` (geometry
            # intersects the box), OR-ed over both halves.
            out = out[
                out.intersects(
                    shapely.MultiPolygon([shapely.box(*env) for env in envelopes])
                )
            ]
    return InMemoryGeoCatalog(out, kind=self.kind)

union(other)

Cross-catalog OR — concatenate rows.

self's CRS and kind win. If other is in a different CRS it's reprojected into self.crs first. The kinds are not required to match: the caller is responsible for ensuring it makes sense to treat the merged rows uniformly (e.g. unioning two raster catalogs is fine; unioning raster + vector would lie about what the result indexes, but no exception is raised — the downstream loader will catch it via its own kind check).

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/memory.py
def union(self, other: InMemoryGeoCatalog) -> InMemoryGeoCatalog:
    """Cross-catalog OR — concatenate rows.

    ``self``'s CRS and kind win. If ``other`` is in a
    different CRS it's reprojected into ``self.crs`` first. The
    kinds are *not* required to match: the caller is
    responsible for ensuring it makes sense to treat the merged
    rows uniformly (e.g. unioning two raster catalogs is fine;
    unioning raster + vector would lie about what the result
    indexes, but no exception is raised — the downstream loader
    will catch it via its own kind check).
    """
    if other.gdf.crs != self.gdf.crs:
        right_gdf = other.gdf.to_crs(self.gdf.crs)
    else:
        right_gdf = other.gdf
    geom_name = str(self.gdf.geometry.name)
    if right_gdf.geometry.name != geom_name:
        # Otherwise concat puts other's footprints in a separate
        # column and the merged geometry is null for those rows.
        right_gdf = right_gdf.rename_geometry(geom_name, inplace=False)
    merged = gpd.GeoDataFrame(
        pd.concat([self.gdf, right_gdf], axis=0), crs=self.gdf.crs
    )
    return InMemoryGeoCatalog(merged, kind=self.kind)

where(query)

Filter by a non-geometric predicate — escape hatch via pandas .query().

Useful when the catalog carries extra columns (sensor, cloud %, mission ID) and you want to filter on them without writing a boolean mask by hand. The geometry / time axes are unaffected; for those use query.

Parameters:

Name Type Description Default
query str

A pandas query string, e.g. "cloud_pct < 20 and sensor == 'S2A'". Column names available are whatever the underlying GeoDataFrame has.

required

Returns:

Type Description
InMemoryGeoCatalog

A new catalog with the matching rows; same kind,

InMemoryGeoCatalog

same CRS.

Example

imagery.where("mission == 'S2A' and cloud_pct < 20")

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/memory.py
def where(self, query: str) -> InMemoryGeoCatalog:
    """Filter by a non-geometric predicate — escape hatch via pandas ``.query()``.

    Useful when the catalog carries extra columns (sensor, cloud %,
    mission ID) and you want to filter on them without writing a
    boolean mask by hand. The geometry / time axes are unaffected;
    for those use `query`.

    Args:
        query: A pandas query string, e.g. ``"cloud_pct < 20 and
            sensor == 'S2A'"``. Column names available are whatever
            the underlying ``GeoDataFrame`` has.

    Returns:
        A new catalog with the matching rows; same kind,
        same CRS.

    Example:
        >>> imagery.where("mission == 'S2A' and cloud_pct < 20")
    """
    return InMemoryGeoCatalog(self.gdf.query(query), kind=self.kind)

DuckDB (extras: [duckdb])

geocatalog.backends.DuckDBGeoCatalog

Lazy, SQL-backed catalog over a GeoParquet artifact.

Holds a DuckDB relation — a query plan, not materialised rows. query / intersect / union return new relations; nothing executes until iter_rows / materialize / gdf is touched.

The class implements the same GeoCatalog Protocol as InMemoryGeoCatalog. Loaders that take catalog.gdf work but materialise the relation on access — explicit callers should prefer iter_rows for streaming.

Connection ownership is explicit: catalogs returned by open own their DuckDB connection and close it from close or context-manager exit. Catalogs derived from query / intersect / union share their parent's connection and close() is a no-op for them. Even a no-filter query returns a non-owning wrapper so calling close on the result cannot close the parent catalog.

Derived catalogs additionally hold a strong reference back to the originating owning catalog via _owner. This keeps the fluent chain DuckDBGeoCatalog.open(path).query(...) safe: the transitively-referenced owner stays alive (and its connection open) as long as any derived catalog in the chain is reachable. When a derived catalog is used as a context manager (with cat.query(...) as out:), its __exit__ closes the owning catalog so the underlying connection is released on block exit. Calling close() directly on a derived catalog remains a no-op — only __exit__ (or closing the owner directly) tears down the shared connection.

Parameters:

Name Type Description Default
relation DuckDBPyRelation

A DuckDB relation whose columns include filepath, geometry (WKB BLOB or GEOMETRY), start_time, end_time, optionally a bbox covering struct (GeoParquet 1.1), plus any per-backend extras.

required
con DuckDBPyConnection

The connection that owns relation. Must outlive the catalog.

required
crs Any

CRS of the geometry column. The catalog stores it once (canonical-CRS convention) — per-row CRS is not supported by this backend.

required
kind CatalogKind

"raster" / "xarray" / "vector"; drives loader dispatch.

required
_owns_con bool

Whether this catalog is responsible for closing con.

False

Attributes:

Name Type Description
relation

The underlying DuckDB relation; escape hatch for SQL power users.

con DuckDBPyConnection | None

The associated connection. Set to None after an owning catalog is closed.

crs

pyproj.CRS for geometry.

kind

The kind of data indexed (loader dispatch tag).

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/duckdb_backend.py
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
class DuckDBGeoCatalog:
    """Lazy, SQL-backed catalog over a GeoParquet artifact.

    Holds a DuckDB *relation* — a query plan, not materialised rows.
    `query` / `intersect` / `union` return new relations; nothing
    executes until ``iter_rows`` / ``materialize`` / ``gdf`` is touched.

    The class implements the same `GeoCatalog` Protocol as
    `InMemoryGeoCatalog`. Loaders that take ``catalog.gdf`` work but
    materialise the relation on access — explicit callers should prefer
    ``iter_rows`` for streaming.

    Connection ownership is explicit: catalogs returned by `open` own
    their DuckDB connection and close it from `close` or context-manager
    exit. Catalogs derived from `query` / `intersect` / `union` share
    their parent's connection and ``close()`` is a no-op for them. Even
    a no-filter `query` returns a non-owning wrapper so calling ``close``
    on the result cannot close the parent catalog.

    Derived catalogs additionally hold a strong reference back to the
    originating *owning* catalog via ``_owner``. This keeps the fluent
    chain ``DuckDBGeoCatalog.open(path).query(...)`` safe: the
    transitively-referenced owner stays alive (and its connection
    open) as long as any derived catalog in the chain is reachable.
    When a derived catalog is used as a context manager
    (``with cat.query(...) as out:``), its ``__exit__`` closes the
    owning catalog so the underlying connection is released on block
    exit. Calling ``close()`` directly on a derived catalog remains a
    no-op — only ``__exit__`` (or closing the owner directly) tears
    down the shared connection.

    Args:
        relation: A DuckDB relation whose columns include ``filepath``,
            ``geometry`` (WKB BLOB or GEOMETRY), ``start_time``,
            ``end_time``, optionally a ``bbox`` covering struct (GeoParquet
            1.1), plus any per-backend extras.
        con: The connection that owns ``relation``. Must outlive the
            catalog.
        crs: CRS of the ``geometry`` column. The catalog stores it once
            (canonical-CRS convention) — per-row CRS is not supported by
            this backend.
        kind: ``"raster"`` / ``"xarray"`` / ``"vector"``; drives
            loader dispatch.
        _owns_con: Whether this catalog is responsible for closing
            ``con``.

    Attributes:
        relation: The underlying DuckDB relation; escape hatch for SQL
            power users.
        con: The associated connection. Set to ``None`` after an owning
            catalog is closed.
        crs: ``pyproj.CRS`` for ``geometry``.
        kind: The kind of data indexed (loader dispatch tag).
    """

    backend = deprecated_alias("kind")

    @renamed_kwargs(backend="kind")
    def __init__(
        self,
        relation: duckdb_mod.DuckDBPyRelation,
        *,
        con: duckdb_mod.DuckDBPyConnection,
        crs: Any,
        kind: CatalogKind,
        _owns_con: bool = False,
    ) -> None:
        _require_duckdb()
        check_kind(kind, "DuckDBGeoCatalog")
        self.relation = relation
        self.con: duckdb_mod.DuckDBPyConnection | None = con
        self.crs = pyproj.CRS.from_user_input(crs)
        self.kind = kind
        self._owns_con = _owns_con
        self._lock = _con_lock(con)
        # True when every row carries a trustworthy GeoParquet 1.1 `bbox`
        # covering struct (a relation read by `open`, and filters of it).
        # `query` then adds bbox predicates the Parquet scan can prune
        # row groups with. Set by `open`; kept by `query` / `sql`; never
        # set for joins / unions, whose rows may lack a bbox.
        self._bbox_covering = False
        # False when `open` could not load DuckDB's spatial extension; spatial
        # queries will fail. `open_catalog(engine="auto")` checks it.
        self._spatial_available = True
        # Strong ref back to the *owning* catalog when this instance is a
        # derivation (`query` / `intersect` / `union` / `sql`). Keeps the
        # owner — and therefore the underlying DuckDB connection — alive
        # for the lifetime of any derived catalog in the chain, so the
        # fluent pattern `DuckDBGeoCatalog.open(p).query(...)` doesn't
        # drop the only reference to the owner mid-expression and leak
        # the connection in long-lived processes.
        self._owner: DuckDBGeoCatalog | None = None

    def _require_open_con(self) -> duckdb_mod.DuckDBPyConnection:
        # Derived catalogs share the owner's connection — if the owner
        # was closed, our `self.con` still points at the (now-closed)
        # DuckDBPyConnection object, so check the owner first.
        con = self.con
        if con is None or (self._owner is not None and self._owner.con is None):
            raise _closed_error()(
                "DuckDBGeoCatalog connection has already been closed. Open a new "
                "catalog, or keep the parent catalog open when using derived catalogs."
            )
        return con

    @contextmanager
    def _locked(self) -> Iterator[duckdb_mod.DuckDBPyConnection]:
        """Hold the connection's lock and yield the open connection."""
        with self._lock:
            yield self._require_open_con()

    def _derive(
        self,
        relation: duckdb_mod.DuckDBPyRelation,
        *,
        keeps_rows: bool = False,
    ) -> DuckDBGeoCatalog:
        """Wrap ``relation`` as a catalog sharing this one's connection.

        ``keeps_rows`` marks a pure row filter of ``self.relation``, which
        may inherit the bbox-covering guarantee.
        """
        derived = DuckDBGeoCatalog(
            relation,
            con=self._require_open_con(),
            crs=self.crs,
            kind=self.kind,
        )
        derived._bbox_covering = keeps_rows and self._bbox_covering
        # Anchor the derivation chain at the originating owning catalog.
        # If `self` owns its connection, `self` is the owner; otherwise
        # `self` itself is a derivation and we inherit its owner. This
        # gives every derived instance a direct strong ref to the root
        # owner — `A.query().intersect()` keeps `A` reachable until the
        # outermost derived catalog is dropped.
        derived._owner = self if self._owns_con else self._owner
        return derived

    def close(self) -> None:
        """Close this catalog's DuckDB connection if it owns it.

        No-op for derived catalogs (from `query` / `intersect` / `union`
        / `sql`) — they share the owner's connection and closing them
        would invalidate sibling derivations. Use the *owning* catalog's
        ``close``, or a context manager on the owning instance, to tear
        down the connection. A derived catalog used as a context
        manager closes its owner on ``__exit__``.
        """
        with self._lock:
            if self._owns_con and self.con is not None:
                self.con.close()
                self.con = None

    def __enter__(self) -> DuckDBGeoCatalog:
        self._require_open_con()
        return self

    def __exit__(
        self,
        exc_type: type[BaseException] | None,
        exc: BaseException | None,
        tb: Any,
    ) -> None:
        # On exit, close the owner if we have one — that's the fluent
        # `with DuckDBGeoCatalog.open(p).query(...) as cat:` pattern,
        # where the only handle the caller has is `cat` (a derivation),
        # and the underlying connection would otherwise leak. For an
        # owning catalog `_owner is None`, so we fall back to closing
        # ourselves. Direct `close()` calls on a derivation remain a
        # no-op so sibling derivations on the same owner stay valid.
        if self._owner is not None:
            self._owner.close()
        else:
            self.close()

    # ── factories ────────────────────────────────────────────────────────

    @classmethod
    @renamed_kwargs(backend="kind")
    def open(
        cls,
        source: str | Path,
        *,
        kind: CatalogKind | None = None,
        crs: Any | None = None,
        retries: int = 3,
        storage_options: dict[str, Any] | None = None,
        strict: bool = False,
    ) -> DuckDBGeoCatalog:
        """Open a GeoParquet file (or directory of shards) lazily.

        Reads the source via DuckDB's `read_parquet`; the relation
        carries the schema but no rows are materialised until queried.
        Local paths are supported directly. URI sources with ``s3://``
        (``s3a://``, ``s3n://``), ``gs://``, ``gcs://``, ``http://``,
        ``https://``, ``r2://`` or ``hf://`` auto-load DuckDB's `httpfs`
        extension; ``az://``, ``azure://`` and ``abfss://`` auto-load
        DuckDB's `azure` extension.

        CRS is recovered from the GeoParquet column metadata (PROJJSON)
        for **local files only** — the metadata reader uses
        `pyarrow.parquet.read_metadata` over a local `Path`. For URI
        sources (``s3://``, ``https://``, ``hf://``, …) the auto-detect
        cannot reach the remote object and silently falls back to the
        ``EPSG:4326`` default; a `UserWarning` is emitted in that case.
        Pass ``crs=`` explicitly for remote sources to avoid the
        fallback. (Remote GeoParquet CRS introspection would need an
        fsspec/pyarrow filesystem hookup and is tracked separately.)

        The kind is recovered from the reserved ``_backend``
        column written by `to_geoparquet`; ad-hoc parquet files lacking
        it default to ``"raster"`` unless overridden.

        Args:
            source: Path or URI. A directory or glob (``shards/*.parquet``)
                is read as one virtual table.
            kind: Kind override (loader dispatch). ``None`` reads the
                ``_backend`` column, falling back to ``"raster"``.
            crs: CRS override. ``None`` reads the GeoParquet PROJJSON
                metadata for local files; falls back to ``EPSG:4326`` if
                neither is present (noisy default rather than silent
                coercion). For URI sources, ``None`` always falls back
                to the default — pass ``crs=`` explicitly.
            retries: Number of retries for transient remote I/O failures.
                ``0`` disables retry/backoff.
            storage_options: Not supported by this backend — DuckDB reads
                URIs natively via its `httpfs` / `azure` extensions and
                does not accept an fsspec-style credential mapping. Pass
                ``None``; configure DuckDB secrets (or pre-set env vars)
                before calling `open`. Use ``engine='memory'`` if you need
                fsspec-backed reads.
            strict: If ``True``, raise `CatalogMetadataError` instead of
                falling back when the ``_backend`` column is missing /
                unreadable (and ``kind=`` was not passed) or the
                GeoParquet ``geo`` metadata is unreadable (and ``crs=``
                was not passed). Remote URIs cannot be introspected at
                all, so ``strict=True`` requires an explicit ``crs=``
                for them. Explicit ``kind=`` / ``crs=`` overrides
                bypass the corresponding check.

        Returns:
            A `DuckDBGeoCatalog` over the relation.
        """
        if storage_options is not None:
            raise ValueError(
                "DuckDBGeoCatalog does not support storage_options. Use "
                "open_catalog(source, engine='memory', storage_options=...) "
                "for fsspec-backed reads (loads the full catalog into memory), "
                "or configure DuckDB credentials directly."
            )
        if kind is not None:  # fail before a connection exists
            check_kind(kind, "DuckDBGeoCatalog")
        dd = _require_duckdb()
        con = dd.connect()
        try:
            spatial_ok = _ensure_spatial(con)
            source_str = _read_parquet_source(source)
            partitioned = _is_partitioned_source(source)
            scheme = _scheme(source)
            extension = DUCKDB_EXTENSIONS.get(scheme or "")
            if extension is not None:
                con.execute(f"INSTALL {extension}")
                con.execute(f"LOAD {extension}")
            if crs is None:
                if scheme is not None and strict:
                    raise CatalogMetadataError(
                        f"cannot auto-detect CRS from remote URI {source_str}: "
                        "GeoParquet metadata introspection only works for "
                        "local files. Pass crs= explicitly when strict=True."
                    )
                if scheme is not None:
                    warnings.warn(
                        f"DuckDBGeoCatalog.open({source_str!r}): cannot auto-detect "
                        "CRS from a remote URI; falling back to EPSG:4326. Pass "
                        "`crs=` explicitly for remote sources to avoid silent "
                        "default coercion.",
                        UserWarning,
                        stacklevel=2,
                    )
                crs = retry_transient_io(
                    _read_geoparquet_crs,
                    source,
                    default="EPSG:4326",
                    strict=strict,
                    retries=retries,
                )
            if kind is None:
                kind = retry_transient_io(
                    _read_backend_tag,
                    con,
                    source_str,
                    default="raster",
                    partitioned=partitioned,
                    strict=strict,
                    retries=retries,
                )
            retry_transient_io(
                _check_schema_version,
                con,
                source_str,
                partitioned=partitioned,
                retries=retries,
            )
            # `con.read_parquet` builds a lazy scan: nothing is read until a
            # query executes, and filters are pushed into the Parquet scan.
            # (`con.sql(..., params=...)` executes immediately and returns a
            # materialised relation — the whole artifact, remote included,
            # was pulled at open; #221.) The path is passed as a value, not
            # interpolated, so apostrophes and hostile input are safe.
            # `hive_partitioning` is conditional: enabling it on a single
            # file under a `key=value` directory would inject a synthetic
            # partition column into the schema.
            relation = retry_transient_io(
                con.read_parquet,
                source_str,
                hive_partitioning=partitioned,
                retries=retries,
            )
            # Inside the cleanup block: a stored `_backend` the constructor
            # rejects must not leak the connection either.
            catalog = cls(relation, con=con, crs=crs, kind=kind, _owns_con=True)
            catalog._bbox_covering = _has_bbox_covering(relation)
            catalog._spatial_available = spatial_ok
        except BaseException:
            # Setup failed (bad extension load, schema mismatch, IO error,
            # invalid kind); don't leak the freshly opened connection.
            con.close()
            raise
        return catalog

    @classmethod
    def from_memory(
        cls,
        catalog: InMemoryGeoCatalog,
        *,
        con: duckdb_mod.DuckDBPyConnection | None = None,
    ) -> DuckDBGeoCatalog:
        """Register an `InMemoryGeoCatalog` as a DuckDB relation.

        Useful for upgrading a small in-RAM catalog into the SQL surface
        (e.g. to spatial-join two in-memory catalogs in parallel) without
        going through a Parquet round-trip.

        Args:
            catalog: The in-memory catalog to wrap.
            con: Optional DuckDB connection to register into. A fresh
                in-memory connection is created if omitted; ownership
                of an externally supplied connection stays with the
                caller (close is a no-op for it).

        Returns:
            A `DuckDBGeoCatalog` over the same rows. The relation scans a
            WKB-encoded copy of the gdf, so later changes to the gdf are
            not seen.
        """
        dd = _require_duckdb()
        owns_con = con is None
        if con is None:
            con = dd.connect()
        try:
            df = _gdf_to_arrow_df(catalog.gdf)
            # Every statement on ``con`` — including the extension LOAD —
            # holds its lock: ``con`` may be shared with a catalog that is
            # executing in another thread (#224).
            with _con_lock(con):
                _ensure_spatial(con)
                # `from_df` scans the DataFrame object directly: no named
                # view or registration, so nothing another call can
                # overwrite (named views keyed on `id()` were rebound when
                # CPython reused an id; #222).
                relation = con.from_df(df).project(
                    "* EXCLUDE (geometry), ST_GeomFromWKB(geometry) AS geometry"
                )
        except BaseException:
            if owns_con:
                con.close()
            raise
        return cls(
            relation,
            con=con,
            crs=catalog.gdf.crs,
            kind=catalog.kind,
            _owns_con=owns_con,
        )

    # ── lazy ↔ eager bridges ─────────────────────────────────────────────

    @cached_property
    def gdf(self) -> gpd.GeoDataFrame:
        """Materialise the relation as a `gpd.GeoDataFrame`.

        Cached — the first access executes the query; subsequent
        accesses are O(1). This is the eager bridge that lets loaders
        written against the in-memory backend work unchanged. For
        streaming/scale callers, prefer `iter_rows`.
        """
        return self.materialize().gdf

    def materialize(self) -> InMemoryGeoCatalog:
        """Execute the relation and wrap the result as an `InMemoryGeoCatalog`.

        Decodes WKB to shapely geometries and rebuilds the
        ``IntervalIndex`` from ``start_time`` / ``end_time``. Useful for
        moving the result into operations that need the full pandas /
        geopandas surface (custom merges, plotting, debugging) but
        defeats the lazy story — call after a selective ``query``.

        Returns:
            An `InMemoryGeoCatalog` over the materialised rows, same
            CRS, same kind.
        """
        with self._locked():
            df = self.relation.df()
        return _df_to_inmemory(df, crs=self.crs, kind=self.kind)

    # ── Protocol surface ─────────────────────────────────────────────────

    def query(
        self,
        slice_: GeoSlice | None = None,
        *,
        bounds: tuple[float, float, float, float] | None = None,
        crs: Any | None = None,
        time: tuple[Any, Any] | pd.Interval | None = None,
    ) -> DuckDBGeoCatalog:
        """SQL spatial + temporal filter — lazy, returns a new relation.

        Builds a ``WHERE`` clause that DuckDB can push down to the
        Parquet reader (bbox-column predicates skip whole row-groups).
        Mirrors `InMemoryGeoCatalog.query`; AOI bounds in a different
        CRS are reprojected internally before being interpolated into
        the SQL.

        Args:
            slice_: A `GeoSlice` whose bbox + interval drive the filter.
                Mutually exclusive with the keyword args.
            bounds: ``(xmin, ymin, xmax, ymax)`` in ``crs`` units.
            crs: CRS of ``bounds``; defaults to the catalog CRS.
            time: Either a ``(start, end)`` pair (`pd.Timestamp`-like)
                or a `pd.Interval`. ``None`` skips the temporal filter.

        Returns:
            A new `DuckDBGeoCatalog` over the filtered relation. May be
            empty; ``len()`` triggers a count query.

        Raises:
            TypeError: If both ``slice_`` and any of (``bounds``,
                ``time``) are passed.
        """
        self._require_open_con()
        if slice_ is not None and (
            bounds is not None or time is not None or crs is not None
        ):
            raise TypeError(
                "query: pass either slice_ or (bounds + crs + time), not both; "
                "a GeoSlice carries its own crs"
            )
        if slice_ is not None:
            q_bounds = slice_.bounds
            q_crs = slice_.crs
            q_interval = slice_.interval
        else:
            if bounds is None and time is None:
                return self._derive(self.relation, keeps_rows=True)
            q_bounds = bounds
            q_crs = crs
            q_interval = _coerce_interval(time) if time is not None else None

        # The relation API's `.filter()` takes a SQL string, so these
        # predicates are interpolated rather than bound as parameters.
        # Every interpolated value is force-coerced to a safe literal
        # first (float / `pd.Timestamp.isoformat`) — never interpolate
        # a raw user string here.
        where: list[str] = []
        if q_bounds is not None:
            # One envelope, or two when the AOI crosses the antimeridian.
            # With a bbox covering column, a plain comparison on it comes
            # first: DuckDB pushes it into the Parquet scan (row-group
            # pruning), which it cannot do for ST_Intersects (#221).
            envelopes = _query_envelopes(q_bounds, q_crs, self.crs)
            terms = []
            for xmin, ymin, xmax, ymax in envelopes:
                st = (
                    f"ST_Intersects(geometry, "
                    f"ST_MakeEnvelope({xmin!r}, {ymin!r}, {xmax!r}, {ymax!r}))"
                )
                if self._bbox_covering:
                    st = (
                        f"bbox.xmax >= {xmin!r} AND bbox.xmin <= {xmax!r} AND "
                        f"bbox.ymax >= {ymin!r} AND bbox.ymin <= {ymax!r} AND {st}"
                    )
                terms.append(f"({st})")
            where.append(f"({' OR '.join(terms)})")
        if q_interval is not None:
            # Bounds are naive UTC (`_coerce_interval` / GeoSlice). Type the
            # literal to match the column so DuckDB never casts through the
            # session time zone: a TIMESTAMP literal compared with a
            # TIMESTAMPTZ column would be read in the host's zone.
            literal = self._time_literal
            suffix = "+00:00" if literal == "TIMESTAMPTZ" else ""
            t_lo = to_naive_utc(q_interval.left).isoformat() + suffix
            t_hi = to_naive_utc(q_interval.right).isoformat() + suffix
            where.append(f"end_time >= {literal} '{t_lo}'")
            where.append(f"start_time <= {literal} '{t_hi}'")

        if not where:
            return self._derive(self.relation, keeps_rows=True)
        clause = " AND ".join(where)
        with self._locked():
            filtered = self.relation.filter(clause)
        return self._derive(filtered, keeps_rows=True)

    def intersect(
        self,
        other: DuckDBGeoCatalog | InMemoryGeoCatalog,
        *,
        spatial_only: bool = False,
    ) -> DuckDBGeoCatalog:
        """Cross-catalog AND via SQL spatial join.

        Translates to ``SELECT ... FROM self JOIN other ON
        ST_Intersects(self.geometry, other.geometry) [AND interval-overlap]``.
        The DuckDB planner builds an R-tree on the smaller side and
        probes with the larger; cost scales as ``O(n log n + m log n)``
        versus `gpd.overlay`'s near-quadratic blow-up at scale.

        Args:
            other: Another catalog. An `InMemoryGeoCatalog` is registered
                via `from_memory` before joining. CRS is reprojected
                into ``self.crs`` if the two differ — done at registration
                time, not in SQL, so the join itself runs in one CRS.
            spatial_only: If True, drop the temporal predicate.

        Returns:
            A new `DuckDBGeoCatalog` over the joined relation. Footprints
            are clipped to ``ST_Intersection``; intervals to the
            tightest overlap of left and right (or the left interval
            when ``spatial_only=True``).
        """
        con = self._require_open_con()
        other_duck = _coerce_to_duckdb(other, con=con, target_crs=self.crs)

        temporal = (
            ""
            if spatial_only
            else (" AND L.end_time >= R.start_time AND L.start_time <= R.end_time")
        )
        time_select = (
            "L.start_time AS start_time, L.end_time AS end_time"
            if spatial_only
            else (
                "GREATEST(L.start_time, R.start_time) AS start_time, "
                "LEAST   (L.end_time,   R.end_time)   AS end_time"
            )
        )
        # GEOS intersection is not bit-symmetric under operand order for
        # near-degenerate sliver overlaps (geocatalog#40) — canonicalise each
        # pair's operand order by WKB bytes, mirroring the in-memory
        # engine's `_symmetric_intersection`, so `a.intersect(b)` and
        # `b.intersect(a)` compute identical geometry per row pair.
        # Relation-API join on aliased relations rather than SQL over
        # named views: the result holds both inputs by reference, so no
        # later `intersect` / `union` can rebind it (#222) and no views
        # accumulate on the connection. `other` was coerced above, before
        # taking our lock, so we never hold two connections' locks.
        with self._locked():
            joined = self._join(other_duck, temporal, time_select)
        return self._derive(joined)

    def _join(
        self, other_duck: DuckDBGeoCatalog, temporal: str, time_select: str
    ) -> duckdb_mod.DuckDBPyRelation:
        """Spatial(-temporal) join with the same output as `InMemoryGeoCatalog`.

        - Every left column is kept; right columns come back prefixed
          ``_right_`` (#225). The time columns come from ``time_select``;
          geometry and the file-level housekeeping columns are rebuilt.
        - The clip keeps only the left row's geometry family, like
          ``gpd.overlay(keep_geom_type=True)``: the polygon part of a
          GeometryCollection is kept, while a pure boundary touch (a
          LineString or Point clip of two polygons) drops the row.
          Single-part MULTI results are unwrapped to match InMemory.
        """
        skip = {"geometry", "start_time", "end_time", "bbox", *INTERNAL_COLUMNS}
        left_cols = [c for c in self.relation.columns if c not in skip]
        right_cols = [c for c in other_duck.relation.columns if c not in skip]
        # ST_GeometryType returns an enum; compare it as text.
        left_type = "CAST(ST_GeometryType(L.geometry) AS VARCHAR)"
        left_family = (
            f"CASE WHEN {left_type} IN ('POINT', 'MULTIPOINT') THEN 1 "
            f"WHEN {left_type} IN ('LINESTRING', 'MULTILINESTRING') "
            "THEN 2 ELSE 3 END"
        )
        clip_col = "__geocatalog_clip"

        # Repair invalid (e.g. self-intersecting) footprints before
        # clipping, like the in-memory engine's `_repair_invalid`: GEOS
        # raises a TopologyException on them otherwise.
        def _valid(g: str) -> str:
            return f"CASE WHEN ST_IsValid({g}) THEN {g} ELSE ST_MakeValid({g}) END"

        lg, rg = _valid("L.geometry"), _valid("R.geometry")
        stage1 = ", ".join(
            [
                *(f"L.{_quote_ident(c)} AS {_quote_ident(c)}" for c in left_cols),
                f"""ST_CollectionExtract(
                    CASE
                        WHEN ST_AsWKB(L.geometry) > ST_AsWKB(R.geometry)
                            THEN ST_Intersection({rg}, {lg})
                        ELSE ST_Intersection({lg}, {rg})
                    END,
                    {left_family}
                ) AS {clip_col}""",
                time_select,
                *(
                    f"R.{_quote_ident(c)} AS {_quote_ident('_right_' + c)}"
                    for c in right_cols
                ),
            ]
        )
        final = ", ".join(
            [
                *(_quote_ident(c) for c in left_cols),
                f"""CASE
                    WHEN CAST(ST_GeometryType({clip_col}) AS VARCHAR) LIKE 'MULTI%'
                         AND ST_NumGeometries({clip_col}) = 1
                        THEN ST_Dump({clip_col})[1].geom
                    ELSE {clip_col}
                END AS geometry""",
                "start_time",
                "end_time",
                *(_quote_ident("_right_" + c) for c in right_cols),
            ]
        )
        return (
            self.relation.set_alias("L")
            .join(
                other_duck.relation.set_alias("R"),
                f"ST_Intersects(L.geometry, R.geometry){temporal}",
                how="inner",
            )
            .project(stage1)
            .filter(f"NOT ST_IsEmpty({clip_col})")
            .project(final)
        )

    def union(self, other: DuckDBGeoCatalog | InMemoryGeoCatalog) -> DuckDBGeoCatalog:
        """Cross-catalog OR via SQL ``UNION ALL``.

        ``self``'s CRS and kind win. ``other`` is reprojected
        into ``self.crs`` if needed before the union. Schemas must be
        compatible for the columns both sides share; extra columns on
        one side become NULL on the other.

        Args:
            other: Catalog to concatenate. Reprojected if needed.

        Returns:
            A new `DuckDBGeoCatalog` over the union relation.
        """
        con = self._require_open_con()
        # Coerce before taking our lock (see `intersect`).
        other_duck = _coerce_to_duckdb(other, con=con, target_crs=self.crs)
        del con
        with self._locked():
            unioned = self._union_by_name(other_duck)
        return self._derive(unioned)

    def _union_by_name(
        self, other_duck: DuckDBGeoCatalog
    ) -> duckdb_mod.DuckDBPyRelation:
        # `UNION ALL BY NAME` semantics without named views (#222): both
        # sides are projected onto the same ordered column list, with a
        # typed NULL for columns only the other side has. That preserves
        # backend-specific columns (`time_var`, `data_vars`, `layer`)
        # instead of dropping them like a positional `UNION ALL` would.
        left, right = self.relation, other_duck.relation
        left_types = dict(zip(left.columns, left.types, strict=True))
        right_types = dict(zip(right.columns, right.types, strict=True))
        columns = [*left_types, *(c for c in right_types if c not in left_types)]

        def _aligned(types: dict[str, Any], fill: dict[str, Any]) -> str:
            return ", ".join(
                _quote_ident(c)
                if c in types
                else f"CAST(NULL AS {fill[c]}) AS {_quote_ident(c)}"
                for c in columns
            )

        return left.project(_aligned(left_types, right_types)).union(
            right.project(_aligned(right_types, left_types))
        )

    def iter_rows(self, *, batch_size: int = 1024) -> Iterator[CatalogRow]:
        """Stream rows as `CatalogRow` instances in Arrow batches.

        Streams the relation through DuckDB's Arrow record-batch reader,
        so time-to-first-row and peak memory are ``O(batch_size)`` —
        not ``O(len(catalog))`` as the previous ``.df()``-materialising
        implementation was. Geometry WKB is decoded one vectorised
        `shapely.from_wkb` call per batch.

        Args:
            batch_size: Rows per Arrow record batch. Bounds both the
                first-row latency and the peak memory of a full
                iteration.

        Yields:
            `CatalogRow` with ``geometry`` decoded from WKB.
        """
        if batch_size < 1:
            raise ValueError(f"batch_size must be >= 1; got {batch_size}")
        # The lock is held for the whole iteration: any other query on the
        # connection would close this stream. Other threads using the same
        # catalog wait until the iteration finishes (or the generator is
        # closed); don't block inside the loop on such a thread.
        with self._locked():
            yield from self._iter_batches(batch_size)

    def _iter_batches(self, batch_size: int) -> Iterator[CatalogRow]:
        for batch in self._arrow_reader(batch_size):
            df = batch.to_pandas()
            if len(df) == 0:
                continue
            geoms = _decode_geometry_column(df["geometry"])
            # TIMESTAMPTZ columns arrive in the session time zone; convert
            # to the catalog's naive-UTC form so rows match InMemory's.
            starts = naive_utc_datetimes(pd.to_datetime(df["start_time"]))
            ends = naive_utc_datetimes(pd.to_datetime(df["end_time"]))
            # `_backend`, `_schema_version` and any other underscore-prefixed
            # column belong to the on-disk schema, not the user-visible row
            # metadata. Filtering them keeps `extras` clean for downstream
            # loaders that introspect it.
            extra_cols = [
                c
                for c in df.columns
                if c not in RESERVED_COLUMNS and not c.startswith("_")
            ]
            paths = df["filepath"] if "filepath" in df.columns else None
            for i in range(len(df)):
                extras = {c: df[c].iloc[i] for c in extra_cols}
                interval = pd.Interval(starts.iloc[i], ends.iloc[i], closed="both")
                # Same fallback as InMemory: no or null filepath -> the
                # row's interval (#225).
                path = paths.iloc[i] if paths is not None else None
                yield CatalogRow(
                    filepath=str(interval) if pd.isna(path) else str(path),
                    geometry=geoms[i],
                    interval=interval,
                    crs=self.crs,
                    extras=extras,
                )

    def _arrow_reader(self, batch_size: int) -> Any:
        """Record-batch reader over the relation, across DuckDB versions.

        ``to_arrow_reader`` is the current API; ``fetch_arrow_reader``
        is its deprecated pre-1.x-series spelling.
        """
        to_reader = getattr(self.relation, "to_arrow_reader", None)
        if to_reader is not None:
            return to_reader(batch_size)
        return self.relation.fetch_arrow_reader(batch_size)

    def iter_slices(self, *, resolution: tuple[float, float]) -> Iterator[GeoSlice]:
        """Yield one `GeoSlice` per row at the given target resolution.

        Lazy in shape but materialising in practice (delegates to
        `iter_rows`). For very large catalogs, prefer to ``query`` down
        first.

        Args:
            resolution: ``(x_res, y_res)`` in CRS units, baked into
                every emitted slice.

        Yields:
            `GeoSlice` instances in catalog row order.
        """
        # Same per-row rules as InMemory (degenerate axes widened to one
        # pixel, missing footprints skipped); see `_footprint_slices`.
        yield from _footprint_slices(
            ((row.geometry, row.interval) for row in self.iter_rows()),
            resolution,
            self.crs,
        )

    # ── properties + persistence ─────────────────────────────────────────

    @cached_property
    def total_bounds(self) -> tuple[float, float, float, float]:
        """Union bbox over the relation — one SQL aggregate, not a scan.

        Returns:
            ``(xmin, ymin, xmax, ymax)`` in catalog-CRS units. Four
            NaNs for an empty catalog.
        """
        with self._locked():
            df = self.relation.aggregate(
                "MIN(ST_XMin(geometry)) AS xmin, "
                "MIN(ST_YMin(geometry)) AS ymin, "
                "MAX(ST_XMax(geometry)) AS xmax, "
                "MAX(ST_YMax(geometry)) AS ymax"
            ).df()
        if pd.isna(df["xmin"].iloc[0]):
            return (np.nan, np.nan, np.nan, np.nan)
        return (
            float(df["xmin"].iloc[0]),
            float(df["ymin"].iloc[0]),
            float(df["xmax"].iloc[0]),
            float(df["ymax"].iloc[0]),
        )

    @cached_property
    def temporal_extent(self) -> pd.Interval | None:
        """Tightest interval over the relation — one SQL aggregate.

        Returns:
            ``pd.Interval(min(start_time), max(end_time), closed='both')``,
            or ``None`` for an empty catalog.
        """
        with self._locked():
            df = self.relation.aggregate(
                "MIN(start_time) AS tmin, MAX(end_time) AS tmax"
            ).df()
        if pd.isna(df["tmin"].iloc[0]):
            return None
        return pd.Interval(
            to_naive_utc(df["tmin"].iloc[0]),
            to_naive_utc(df["tmax"].iloc[0]),
            closed="both",
        )

    @cached_property
    def _time_literal(self) -> str:
        """SQL literal type matching ``end_time``: TIMESTAMPTZ or TIMESTAMP."""
        with self._locked():
            types = dict(zip(self.relation.columns, self.relation.types, strict=True))
        col_type = str(types.get("end_time", "")).upper()
        return "TIMESTAMPTZ" if "TIME ZONE" in col_type else "TIMESTAMP"

    def to_geoparquet(
        self,
        path: str | Path,
        *,
        write_covering_bbox: bool = True,
    ) -> None:
        """Persist the relation as a GeoParquet file.

        Materialises the relation, then routes through the existing
        `geopandas` writer so the resulting Parquet carries proper
        GeoParquet metadata (column CRS, bbox covering struct in 1.1).
        DuckDB's native GeoParquet writer is newer and less battle-tested
        — going through geopandas avoids that adoption caveat (§10.2 of
        the design plan).

        Args:
            path: Destination path.
            write_covering_bbox: Emit the per-row bbox covering struct
                that GeoParquet 1.1 readers (DuckDB, geopandas) use for
                predicate pushdown. Default True.
        """
        from geocatalog._src.storage.parquet import to_geoparquet as _write

        _write(
            self.materialize(),
            path,
            write_covering_bbox=write_covering_bbox,
        )

    def sql(self, where: str) -> DuckDBGeoCatalog:
        """Apply an arbitrary SQL ``WHERE`` clause — escape hatch.

        Lets users write predicates the structured `query` API doesn't
        cover (``cloud_pct < 5 AND sensor = 'S2A'``). The result is
        still a `DuckDBGeoCatalog`, so further `query` / `intersect` /
        `union` calls chain off it.

        Warning:
            ``where`` is spliced into the SQL as written — it is not
            parameterised or escaped. Pass trusted input only; never
            build it from user-supplied strings.

        Args:
            where: The body of a SQL ``WHERE`` clause, *without* the
                ``WHERE`` keyword. Column names available are whatever
                the underlying relation has.

        Returns:
            A filtered `DuckDBGeoCatalog`.
        """
        with self._locked():
            filtered = self.relation.filter(where)
        return self._derive(filtered, keeps_rows=True)

    @cached_property
    def _row_count(self) -> int:
        """Cached row count from one COUNT(*) query."""
        with self._locked():
            df = self.relation.aggregate("COUNT(*) AS n").df()
        return int(df["n"].iloc[0])

    def __len__(self) -> int:
        """Number of rows — cached after one COUNT(*) query."""
        self._require_open_con()
        return self._row_count

    def __repr__(self) -> str:
        return f"DuckDBGeoCatalog(kind={self.kind!r}, crs={self.crs.to_string()!r})"

    def get_config(self) -> dict[str, Any]:
        """JSON-serialisable summary — kind, row count, CRS.

        Returns:
            ``{"kind": str, "len": int, "crs": str, "engine": "duckdb"}``
            (plus ``"backend"``, the deprecated name of ``"kind"``).
            ``len`` triggers a count query — comparable shape to
            `InMemoryGeoCatalog.get_config` but with a SQL hop.
        """
        return {
            "kind": self.kind,
            "len": len(self),
            "crs": crs_config_string(self.crs),
            "engine": "duckdb",
            "backend": self.kind,  # deprecated key, kept for one release
        }

gdf cached property

Materialise the relation as a gpd.GeoDataFrame.

Cached — the first access executes the query; subsequent accesses are O(1). This is the eager bridge that lets loaders written against the in-memory backend work unchanged. For streaming/scale callers, prefer iter_rows.

temporal_extent cached property

Tightest interval over the relation — one SQL aggregate.

Returns:

Type Description
Interval | None

pd.Interval(min(start_time), max(end_time), closed='both'),

Interval | None

or None for an empty catalog.

total_bounds cached property

Union bbox over the relation — one SQL aggregate, not a scan.

Returns:

Type Description
float

(xmin, ymin, xmax, ymax) in catalog-CRS units. Four

float

NaNs for an empty catalog.

__len__()

Number of rows — cached after one COUNT(*) query.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/duckdb_backend.py
def __len__(self) -> int:
    """Number of rows — cached after one COUNT(*) query."""
    self._require_open_con()
    return self._row_count

close()

Close this catalog's DuckDB connection if it owns it.

No-op for derived catalogs (from query / intersect / union / sql) — they share the owner's connection and closing them would invalidate sibling derivations. Use the owning catalog's close, or a context manager on the owning instance, to tear down the connection. A derived catalog used as a context manager closes its owner on __exit__.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/duckdb_backend.py
def close(self) -> None:
    """Close this catalog's DuckDB connection if it owns it.

    No-op for derived catalogs (from `query` / `intersect` / `union`
    / `sql`) — they share the owner's connection and closing them
    would invalidate sibling derivations. Use the *owning* catalog's
    ``close``, or a context manager on the owning instance, to tear
    down the connection. A derived catalog used as a context
    manager closes its owner on ``__exit__``.
    """
    with self._lock:
        if self._owns_con and self.con is not None:
            self.con.close()
            self.con = None

from_memory(catalog, *, con=None) classmethod

Register an InMemoryGeoCatalog as a DuckDB relation.

Useful for upgrading a small in-RAM catalog into the SQL surface (e.g. to spatial-join two in-memory catalogs in parallel) without going through a Parquet round-trip.

Parameters:

Name Type Description Default
catalog InMemoryGeoCatalog

The in-memory catalog to wrap.

required
con DuckDBPyConnection | None

Optional DuckDB connection to register into. A fresh in-memory connection is created if omitted; ownership of an externally supplied connection stays with the caller (close is a no-op for it).

None

Returns:

Type Description
DuckDBGeoCatalog

A DuckDBGeoCatalog over the same rows. The relation scans a

DuckDBGeoCatalog

WKB-encoded copy of the gdf, so later changes to the gdf are

DuckDBGeoCatalog

not seen.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/duckdb_backend.py
@classmethod
def from_memory(
    cls,
    catalog: InMemoryGeoCatalog,
    *,
    con: duckdb_mod.DuckDBPyConnection | None = None,
) -> DuckDBGeoCatalog:
    """Register an `InMemoryGeoCatalog` as a DuckDB relation.

    Useful for upgrading a small in-RAM catalog into the SQL surface
    (e.g. to spatial-join two in-memory catalogs in parallel) without
    going through a Parquet round-trip.

    Args:
        catalog: The in-memory catalog to wrap.
        con: Optional DuckDB connection to register into. A fresh
            in-memory connection is created if omitted; ownership
            of an externally supplied connection stays with the
            caller (close is a no-op for it).

    Returns:
        A `DuckDBGeoCatalog` over the same rows. The relation scans a
        WKB-encoded copy of the gdf, so later changes to the gdf are
        not seen.
    """
    dd = _require_duckdb()
    owns_con = con is None
    if con is None:
        con = dd.connect()
    try:
        df = _gdf_to_arrow_df(catalog.gdf)
        # Every statement on ``con`` — including the extension LOAD —
        # holds its lock: ``con`` may be shared with a catalog that is
        # executing in another thread (#224).
        with _con_lock(con):
            _ensure_spatial(con)
            # `from_df` scans the DataFrame object directly: no named
            # view or registration, so nothing another call can
            # overwrite (named views keyed on `id()` were rebound when
            # CPython reused an id; #222).
            relation = con.from_df(df).project(
                "* EXCLUDE (geometry), ST_GeomFromWKB(geometry) AS geometry"
            )
    except BaseException:
        if owns_con:
            con.close()
        raise
    return cls(
        relation,
        con=con,
        crs=catalog.gdf.crs,
        kind=catalog.kind,
        _owns_con=owns_con,
    )

get_config()

JSON-serialisable summary — kind, row count, CRS.

Returns:

Type Description
``{"kind"

str, "len": int, "crs": str, "engine": "duckdb"}``

dict[str, Any]

(plus "backend", the deprecated name of "kind").

dict[str, Any]

len triggers a count query — comparable shape to

dict[str, Any]

InMemoryGeoCatalog.get_config but with a SQL hop.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/duckdb_backend.py
def get_config(self) -> dict[str, Any]:
    """JSON-serialisable summary — kind, row count, CRS.

    Returns:
        ``{"kind": str, "len": int, "crs": str, "engine": "duckdb"}``
        (plus ``"backend"``, the deprecated name of ``"kind"``).
        ``len`` triggers a count query — comparable shape to
        `InMemoryGeoCatalog.get_config` but with a SQL hop.
    """
    return {
        "kind": self.kind,
        "len": len(self),
        "crs": crs_config_string(self.crs),
        "engine": "duckdb",
        "backend": self.kind,  # deprecated key, kept for one release
    }

intersect(other, *, spatial_only=False)

Cross-catalog AND via SQL spatial join.

Translates to SELECT ... FROM self JOIN other ON ST_Intersects(self.geometry, other.geometry) [AND interval-overlap]. The DuckDB planner builds an R-tree on the smaller side and probes with the larger; cost scales as O(n log n + m log n) versus gpd.overlay's near-quadratic blow-up at scale.

Parameters:

Name Type Description Default
other DuckDBGeoCatalog | InMemoryGeoCatalog

Another catalog. An InMemoryGeoCatalog is registered via from_memory before joining. CRS is reprojected into self.crs if the two differ — done at registration time, not in SQL, so the join itself runs in one CRS.

required
spatial_only bool

If True, drop the temporal predicate.

False

Returns:

Type Description
DuckDBGeoCatalog

A new DuckDBGeoCatalog over the joined relation. Footprints

DuckDBGeoCatalog

are clipped to ST_Intersection; intervals to the

DuckDBGeoCatalog

tightest overlap of left and right (or the left interval

DuckDBGeoCatalog

when spatial_only=True).

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/duckdb_backend.py
def intersect(
    self,
    other: DuckDBGeoCatalog | InMemoryGeoCatalog,
    *,
    spatial_only: bool = False,
) -> DuckDBGeoCatalog:
    """Cross-catalog AND via SQL spatial join.

    Translates to ``SELECT ... FROM self JOIN other ON
    ST_Intersects(self.geometry, other.geometry) [AND interval-overlap]``.
    The DuckDB planner builds an R-tree on the smaller side and
    probes with the larger; cost scales as ``O(n log n + m log n)``
    versus `gpd.overlay`'s near-quadratic blow-up at scale.

    Args:
        other: Another catalog. An `InMemoryGeoCatalog` is registered
            via `from_memory` before joining. CRS is reprojected
            into ``self.crs`` if the two differ — done at registration
            time, not in SQL, so the join itself runs in one CRS.
        spatial_only: If True, drop the temporal predicate.

    Returns:
        A new `DuckDBGeoCatalog` over the joined relation. Footprints
        are clipped to ``ST_Intersection``; intervals to the
        tightest overlap of left and right (or the left interval
        when ``spatial_only=True``).
    """
    con = self._require_open_con()
    other_duck = _coerce_to_duckdb(other, con=con, target_crs=self.crs)

    temporal = (
        ""
        if spatial_only
        else (" AND L.end_time >= R.start_time AND L.start_time <= R.end_time")
    )
    time_select = (
        "L.start_time AS start_time, L.end_time AS end_time"
        if spatial_only
        else (
            "GREATEST(L.start_time, R.start_time) AS start_time, "
            "LEAST   (L.end_time,   R.end_time)   AS end_time"
        )
    )
    # GEOS intersection is not bit-symmetric under operand order for
    # near-degenerate sliver overlaps (geocatalog#40) — canonicalise each
    # pair's operand order by WKB bytes, mirroring the in-memory
    # engine's `_symmetric_intersection`, so `a.intersect(b)` and
    # `b.intersect(a)` compute identical geometry per row pair.
    # Relation-API join on aliased relations rather than SQL over
    # named views: the result holds both inputs by reference, so no
    # later `intersect` / `union` can rebind it (#222) and no views
    # accumulate on the connection. `other` was coerced above, before
    # taking our lock, so we never hold two connections' locks.
    with self._locked():
        joined = self._join(other_duck, temporal, time_select)
    return self._derive(joined)

iter_rows(*, batch_size=1024)

Stream rows as CatalogRow instances in Arrow batches.

Streams the relation through DuckDB's Arrow record-batch reader, so time-to-first-row and peak memory are O(batch_size) — not O(len(catalog)) as the previous .df()-materialising implementation was. Geometry WKB is decoded one vectorised shapely.from_wkb call per batch.

Parameters:

Name Type Description Default
batch_size int

Rows per Arrow record batch. Bounds both the first-row latency and the peak memory of a full iteration.

1024

Yields:

Type Description
CatalogRow

CatalogRow with geometry decoded from WKB.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/duckdb_backend.py
def iter_rows(self, *, batch_size: int = 1024) -> Iterator[CatalogRow]:
    """Stream rows as `CatalogRow` instances in Arrow batches.

    Streams the relation through DuckDB's Arrow record-batch reader,
    so time-to-first-row and peak memory are ``O(batch_size)`` —
    not ``O(len(catalog))`` as the previous ``.df()``-materialising
    implementation was. Geometry WKB is decoded one vectorised
    `shapely.from_wkb` call per batch.

    Args:
        batch_size: Rows per Arrow record batch. Bounds both the
            first-row latency and the peak memory of a full
            iteration.

    Yields:
        `CatalogRow` with ``geometry`` decoded from WKB.
    """
    if batch_size < 1:
        raise ValueError(f"batch_size must be >= 1; got {batch_size}")
    # The lock is held for the whole iteration: any other query on the
    # connection would close this stream. Other threads using the same
    # catalog wait until the iteration finishes (or the generator is
    # closed); don't block inside the loop on such a thread.
    with self._locked():
        yield from self._iter_batches(batch_size)

iter_slices(*, resolution)

Yield one GeoSlice per row at the given target resolution.

Lazy in shape but materialising in practice (delegates to iter_rows). For very large catalogs, prefer to query down first.

Parameters:

Name Type Description Default
resolution tuple[float, float]

(x_res, y_res) in CRS units, baked into every emitted slice.

required

Yields:

Type Description
GeoSlice

GeoSlice instances in catalog row order.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/duckdb_backend.py
def iter_slices(self, *, resolution: tuple[float, float]) -> Iterator[GeoSlice]:
    """Yield one `GeoSlice` per row at the given target resolution.

    Lazy in shape but materialising in practice (delegates to
    `iter_rows`). For very large catalogs, prefer to ``query`` down
    first.

    Args:
        resolution: ``(x_res, y_res)`` in CRS units, baked into
            every emitted slice.

    Yields:
        `GeoSlice` instances in catalog row order.
    """
    # Same per-row rules as InMemory (degenerate axes widened to one
    # pixel, missing footprints skipped); see `_footprint_slices`.
    yield from _footprint_slices(
        ((row.geometry, row.interval) for row in self.iter_rows()),
        resolution,
        self.crs,
    )

materialize()

Execute the relation and wrap the result as an InMemoryGeoCatalog.

Decodes WKB to shapely geometries and rebuilds the IntervalIndex from start_time / end_time. Useful for moving the result into operations that need the full pandas / geopandas surface (custom merges, plotting, debugging) but defeats the lazy story — call after a selective query.

Returns:

Type Description
InMemoryGeoCatalog

An InMemoryGeoCatalog over the materialised rows, same

InMemoryGeoCatalog

CRS, same kind.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/duckdb_backend.py
def materialize(self) -> InMemoryGeoCatalog:
    """Execute the relation and wrap the result as an `InMemoryGeoCatalog`.

    Decodes WKB to shapely geometries and rebuilds the
    ``IntervalIndex`` from ``start_time`` / ``end_time``. Useful for
    moving the result into operations that need the full pandas /
    geopandas surface (custom merges, plotting, debugging) but
    defeats the lazy story — call after a selective ``query``.

    Returns:
        An `InMemoryGeoCatalog` over the materialised rows, same
        CRS, same kind.
    """
    with self._locked():
        df = self.relation.df()
    return _df_to_inmemory(df, crs=self.crs, kind=self.kind)

open(source, *, kind=None, crs=None, retries=3, storage_options=None, strict=False) classmethod

Open a GeoParquet file (or directory of shards) lazily.

Reads the source via DuckDB's read_parquet; the relation carries the schema but no rows are materialised until queried. Local paths are supported directly. URI sources with s3:// (s3a://, s3n://), gs://, gcs://, http://, https://, r2:// or hf:// auto-load DuckDB's httpfs extension; az://, azure:// and abfss:// auto-load DuckDB's azure extension.

CRS is recovered from the GeoParquet column metadata (PROJJSON) for local files only — the metadata reader uses pyarrow.parquet.read_metadata over a local Path. For URI sources (s3://, https://, hf://, …) the auto-detect cannot reach the remote object and silently falls back to the EPSG:4326 default; a UserWarning is emitted in that case. Pass crs= explicitly for remote sources to avoid the fallback. (Remote GeoParquet CRS introspection would need an fsspec/pyarrow filesystem hookup and is tracked separately.)

The kind is recovered from the reserved _backend column written by to_geoparquet; ad-hoc parquet files lacking it default to "raster" unless overridden.

Parameters:

Name Type Description Default
source str | Path

Path or URI. A directory or glob (shards/*.parquet) is read as one virtual table.

required
kind CatalogKind | None

Kind override (loader dispatch). None reads the _backend column, falling back to "raster".

None
crs Any | None

CRS override. None reads the GeoParquet PROJJSON metadata for local files; falls back to EPSG:4326 if neither is present (noisy default rather than silent coercion). For URI sources, None always falls back to the default — pass crs= explicitly.

None
retries int

Number of retries for transient remote I/O failures. 0 disables retry/backoff.

3
storage_options dict[str, Any] | None

Not supported by this backend — DuckDB reads URIs natively via its httpfs / azure extensions and does not accept an fsspec-style credential mapping. Pass None; configure DuckDB secrets (or pre-set env vars) before calling open. Use engine='memory' if you need fsspec-backed reads.

None
strict bool

If True, raise CatalogMetadataError instead of falling back when the _backend column is missing / unreadable (and kind= was not passed) or the GeoParquet geo metadata is unreadable (and crs= was not passed). Remote URIs cannot be introspected at all, so strict=True requires an explicit crs= for them. Explicit kind= / crs= overrides bypass the corresponding check.

False

Returns:

Type Description
DuckDBGeoCatalog

A DuckDBGeoCatalog over the relation.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/duckdb_backend.py
@classmethod
@renamed_kwargs(backend="kind")
def open(
    cls,
    source: str | Path,
    *,
    kind: CatalogKind | None = None,
    crs: Any | None = None,
    retries: int = 3,
    storage_options: dict[str, Any] | None = None,
    strict: bool = False,
) -> DuckDBGeoCatalog:
    """Open a GeoParquet file (or directory of shards) lazily.

    Reads the source via DuckDB's `read_parquet`; the relation
    carries the schema but no rows are materialised until queried.
    Local paths are supported directly. URI sources with ``s3://``
    (``s3a://``, ``s3n://``), ``gs://``, ``gcs://``, ``http://``,
    ``https://``, ``r2://`` or ``hf://`` auto-load DuckDB's `httpfs`
    extension; ``az://``, ``azure://`` and ``abfss://`` auto-load
    DuckDB's `azure` extension.

    CRS is recovered from the GeoParquet column metadata (PROJJSON)
    for **local files only** — the metadata reader uses
    `pyarrow.parquet.read_metadata` over a local `Path`. For URI
    sources (``s3://``, ``https://``, ``hf://``, …) the auto-detect
    cannot reach the remote object and silently falls back to the
    ``EPSG:4326`` default; a `UserWarning` is emitted in that case.
    Pass ``crs=`` explicitly for remote sources to avoid the
    fallback. (Remote GeoParquet CRS introspection would need an
    fsspec/pyarrow filesystem hookup and is tracked separately.)

    The kind is recovered from the reserved ``_backend``
    column written by `to_geoparquet`; ad-hoc parquet files lacking
    it default to ``"raster"`` unless overridden.

    Args:
        source: Path or URI. A directory or glob (``shards/*.parquet``)
            is read as one virtual table.
        kind: Kind override (loader dispatch). ``None`` reads the
            ``_backend`` column, falling back to ``"raster"``.
        crs: CRS override. ``None`` reads the GeoParquet PROJJSON
            metadata for local files; falls back to ``EPSG:4326`` if
            neither is present (noisy default rather than silent
            coercion). For URI sources, ``None`` always falls back
            to the default — pass ``crs=`` explicitly.
        retries: Number of retries for transient remote I/O failures.
            ``0`` disables retry/backoff.
        storage_options: Not supported by this backend — DuckDB reads
            URIs natively via its `httpfs` / `azure` extensions and
            does not accept an fsspec-style credential mapping. Pass
            ``None``; configure DuckDB secrets (or pre-set env vars)
            before calling `open`. Use ``engine='memory'`` if you need
            fsspec-backed reads.
        strict: If ``True``, raise `CatalogMetadataError` instead of
            falling back when the ``_backend`` column is missing /
            unreadable (and ``kind=`` was not passed) or the
            GeoParquet ``geo`` metadata is unreadable (and ``crs=``
            was not passed). Remote URIs cannot be introspected at
            all, so ``strict=True`` requires an explicit ``crs=``
            for them. Explicit ``kind=`` / ``crs=`` overrides
            bypass the corresponding check.

    Returns:
        A `DuckDBGeoCatalog` over the relation.
    """
    if storage_options is not None:
        raise ValueError(
            "DuckDBGeoCatalog does not support storage_options. Use "
            "open_catalog(source, engine='memory', storage_options=...) "
            "for fsspec-backed reads (loads the full catalog into memory), "
            "or configure DuckDB credentials directly."
        )
    if kind is not None:  # fail before a connection exists
        check_kind(kind, "DuckDBGeoCatalog")
    dd = _require_duckdb()
    con = dd.connect()
    try:
        spatial_ok = _ensure_spatial(con)
        source_str = _read_parquet_source(source)
        partitioned = _is_partitioned_source(source)
        scheme = _scheme(source)
        extension = DUCKDB_EXTENSIONS.get(scheme or "")
        if extension is not None:
            con.execute(f"INSTALL {extension}")
            con.execute(f"LOAD {extension}")
        if crs is None:
            if scheme is not None and strict:
                raise CatalogMetadataError(
                    f"cannot auto-detect CRS from remote URI {source_str}: "
                    "GeoParquet metadata introspection only works for "
                    "local files. Pass crs= explicitly when strict=True."
                )
            if scheme is not None:
                warnings.warn(
                    f"DuckDBGeoCatalog.open({source_str!r}): cannot auto-detect "
                    "CRS from a remote URI; falling back to EPSG:4326. Pass "
                    "`crs=` explicitly for remote sources to avoid silent "
                    "default coercion.",
                    UserWarning,
                    stacklevel=2,
                )
            crs = retry_transient_io(
                _read_geoparquet_crs,
                source,
                default="EPSG:4326",
                strict=strict,
                retries=retries,
            )
        if kind is None:
            kind = retry_transient_io(
                _read_backend_tag,
                con,
                source_str,
                default="raster",
                partitioned=partitioned,
                strict=strict,
                retries=retries,
            )
        retry_transient_io(
            _check_schema_version,
            con,
            source_str,
            partitioned=partitioned,
            retries=retries,
        )
        # `con.read_parquet` builds a lazy scan: nothing is read until a
        # query executes, and filters are pushed into the Parquet scan.
        # (`con.sql(..., params=...)` executes immediately and returns a
        # materialised relation — the whole artifact, remote included,
        # was pulled at open; #221.) The path is passed as a value, not
        # interpolated, so apostrophes and hostile input are safe.
        # `hive_partitioning` is conditional: enabling it on a single
        # file under a `key=value` directory would inject a synthetic
        # partition column into the schema.
        relation = retry_transient_io(
            con.read_parquet,
            source_str,
            hive_partitioning=partitioned,
            retries=retries,
        )
        # Inside the cleanup block: a stored `_backend` the constructor
        # rejects must not leak the connection either.
        catalog = cls(relation, con=con, crs=crs, kind=kind, _owns_con=True)
        catalog._bbox_covering = _has_bbox_covering(relation)
        catalog._spatial_available = spatial_ok
    except BaseException:
        # Setup failed (bad extension load, schema mismatch, IO error,
        # invalid kind); don't leak the freshly opened connection.
        con.close()
        raise
    return catalog

query(slice_=None, *, bounds=None, crs=None, time=None)

SQL spatial + temporal filter — lazy, returns a new relation.

Builds a WHERE clause that DuckDB can push down to the Parquet reader (bbox-column predicates skip whole row-groups). Mirrors InMemoryGeoCatalog.query; AOI bounds in a different CRS are reprojected internally before being interpolated into the SQL.

Parameters:

Name Type Description Default
slice_ GeoSlice | None

A GeoSlice whose bbox + interval drive the filter. Mutually exclusive with the keyword args.

None
bounds tuple[float, float, float, float] | None

(xmin, ymin, xmax, ymax) in crs units.

None
crs Any | None

CRS of bounds; defaults to the catalog CRS.

None
time tuple[Any, Any] | Interval | None

Either a (start, end) pair (pd.Timestamp-like) or a pd.Interval. None skips the temporal filter.

None

Returns:

Type Description
DuckDBGeoCatalog

A new DuckDBGeoCatalog over the filtered relation. May be

DuckDBGeoCatalog

empty; len() triggers a count query.

Raises:

Type Description
TypeError

If both slice_ and any of (bounds, time) are passed.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/duckdb_backend.py
def query(
    self,
    slice_: GeoSlice | None = None,
    *,
    bounds: tuple[float, float, float, float] | None = None,
    crs: Any | None = None,
    time: tuple[Any, Any] | pd.Interval | None = None,
) -> DuckDBGeoCatalog:
    """SQL spatial + temporal filter — lazy, returns a new relation.

    Builds a ``WHERE`` clause that DuckDB can push down to the
    Parquet reader (bbox-column predicates skip whole row-groups).
    Mirrors `InMemoryGeoCatalog.query`; AOI bounds in a different
    CRS are reprojected internally before being interpolated into
    the SQL.

    Args:
        slice_: A `GeoSlice` whose bbox + interval drive the filter.
            Mutually exclusive with the keyword args.
        bounds: ``(xmin, ymin, xmax, ymax)`` in ``crs`` units.
        crs: CRS of ``bounds``; defaults to the catalog CRS.
        time: Either a ``(start, end)`` pair (`pd.Timestamp`-like)
            or a `pd.Interval`. ``None`` skips the temporal filter.

    Returns:
        A new `DuckDBGeoCatalog` over the filtered relation. May be
        empty; ``len()`` triggers a count query.

    Raises:
        TypeError: If both ``slice_`` and any of (``bounds``,
            ``time``) are passed.
    """
    self._require_open_con()
    if slice_ is not None and (
        bounds is not None or time is not None or crs is not None
    ):
        raise TypeError(
            "query: pass either slice_ or (bounds + crs + time), not both; "
            "a GeoSlice carries its own crs"
        )
    if slice_ is not None:
        q_bounds = slice_.bounds
        q_crs = slice_.crs
        q_interval = slice_.interval
    else:
        if bounds is None and time is None:
            return self._derive(self.relation, keeps_rows=True)
        q_bounds = bounds
        q_crs = crs
        q_interval = _coerce_interval(time) if time is not None else None

    # The relation API's `.filter()` takes a SQL string, so these
    # predicates are interpolated rather than bound as parameters.
    # Every interpolated value is force-coerced to a safe literal
    # first (float / `pd.Timestamp.isoformat`) — never interpolate
    # a raw user string here.
    where: list[str] = []
    if q_bounds is not None:
        # One envelope, or two when the AOI crosses the antimeridian.
        # With a bbox covering column, a plain comparison on it comes
        # first: DuckDB pushes it into the Parquet scan (row-group
        # pruning), which it cannot do for ST_Intersects (#221).
        envelopes = _query_envelopes(q_bounds, q_crs, self.crs)
        terms = []
        for xmin, ymin, xmax, ymax in envelopes:
            st = (
                f"ST_Intersects(geometry, "
                f"ST_MakeEnvelope({xmin!r}, {ymin!r}, {xmax!r}, {ymax!r}))"
            )
            if self._bbox_covering:
                st = (
                    f"bbox.xmax >= {xmin!r} AND bbox.xmin <= {xmax!r} AND "
                    f"bbox.ymax >= {ymin!r} AND bbox.ymin <= {ymax!r} AND {st}"
                )
            terms.append(f"({st})")
        where.append(f"({' OR '.join(terms)})")
    if q_interval is not None:
        # Bounds are naive UTC (`_coerce_interval` / GeoSlice). Type the
        # literal to match the column so DuckDB never casts through the
        # session time zone: a TIMESTAMP literal compared with a
        # TIMESTAMPTZ column would be read in the host's zone.
        literal = self._time_literal
        suffix = "+00:00" if literal == "TIMESTAMPTZ" else ""
        t_lo = to_naive_utc(q_interval.left).isoformat() + suffix
        t_hi = to_naive_utc(q_interval.right).isoformat() + suffix
        where.append(f"end_time >= {literal} '{t_lo}'")
        where.append(f"start_time <= {literal} '{t_hi}'")

    if not where:
        return self._derive(self.relation, keeps_rows=True)
    clause = " AND ".join(where)
    with self._locked():
        filtered = self.relation.filter(clause)
    return self._derive(filtered, keeps_rows=True)

sql(where)

Apply an arbitrary SQL WHERE clause — escape hatch.

Lets users write predicates the structured query API doesn't cover (cloud_pct < 5 AND sensor = 'S2A'). The result is still a DuckDBGeoCatalog, so further query / intersect / union calls chain off it.

Warning

where is spliced into the SQL as written — it is not parameterised or escaped. Pass trusted input only; never build it from user-supplied strings.

Parameters:

Name Type Description Default
where str

The body of a SQL WHERE clause, without the WHERE keyword. Column names available are whatever the underlying relation has.

required

Returns:

Type Description
DuckDBGeoCatalog

A filtered DuckDBGeoCatalog.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/duckdb_backend.py
def sql(self, where: str) -> DuckDBGeoCatalog:
    """Apply an arbitrary SQL ``WHERE`` clause — escape hatch.

    Lets users write predicates the structured `query` API doesn't
    cover (``cloud_pct < 5 AND sensor = 'S2A'``). The result is
    still a `DuckDBGeoCatalog`, so further `query` / `intersect` /
    `union` calls chain off it.

    Warning:
        ``where`` is spliced into the SQL as written — it is not
        parameterised or escaped. Pass trusted input only; never
        build it from user-supplied strings.

    Args:
        where: The body of a SQL ``WHERE`` clause, *without* the
            ``WHERE`` keyword. Column names available are whatever
            the underlying relation has.

    Returns:
        A filtered `DuckDBGeoCatalog`.
    """
    with self._locked():
        filtered = self.relation.filter(where)
    return self._derive(filtered, keeps_rows=True)

to_geoparquet(path, *, write_covering_bbox=True)

Persist the relation as a GeoParquet file.

Materialises the relation, then routes through the existing geopandas writer so the resulting Parquet carries proper GeoParquet metadata (column CRS, bbox covering struct in 1.1). DuckDB's native GeoParquet writer is newer and less battle-tested — going through geopandas avoids that adoption caveat (§10.2 of the design plan).

Parameters:

Name Type Description Default
path str | Path

Destination path.

required
write_covering_bbox bool

Emit the per-row bbox covering struct that GeoParquet 1.1 readers (DuckDB, geopandas) use for predicate pushdown. Default True.

True
Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/duckdb_backend.py
def to_geoparquet(
    self,
    path: str | Path,
    *,
    write_covering_bbox: bool = True,
) -> None:
    """Persist the relation as a GeoParquet file.

    Materialises the relation, then routes through the existing
    `geopandas` writer so the resulting Parquet carries proper
    GeoParquet metadata (column CRS, bbox covering struct in 1.1).
    DuckDB's native GeoParquet writer is newer and less battle-tested
    — going through geopandas avoids that adoption caveat (§10.2 of
    the design plan).

    Args:
        path: Destination path.
        write_covering_bbox: Emit the per-row bbox covering struct
            that GeoParquet 1.1 readers (DuckDB, geopandas) use for
            predicate pushdown. Default True.
    """
    from geocatalog._src.storage.parquet import to_geoparquet as _write

    _write(
        self.materialize(),
        path,
        write_covering_bbox=write_covering_bbox,
    )

union(other)

Cross-catalog OR via SQL UNION ALL.

self's CRS and kind win. other is reprojected into self.crs if needed before the union. Schemas must be compatible for the columns both sides share; extra columns on one side become NULL on the other.

Parameters:

Name Type Description Default
other DuckDBGeoCatalog | InMemoryGeoCatalog

Catalog to concatenate. Reprojected if needed.

required

Returns:

Type Description
DuckDBGeoCatalog

A new DuckDBGeoCatalog over the union relation.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/backends/duckdb_backend.py
def union(self, other: DuckDBGeoCatalog | InMemoryGeoCatalog) -> DuckDBGeoCatalog:
    """Cross-catalog OR via SQL ``UNION ALL``.

    ``self``'s CRS and kind win. ``other`` is reprojected
    into ``self.crs`` if needed before the union. Schemas must be
    compatible for the columns both sides share; extra columns on
    one side become NULL on the other.

    Args:
        other: Catalog to concatenate. Reprojected if needed.

    Returns:
        A new `DuckDBGeoCatalog` over the union relation.
    """
    con = self._require_open_con()
    # Coerce before taking our lock (see `intersect`).
    other_duck = _coerce_to_duckdb(other, con=con, target_crs=self.crs)
    del con
    with self._locked():
        unioned = self._union_by_name(other_duck)
    return self._derive(unioned)

Rows

geocatalog.backends.CatalogRow dataclass

Backend-neutral view of a single catalog row.

Yielded by GeoCatalog.iter_rows; consumed by loaders and the geopatcher bridge. The dataclass exists so streaming code (DuckDB cursors, on-disk shards) can hand rows downstream without callers caring whether the row came from a gpd.GeoDataFrame or a SQL relation.

Attributes:

Name Type Description
filepath str

Path or URI of the indexed file. The loader resolves this with the configured reader class.

geometry BaseGeometry

Footprint polygon (or multipolygon) in crs units. Already decoded from WKB for DuckDB-backed catalogs.

interval Interval

Time window for the row, closed='both'.

crs CRS

Coordinate reference of geometry.

extras dict[str, Any]

Backend-specific metadata (layer, data_vars, time_var, …). Empty dict for rows that carry no extras.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/base.py
@dataclasses.dataclass(frozen=True)
class CatalogRow:
    """Backend-neutral view of a single catalog row.

    Yielded by `GeoCatalog.iter_rows`; consumed by loaders and the
    `geopatcher` bridge. The dataclass exists so streaming code
    (DuckDB cursors, on-disk shards) can hand rows downstream without
    callers caring whether the row came from a `gpd.GeoDataFrame` or a
    SQL relation.

    Attributes:
        filepath: Path or URI of the indexed file. The loader resolves
            this with the configured reader class.
        geometry: Footprint polygon (or multipolygon) in ``crs`` units.
            Already decoded from WKB for DuckDB-backed catalogs.
        interval: Time window for the row, ``closed='both'``.
        crs: Coordinate reference of ``geometry``.
        extras: Backend-specific metadata (``layer``, ``data_vars``,
            ``time_var``, …). Empty dict for rows that carry no extras.
    """

    filepath: str
    geometry: shapely.geometry.base.BaseGeometry
    interval: pd.Interval
    crs: pyproj.CRS
    extras: dict[str, Any] = dataclasses.field(default_factory=dict)

    @property
    def state(self) -> StateFields | None:
        """The row's model-state fields, typed; ``None`` for a non-state row.

        A row is a state row when it has a ``run_time`` extra
        (`is_state_frame`). Reads the reserved state columns out of
        ``extras``, with nulls as ``None`` whatever the backend returned
        (``NaN``, ``NaT``, a numpy array for ``parents``).
        """
        if not is_state_frame(self.extras):
            return None
        get = self.extras.get
        run_time = get("run_time")
        run_ts = (
            None if run_time is None or pd.isna(run_time) else pd.Timestamp(run_time)
        )
        return StateFields(
            kind=state_text(get("kind")),
            run_time=None if run_ts is None else to_naive_utc(run_ts),
            member=state_text(get("member")),
            producer=state_text(get("producer")),
            parents=tuple(state_parents(get("parents")) or ()),
        )

state property

The row's model-state fields, typed; None for a non-state row.

A row is a state row when it has a run_time extra (is_state_frame). Reads the reserved state columns out of extras, with nulls as None whatever the backend returned (NaN, NaT, a numpy array for parents).

Errors

Errors about a catalog's state or artifacts derive from GeoCatalogError and from the builtin callers caught before (ValueError / RuntimeError). Invalid arguments raise the builtin ValueError / TypeError; see the parameter vocabulary.

geocatalog.backends.GeoCatalogError

Bases: Exception

Base class of the errors about a catalog's state or its artifacts.

A closed catalog, unreadable metadata, an unsupported schema version. Invalid arguments (an unknown kind or engine, malformed bounds) raise the builtin ValueError / TypeError, and an unparsable CRS raises pyproj.exceptions.CRSError, so catch those as well when you want every failure. Each subclass also derives from the builtin a caller would have caught before the hierarchy existed (ValueError, RuntimeError), so except ValueError keeps working.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/base.py
class GeoCatalogError(Exception):
    """Base class of the errors about a catalog's state or its artifacts.

    A closed catalog, unreadable metadata, an unsupported schema version.
    Invalid *arguments* (an unknown ``kind`` or ``engine``, malformed
    ``bounds``) raise the builtin `ValueError` / `TypeError`, and an
    unparsable CRS raises ``pyproj.exceptions.CRSError``, so catch those
    as well when you want every failure. Each subclass also derives from
    the builtin a caller would have caught before the hierarchy existed
    (`ValueError`, `RuntimeError`), so ``except ValueError`` keeps working.
    """

geocatalog.backends.CatalogSchemaError

Bases: GeoCatalogError, ValueError

A GeoParquet artifact has a _schema_version the reader can't load.

Raised when _schema_version exceeds SCHEMA_VERSION_CURRENT (the reader is older than the writer), or when a forward migration is missing for an older artifact. The message identifies the artifact's version and the reader's version so the user can decide whether to upgrade the library or run geocatalog migrate.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/base.py
class CatalogSchemaError(GeoCatalogError, ValueError):
    """A GeoParquet artifact has a `_schema_version` the reader can't load.

    Raised when ``_schema_version`` exceeds `SCHEMA_VERSION_CURRENT` (the
    reader is older than the writer), or when a forward migration is
    missing for an older artifact. The message identifies the artifact's
    version and the reader's version so the user can decide whether to
    upgrade the library or run ``geocatalog migrate``.
    """

geocatalog.backends.CatalogMetadataError

Bases: GeoCatalogError, ValueError

A catalog artifact's metadata could not be read or is missing.

Raised by the strict=True mode of the catalog open entry points when a GeoParquet artifact lacks the reserved _backend column, carries unreadable/malformed geo metadata, or its CRS cannot be parsed — instead of the default behaviour of logging a warning and falling back (kind="raster" / crs="EPSG:4326").

Source code in packages/geotoolz-catalog/src/geocatalog/_src/base.py
class CatalogMetadataError(GeoCatalogError, ValueError):
    """A catalog artifact's metadata could not be read or is missing.

    Raised by the `strict=True` mode of the catalog `open` entry points
    when a GeoParquet artifact lacks the reserved ``_backend`` column,
    carries unreadable/malformed ``geo`` metadata, or its CRS cannot be
    parsed — instead of the default behaviour of logging a warning and
    falling back (``kind="raster"`` / ``crs="EPSG:4326"``).
    """

geocatalog.backends.CatalogClosedError

Bases: GeoCatalogError, RuntimeError

A catalog was used after its connection was closed.

Raised by DuckDBGeoCatalog (and every catalog derived from it by query / filter) after close(). The DuckDB backend raises a subclass that also derives from duckdb.ConnectionException, which is what it raised before this class existed.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/base.py
class CatalogClosedError(GeoCatalogError, RuntimeError):
    """A catalog was used after its connection was closed.

    Raised by `DuckDBGeoCatalog` (and every catalog derived from it by
    ``query`` / ``filter``) after ``close()``. The DuckDB backend raises
    a subclass that also derives from ``duckdb.ConnectionException``,
    which is what it raised before this class existed.
    """