Using SQLAlchemy with Spatial Databases
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Comprehensive library of 376+ spatial functions covering geometry construction, spatial relationships, measurements, transformations, and raster operations. Functions are dynamically generated and provide consistent interfaces across all supported database backends.
Spatial functions can be called in multiple ways:
from geoalchemy2 import functions as func
from sqlalchemy.sql import func as sql_func
# Using geoalchemy2.functions module
result = session.query(func.ST_Area(Lake.geom)).scalar()
# Using SQLAlchemy's func object
result = session.query(sql_func.ST_Area(Lake.geom)).scalar()
# Applying to spatial elements directly
lake = session.query(Lake).first()
area = lake.geom.ST_Area()
# In query filters
large_lakes = session.query(Lake).filter(
func.ST_Area(Lake.geom) > 1000000
).all()Create geometries from coordinates, existing geometries, and other spatial data sources.
def ST_MakePoint(x: float, y: float, z: float = None, m: float = None):
"""Create a 2D, 3DZ or 4D Point."""
def ST_MakePointM(x: float, y: float, m: float):
"""Create a Point from X, Y and M values."""
def ST_MakeLine(*points):
"""Create a Linestring from Point, MultiPoint, or LineString geometries."""
def ST_MakePolygon(shell, holes=None):
"""Create a Polygon from a shell and optional list of holes."""
def ST_MakeEnvelope(xmin: float, ymin: float, xmax: float, ymax: float, srid: int = None):
"""Create a rectangular Polygon from minimum and maximum coordinates."""
def ST_Collect(*geometries):
"""Create a GeometryCollection or Multi* geometry from a set of geometries."""
def ST_Point(x: float, y: float):
"""Create a Point with the given coordinate values. Alias for ST_MakePoint."""
def ST_Polygon(linestring, srid: int = None):
"""Create a Polygon from a LineString with a specified SRID."""
def ST_LineFromMultiPoint(multipoint):
"""Create a LineString from a MultiPoint geometry."""Usage examples:
from geoalchemy2.functions import ST_MakePoint, ST_MakeLine, ST_MakePolygon
# Create points
point1 = ST_MakePoint(0, 0)
point2 = ST_MakePoint(1, 1)
point3d = ST_MakePoint(0, 0, 10)
# Create line from points
line = ST_MakeLine(point1, point2)
# Create polygon from coordinates
envelope = ST_MakeEnvelope(-1, -1, 1, 1, 4326)
# Use in queries
nearby_points = session.query(Location).filter(
func.ST_DWithin(Location.geom, ST_MakePoint(0, 0), 1000)
).all()Extract information and components from existing geometries.
def ST_X(geom):
"""Return the X coordinate of a Point."""
def ST_Y(geom):
"""Return the Y coordinate of a Point."""
def ST_Z(geom):
"""Return the Z coordinate of a Point."""
def ST_M(geom):
"""Return the M coordinate of a Point."""
def ST_SRID(geom):
"""Return the spatial reference identifier for a geometry."""
def ST_GeometryType(geom):
"""Return the geometry type as a string."""
def ST_Dimension(geom):
"""Return the coordinate dimension of a geometry."""
def ST_CoordDim(geom):
"""Return the coordinate dimension of a geometry."""
def ST_NumGeometries(geom):
"""Return the number of geometries in a GeometryCollection."""
def ST_GeometryN(geom, n: int):
"""Return the Nth geometry in a GeometryCollection."""
def ST_NumPoints(geom):
"""Return the number of points in a LineString or CircularString."""
def ST_PointN(geom, n: int):
"""Return the Nth point in a LineString."""
def ST_StartPoint(geom):
"""Return the first point of a LineString."""
def ST_EndPoint(geom):
"""Return the last point of a LineString."""
def ST_Boundary(geom):
"""Return the boundary of a geometry."""
def ST_Envelope(geom):
"""Return the bounding box of a geometry."""
def ST_ExteriorRing(geom):
"""Return the exterior ring of a Polygon."""
def ST_NumInteriorRings(geom):
"""Return the number of interior rings in a Polygon."""
def ST_InteriorRingN(geom, n: int):
"""Return the Nth interior ring of a Polygon."""Test spatial relationships between geometries using standardized predicates.
def ST_Contains(geom1, geom2):
"""Test if geom1 completely contains geom2."""
def ST_Within(geom1, geom2):
"""Test if geom1 is completely within geom2."""
def ST_Intersects(geom1, geom2):
"""Test if two geometries intersect."""
def ST_Crosses(geom1, geom2):
"""Test if two geometries cross each other."""
def ST_Overlaps(geom1, geom2):
"""Test if two geometries overlap."""
def ST_Touches(geom1, geom2):
"""Test if two geometries touch at their boundaries."""
def ST_Disjoint(geom1, geom2):
"""Test if two geometries are disjoint (do not intersect)."""
def ST_Equals(geom1, geom2):
"""Test if two geometries are spatially equal."""
def ST_Covers(geom1, geom2):
"""Test if geom1 covers geom2."""
def ST_CoveredBy(geom1, geom2):
"""Test if geom1 is covered by geom2."""
def ST_ContainsProperly(geom1, geom2):
"""Test if geom1 properly contains geom2."""
def ST_Relate(geom1, geom2, pattern: str = None):
"""Test spatial relationship using DE-9IM intersection matrix."""Usage examples:
# Find buildings within a district
buildings_in_district = session.query(Building).filter(
func.ST_Within(Building.geom, district.geom)
).all()
# Find intersecting roads and railways
intersections = session.query(Road, Railway).filter(
func.ST_Intersects(Road.geom, Railway.geom)
).all()
# Complex spatial query with multiple predicates
complex_query = session.query(Parcel).filter(
func.ST_Contains(Parcel.geom, point),
func.ST_Area(Parcel.geom) > 1000,
~func.ST_Overlaps(Parcel.geom, flood_zone.geom) # NOT overlaps
).all()Calculate distances, areas, lengths, and other geometric measurements.
def ST_Distance(geom1, geom2):
"""Calculate the minimum distance between two geometries."""
def ST_DWithin(geom1, geom2, distance: float):
"""Test if two geometries are within a specified distance."""
def ST_Area(geom):
"""Calculate the area of a polygon or multi-polygon."""
def ST_Length(geom):
"""Calculate the length of a linestring or multi-linestring."""
def ST_Perimeter(geom):
"""Calculate the perimeter of a polygon."""
def ST_Distance_Sphere(geom1, geom2):
"""Calculate spherical distance between two lon/lat geometries."""
def ST_Distance_Spheroid(geom1, geom2, spheroid: str):
"""Calculate distance on a spheroid between two geometries."""
def ST_Azimuth(geom1, geom2):
"""Calculate the azimuth between two points."""
def ST_Angle(geom1, geom2, geom3=None):
"""Calculate the angle between three points or two vectors."""Transform, modify, and process geometries for analysis and visualization.
def ST_Buffer(geom, distance: float, quadsegs: int = None):
"""Create a buffer around a geometry."""
def ST_Centroid(geom):
"""Calculate the centroid of a geometry."""
def ST_PointOnSurface(geom):
"""Return a point guaranteed to be on the surface of a geometry."""
def ST_Simplify(geom, tolerance: float):
"""Simplify a geometry using the Douglas-Peucker algorithm."""
def ST_SimplifyPreserveTopology(geom, tolerance: float):
"""Simplify a geometry while preserving topology."""
def ST_ConvexHull(geom):
"""Calculate the convex hull of a geometry."""
def ST_Union(*geometries):
"""Calculate the union of multiple geometries."""
def ST_Intersection(geom1, geom2):
"""Calculate the intersection of two geometries."""
def ST_Difference(geom1, geom2):
"""Calculate the difference between two geometries."""
def ST_SymDifference(geom1, geom2):
"""Calculate the symmetric difference between two geometries."""
def ST_Snap(geom1, geom2, tolerance: float):
"""Snap vertices of geom1 to geom2 within tolerance."""
def ST_SnapToGrid(geom, *args):
"""Snap geometry vertices to a grid."""Transform geometries between spatial reference systems and manage coordinate data.
def ST_Transform(geom, srid: int):
"""Transform geometry to a different spatial reference system."""
def ST_SetSRID(geom, srid: int):
"""Set the SRID of a geometry without transformation."""
def ST_SRID(geom):
"""Return the SRID of a geometry."""
def Find_SRID(schema: str, table: str, column: str):
"""Find the SRID for a geometry column."""
def UpdateGeometrySRID(schema: str, table: str, column: str, srid: int):
"""Update the SRID of all features in a geometry column."""Convert between different spatial data formats and representations.
def ST_AsText(geom):
"""Return WKT representation of a geometry."""
def ST_AsEWKT(geom):
"""Return EWKT representation of a geometry."""
def ST_AsBinary(geom):
"""Return WKB representation of a geometry."""
def ST_AsEWKB(geom):
"""Return EWKB representation of a geometry."""
def ST_AsGeoJSON(geom, maxdecimaldigits: int = None):
"""Return GeoJSON representation of a geometry."""
def ST_AsKML(geom, maxdecimaldigits: int = None):
"""Return KML representation of a geometry."""
def ST_AsGML(geom, version: int = None):
"""Return GML representation of a geometry."""
def ST_AsSVG(geom, relative: bool = None, precision: int = None):
"""Return SVG representation of a geometry."""
def ST_GeomFromText(wkt: str, srid: int = None):
"""Create geometry from WKT representation."""
def ST_GeomFromWKB(wkb: bytes, srid: int = None):
"""Create geometry from WKB representation."""
def ST_GeomFromGeoJSON(geojson: str):
"""Create geometry from GeoJSON representation."""
def ST_GeomFromKML(kml: str):
"""Create geometry from KML representation."""
def ST_GeomFromGML(gml: str, srid: int = None):
"""Create geometry from GML representation."""Process and analyze raster data including satellite imagery and elevation models.
# Raster Information
def ST_Width(raster):
"""Return the width of a raster in pixels."""
def ST_Height(raster):
"""Return the height of a raster in pixels."""
def ST_NumBands(raster):
"""Return the number of bands in a raster."""
def ST_PixelWidth(raster):
"""Return the pixel width of a raster."""
def ST_PixelHeight(raster):
"""Return the pixel height of a raster."""
# Raster Values
def ST_Value(raster, band: int, x: int, y: int):
"""Return the value of a raster pixel."""
def ST_SetValue(raster, band: int, x: int, y: int, value: float):
"""Set the value of a raster pixel."""
def ST_BandNoDataValue(raster, band: int = None):
"""Return the NODATA value of a raster band."""
def ST_SetBandNoDataValue(raster, band: int, nodatavalue: float):
"""Set the NODATA value of a raster band."""
# Raster Processing
def ST_Clip(raster, geom):
"""Clip a raster by a geometry."""
def ST_Union(*rasters):
"""Union multiple rasters into a single raster."""
def ST_MapAlgebra(raster1, raster2, expression: str):
"""Apply map algebra expression to raster bands."""
def ST_Reclass(raster, reclassexpr: str):
"""Reclassify raster values using expressions."""
# Raster-Geometry Conversion
def ST_AsRaster(geom, *args):
"""Convert geometry to raster representation."""
def ST_DumpAsPolygons(raster, band: int = None):
"""Convert raster pixels to polygon geometries."""
def ST_ConvexHull(raster):
"""Return the convex hull of a raster."""The complete function library includes:
All functions support:
Install with Tessl CLI
npx tessl i tessl/pypi-geoalchemy2