Source: https://gres.monicz.dev/guide/spatial/

# PostGIS

Gres reads and writes [PostGIS](https://postgis.net/documentation/) `geometry` and `geography` values in binary format without text round trips. With the `postgis` extra, rows decode into [gometry](https://gometry.monicz.dev/) objects carrying the database's CRS and edge model; without `gometry`, use `Decoding(geometry='exact')` for [EWKB carriers](https://gres.monicz.dev/guide/spatial/#exact-ewkb-transport).

```bash
pip install 'gres[postgis]'
```

The target database needs `CREATE EXTENSION postgis` with its types and functions on the session's `search_path`.

## Example

```python
import asyncio

import gometry as gm
from gres import Connection, scalar

# geometry(..., 4326): longitude and latitude joined by straight edges
WGS84 = gm.Space(crs=4326, model='planar')
# geography: great-circle edges
GEODETIC = gm.Space(crs=4326, model='spherical')


async def main() -> None:
    async with Connection() as db:
        await db.execute("""
            CREATE TEMP TABLE station(
                id int PRIMARY KEY,
                name text NOT NULL,
                location geometry(Point, 4326) NOT NULL
            );
            CREATE INDEX ON station USING gist ((location::geography));
        """)
        await db.copy_from_rows(
            'station',
            [
                (1, 'Harbour', gm.Point(10.74, 59.91, space=WGS84)),
                (2, 'Airport', gm.Point(11.10, 60.19, space=WGS84)),
                (3, 'Bergen', gm.Point(5.32, 60.39, space=WGS84)),
            ],
            columns=['id', 'name', 'location'],
        )

        here = gm.Point(10.75, 59.92, space=GEODETIC)
        nearby = await db.fetch_all(
            """SELECT name FROM station
               WHERE ST_DWithin(location::geography, $1, 50000)
               ORDER BY location::geography <-> $1""",
            (here,),
            row=scalar(str),
        )
        print(nearby)  # ['Harbour', 'Airport']

        harbour = await db.fetch_one(
            'SELECT location FROM station WHERE id = 1',
            row=scalar(gm.Geometry),
        )
        print(harbour.space.model, harbour.crs)  # planar EPSG:4326


asyncio.run(main())
```

`here` is spherical and binds to the `geography` parameter; the stored points are planar and bind to `geometry(Point, 4326)`. `ST_DWithin` on `geography` takes metres, and the expression index accelerates both the filter and `<->` ordering.

## `geometry`, `geography`, and gometry models

| PostGIS type | gometry model | Edges between vertices | Distance and area units in PostGIS |
| --- | --- | --- | --- |
| `geometry` | `planar` | Straight lines in the stored coordinates | The CRS's units: degrees for EPSG:4326, metres for most projected CRSs |
| `geography` | `spherical` | Great-circle arcs | Metres and square metres |

Values bind only to their matching family (`planar` -> `geometry`, `spherical` -> `geography`); mismatches raise `EncodingError`. gometry's [`chart` model](https://gometry.monicz.dev/mental-model/) has no PostGIS counterpart — reinterpret it explicitly with `with_space(...)` before binding. See PostGIS's [Geography documentation](https://postgis.net/docs/using_postgis_dbmanagement.html#PostGIS_Geography) for trade-offs between `geography` and `geometry`.

## SRIDs and coordinate reference systems

An SRID keys a row in the database's `spatial_ref_sys` table and is not necessarily an EPSG code. Gres maps SRIDs to gometry CRSs using the database's definitions (which requires `SELECT` on `spatial_ref_sys`; [exact EWKB transport](https://gres.monicz.dev/guide/spatial/#exact-ewkb-transport) does not):

- **Reading:** nonzero SRIDs resolve to the authority code (`EPSG:4326`) when known to gometry, or the stored WKT/PROJ definition. SRID 0 produces a CRS-less value; missing SRIDs raise `DecodingError`.
- **Writing:** Gres matches the value's CRS against `spatial_ref_sys`. Zero matches raise `EncodingError`; multiple matches require [`SpatialParameter(value, srid)`](https://gres.monicz.dev/api/spatial/#gres.SpatialParameter "SpatialParameter dataclass"). Values without a CRS send SRID 0.
- **No implicit reprojection:** Gres never transforms coordinates. Reproject with gometry's [`to_space`](https://gometry.monicz.dev/guide/crs/) or PostGIS's [`ST_Transform`](https://postgis.net/docs/ST_Transform.html). Binding a mismatched CRS to a typed column such as `geometry(Point, 4326)` raises `DataError`.

Prefer typed columns (`geometry(Point, 4326)`, `geography(Polygon, 4326)`): PostGIS enforces kind and SRID, and Gres reads one CRS definition. On `INSERT`, PostgreSQL does not report the column's SRID for parameters, so SRID 0 takes the column's SRID without transforming coordinates — attach a gometry `Space` when the source CRS matters. EWKB carries no coordinate epoch; store epochs in a separate column if needed.

## Query with spatial indexes

Bind gometry values wherever SQL expects `geometry` or `geography`:

- A [GiST index](https://postgis.net/workshops/postgis-intro/indexing.html) stores bounding boxes; `&&` returns bounding-box candidates, not exact intersections.
- Indexable predicates such as [`ST_Intersects`](https://postgis.net/docs/ST_Intersects.html) and [`ST_DWithin`](https://postgis.net/docs/ST_DWithin.html) use the index to prefilter candidates before exact refinement. Prefer `ST_DWithin(a, b, r)` over `ST_Distance(a, b) < r`, which cannot use an index.
- Queries casting `location::geography` need an expression index on that cast, as in the example above.

## Extents: `box2d` and `box3d`

[`ST_Extent`](https://postgis.net/docs/ST_Extent.html) and [`ST_3DExtent`](https://postgis.net/docs/ST_3DExtent.html) return `box2d` and `box3d` values as float tuples in [GeoJSON `bbox`](https://datatracker.ietf.org/doc/html/rfc7946#section-5) / gometry `bounds` order:

```python
# Partial: continues the example above.
extent = await db.fetch_one(
    'SELECT ST_Extent(location) FROM station',
    row=scalar(tuple[float, float, float, float]),
)
print(extent)  # (5.32, 59.91, 11.1, 60.39)
coverage = gm.box(*extent, space=WGS84)
```

- **Order:** `(xmin, ymin, xmax, ymax)` for `box2d`; `(xmin, ymin, zmin, xmax, ymax, zmax)` for `box3d`. The same tuples and PostGIS `BOX(...)` strings bind as parameters; an empty extent returns `None`.
- **No SRID:** attach a `Space` in Python or use `ST_SetSRID(ST_Extent(location)::geometry, 4326)` in SQL.
- **Precision:** PostGIS transmits boxes as text, which can round bounds; use [`ST_XMin`](https://postgis.net/docs/ST_XMin.html) and siblings for exact floats.
- **Arrow:** `stream_arrow` emits GeoArrow `geoarrow.box` structs (`xmin`, `ymin`, `xmax`, `ymax`, plus `zmin`/`zmax` for `box3d`).

## GeoArrow and COPY

### Read PostGIS columns as GeoArrow

`stream_arrow` emits PostGIS columns as [GeoArrow](https://geoarrow.org/). gometry's [`from_arrow`](https://gometry.monicz.dev/ecosystem/arrow/) also restores PostGIS curve and surface types. The column's type modifier chooses the layout before any rows arrive:

| PostGIS column | GeoArrow encoding |
| --- | --- |
| Single point, line, or polygon kind (or multi form), e.g. `geometry(Point,4326)` or `geography(MultiPolygonZ)` | Native layout (`geoarrow.point`, etc.) with the column's dimensions |
| Curves, surfaces, geometry collections, or untyped columns | `geoarrow.wkb` |

- **CRS:** resolved from the column's SRID via `spatial_ref_sys` and gometry. Expressions without a declared SRID (such as `ST_Transform(geom, 3857)`) take the first non-`NULL` value's SRID; a later row with a different SRID raises `DecodingError`.
- **Edges:** `geometry` uses planar edges; `geography` uses spherical edges (polygon interiors on the left of rings).
- **Overrides and nested fields:** pass a GeoArrow field in `schema=` (e.g. `geoarrow.wkb`) to override one column. PostGIS arrays and composite fields stay exact EWKB unless overridden in `schema=`.
- **Layout:** native output uses separated coordinate arrays and 32-bit list offsets (interleaved coordinates and 64-bit offsets are accepted on import); WKB supports 32-bit and 64-bit binary offsets.
- Pass `geometry='exact'` to stream Arrow `large_binary` EWKB with `gres.postgis` metadata (preserving mixed SRIDs in one column; see [Exact EWKB transport](https://gres.monicz.dev/guide/spatial/#exact-ewkb-transport)).

### Load spatial data with COPY

`copy_from_rows` accepts gometry objects and exact EWKB carriers. Because row COPY inspects the destination column's SRID, copying a CRS-less gometry value into `geometry(Point, 4326)` raises `EncodingError`.

`copy_from_arrow` loads GeoArrow, WKB, or EWKB columns:

- GeoArrow converts to the destination PostGIS type: declared destination SRIDs are verified and applied; undeclared destinations require an unambiguous match in `spatial_ref_sys`.
- Plain WKB/EWKB follows the destination type; `gres.postgis` field metadata must match the destination family. When copying exact EWKB across databases, ensure matching SRID definitions.
- Async iterables exposing an Arrow `schema` attribute let Gres prepare conversions (or skip CRS lookups for exact EWKB) before pulling batches.

## Exact EWKB transport

Use [`Decoding(geometry='exact')`](https://gres.monicz.dev/api/types/#gres.Decoding "Decoding dataclass") (or `stream_arrow(..., geometry='exact')`) for [`EwkbGeometry`](https://gres.monicz.dev/api/spatial/#gres.EwkbGeometry "EwkbGeometry") and [`EwkbGeography`](https://gres.monicz.dev/api/spatial/#gres.EwkbGeography "EwkbGeography") carriers. They expose the database's EWKB bytes unchanged (SRID, Z/M ordinates, and all PostGIS shape kinds), require neither `gometry` nor `SELECT` on `spatial_ref_sys`, and bind only to their own family.

## Curves and surfaces

PostGIS curve and surface kinds decode to gometry's `CircularString`, `CompoundCurve`, `CurvePolygon`, `MultiCurve`, `MultiSurface`, `PolyhedralSurface`, `TIN`, and `Triangle` and round-trip byte for byte with SRID and Z/M ordinates:

```python
# Partial: continues the example above.
arc = await db.fetch_one(
    "SELECT 'CIRCULARSTRING(0 0, 1 1, 2 0)'::geometry", row=scalar(gm.CircularString)
)
print(arc.length)  # 3.141592653589793
print(type(arc.linearize()).__name__)  # LineString
```

- **Exact arcs:** gometry computes length, area, bounds, and centroid from the true arcs (`gm.length(arc, metric='cartesian')` measures in degrees on geographic CRSs).
- **Straight-edge operations:** buffers, overlays, and other straight-edge operations raise `GeometryTypeError` directing you to `linearize()` (equivalent to SQL [`ST_CurveToLine`](https://postgis.net/docs/ST_CurveToLine.html)). See gometry's [geometry guide](https://gometry.monicz.dev/guide/geometry/).
- **Planar only:** PostGIS `geography` stores neither curves nor surfaces.
- **Arrow:** curves and surfaces stream as `geoarrow.wkb` (restored by `copy_from_arrow` and gometry's `from_arrow`; linearize in gometry before exporting to GeoPandas/Shapely).

## Values as stored

Gres does not validate or repair geometries: Z/M ordinates, empty geometries, SRIDs, and invalid rings round-trip as stored. Check validity with [`ST_IsValid`](https://postgis.net/docs/ST_IsValid.html) or gometry's [validation guide](https://gometry.monicz.dev/guide/validation/). SQL `NULL` is `None`. For `geometry[]` and `geography[]` arrays, see [Arrays](https://gres.monicz.dev/guide/types/#arrays).
