PostGIS¶
Gres reads and writes PostGIS geometry and geography values in binary format without text round trips. With the postgis extra, rows decode into gometry objects carrying the database's CRS and edge model; without gometry, use Decoding(geometry='exact') for EWKB carriers.
pip install 'gres[postgis]'
The target database needs CREATE EXTENSION postgis with its types and functions on the session's search_path.
Example¶
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 has no PostGIS counterpart — reinterpret it explicitly with with_space(...) before binding. See PostGIS's Geography documentation 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 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 raiseDecodingError. - Writing: Gres matches the value's CRS against
spatial_ref_sys. Zero matches raiseEncodingError; multiple matches requireSpatialParameter(value, srid). Values without a CRS send SRID 0. - No implicit reprojection: Gres never transforms coordinates. Reproject with gometry's
to_spaceor PostGIS'sST_Transform. Binding a mismatched CRS to a typed column such asgeometry(Point, 4326)raisesDataError.
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 stores bounding boxes;
&&returns bounding-box candidates, not exact intersections. - Indexable predicates such as
ST_IntersectsandST_DWithinuse the index to prefilter candidates before exact refinement. PreferST_DWithin(a, b, r)overST_Distance(a, b) < r, which cannot use an index. - Queries casting
location::geographyneed an expression index on that cast, as in the example above.
Extents: box2d and box3d¶
ST_Extent and ST_3DExtent return box2d and box3d values as float tuples in GeoJSON bbox / gometry bounds order:
# 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)forbox2d;(xmin, ymin, zmin, xmax, ymax, zmax)forbox3d. The same tuples and PostGISBOX(...)strings bind as parameters; an empty extent returnsNone. - No SRID: attach a
Spacein Python or useST_SetSRID(in SQL.ST_Extent( location) ::geometry, 4326) - Precision: PostGIS transmits boxes as text, which can round bounds; use
ST_XMinand siblings for exact floats. - Arrow:
stream_arrowemits GeoArrowgeoarrow.boxstructs (xmin,ymin,xmax,ymax, pluszmin/zmaxforbox3d).
GeoArrow and COPY¶
Read PostGIS columns as GeoArrow¶
stream_arrow emits PostGIS columns as GeoArrow. gometry's from_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_sysand gometry. Expressions without a declared SRID (such asST_Transform(geom, 3857)) take the first non-NULLvalue's SRID; a later row with a different SRID raisesDecodingError. - Edges:
geometryuses planar edges;geographyuses 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 inschema=. - 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 Arrowlarge_binaryEWKB withgres.postgismetadata (preserving mixed SRIDs in one column; see 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.postgisfield metadata must match the destination family. When copying exact EWKB across databases, ensure matching SRID definitions. - Async iterables exposing an Arrow
schemaattribute let Gres prepare conversions (or skip CRS lookups for exact EWKB) before pulling batches.
Exact EWKB transport¶
Use Decoding(geometry='exact') (or stream_arrow(..., geometry='exact')) for EwkbGeometry and 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:
# 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
GeometryTypeErrordirecting you tolinearize()(equivalent to SQLST_CurveToLine). See gometry's geometry guide. - Planar only: PostGIS
geographystores neither curves nor surfaces. - Arrow: curves and surfaces stream as
geoarrow.wkb(restored bycopy_from_arrowand gometry'sfrom_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 or gometry's validation guide. SQL NULL is None. For geometry[] and geography[] arrays, see Arrays.