Using SQLAlchemy with Spatial Databases
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Spatial element classes for handling spatial data interchange between database representations and Python objects. These elements provide transparent conversion and enable direct application of spatial functions to geometric data.
Handle Well-Known Text representations of geometries, providing human-readable spatial data interchange.
class WKTElement:
"""
Element for Well-Known Text geometry representations.
Parameters:
- data: str, WKT string representation of geometry
- srid: int, spatial reference system identifier (default: -1)
- extended: bool, use extended WKT format (default: None)
"""
def __init__(self, data: str, srid: int = -1, extended: bool = None): ...
@property
def desc(self) -> str:
"""String representation of the WKT data."""Usage examples:
from geoalchemy2 import WKTElement
from geoalchemy2.functions import ST_Area, ST_Buffer
# Create WKT element from string
point = WKTElement('POINT(1 2)', srid=4326)
polygon = WKTElement('POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))', srid=4326)
# Use in database operations
session.add(Lake(name='Test Lake', geom=polygon))
# Apply spatial functions directly
buffered = point.ST_Buffer(100)
area = polygon.ST_Area()
# Use in queries
lakes = session.query(Lake).filter(
Lake.geom.ST_Contains(point)
).all()Handle Well-Known Binary representations of geometries, providing efficient binary spatial data interchange.
class WKBElement:
"""
Element for Well-Known Binary geometry representations.
Parameters:
- data: bytes, WKB binary representation of geometry
- srid: int, spatial reference system identifier (default: -1)
- extended: bool, use extended WKB format (default: None)
"""
def __init__(self, data: bytes, srid: int = -1, extended: bool = None): ...
@property
def desc(self) -> str:
"""Hexadecimal string representation of the WKB data."""Usage examples:
from geoalchemy2 import WKBElement
import binascii
# Create WKB element from binary data
wkb_data = binascii.unhexlify('0101000000000000000000F03F0000000000000040')
point = WKBElement(wkb_data, srid=4326)
# WKB elements are typically returned from database queries
lake = session.query(Lake).first()
geometry = lake.geom # This is a WKBElement
# Apply spatial functions
center = geometry.ST_Centroid()
area = geometry.ST_Area()
transformed = geometry.ST_Transform(3857)
# Use in spatial operations
nearby = session.query(Lake).filter(
Lake.geom.ST_DWithin(point, 1000)
).all()Handle raster data representations for satellite imagery, digital elevation models, and gridded datasets.
class RasterElement:
"""
Element for raster data representations.
Parameters:
- data: bytes, binary raster data
- srid: int, spatial reference system identifier (default: -1)
"""
def __init__(self, data: bytes, srid: int = -1): ...
@property
def desc(self) -> str:
"""Hexadecimal string representation of the raster data."""Usage examples:
from geoalchemy2 import RasterElement
# Raster elements are typically returned from database queries
image = session.query(SatelliteImage).first()
raster = image.image_data # This is a RasterElement
# Apply raster functions
width = raster.ST_Width()
height = raster.ST_Height()
num_bands = raster.ST_NumBands()
# Extract pixel values
pixel_value = raster.ST_Value(1, 100, 200) # band 1, x=100, y=200
# Convert to geometry
convex_hull = raster.ST_ConvexHull()
envelope = raster.ST_Envelope()Handle composite values returned by spatial functions that produce structured results.
class CompositeElement:
"""
Element for accessing components of composite spatial types.
Parameters:
- base: base expression or element
- field: str, field name to access
- type_: SQLAlchemy type for the field
"""
def __init__(self, base, field: str, type_): ...Usage examples:
from geoalchemy2.functions import ST_Dump
# ST_Dump returns GeometryDump composite type
dump_result = session.query(ST_Dump(polygon)).first()
# Access composite components
path = dump_result.path # Array of integers
geom = dump_result.geom # Geometry component
# Use in complex queries
components = session.query(
ST_Dump(Lake.geom).geom.label('part'),
ST_Dump(Lake.geom).path.label('path')
).all()Self-updating element classes that automatically refresh their spatial function capabilities.
class DynamicWKTElement(WKTElement):
"""Dynamic WKT element with auto-updating function capabilities."""
class DynamicWKBElement(WKBElement):
"""Dynamic WKB element with auto-updating function capabilities."""
class DynamicRasterElement(RasterElement):
"""Dynamic raster element with auto-updating function capabilities."""Spatial elements provide automatic conversion between different representations:
# Convert WKT to WKB via database function
wkt_elem = WKTElement('POINT(1 2)', srid=4326)
wkb_result = session.scalar(wkt_elem.ST_AsBinary())
# Convert WKB to WKT via database function
wkb_elem = WKBElement(binary_data, srid=4326)
wkt_result = session.scalar(wkb_elem.ST_AsText())All spatial elements automatically provide access to the complete library of spatial functions:
# Geometry construction and manipulation
transformed = element.ST_Transform(3857)
buffered = element.ST_Buffer(100)
simplified = element.ST_Simplify(0.1)
# Spatial relationships and predicates
contains = element1.ST_Contains(element2)
intersects = element1.ST_Intersects(element2)
within = element1.ST_Within(element2)
# Measurements and calculations
area = element.ST_Area()
length = element.ST_Length()
distance = element1.ST_Distance(element2)
# Coordinate system operations
srid = element.ST_SRID()
transformed = element.ST_Transform(4326)Each spatial function returns appropriate types:
Install with Tessl CLI
npx tessl i tessl/pypi-geoalchemy2