Using SQLAlchemy with Spatial Databases
npx @tessl/cli install tessl/pypi-geoalchemy2@0.18.00
# GeoAlchemy2
1
2
A comprehensive Python toolkit that provides a SQLAlchemy extension for working with spatial databases. GeoAlchemy2 enables seamless integration of geographic and spatial data types, functions, and operations into SQLAlchemy-based applications, supporting major spatial database backends including PostGIS (PostgreSQL), SpatiaLite (SQLite), MySQL, and MariaDB.
3
4
## Package Information
5
6
- **Package Name**: GeoAlchemy2
7
- **Language**: Python
8
- **Installation**: `pip install GeoAlchemy2`
9
- **Optional Dependencies**: `pip install GeoAlchemy2[shapely]` for Shapely integration
10
11
## Core Imports
12
13
```python
14
import geoalchemy2
15
from geoalchemy2 import Geometry, Geography, Raster
16
from geoalchemy2 import WKTElement, WKBElement, RasterElement
17
from geoalchemy2 import functions as func
18
from geoalchemy2.shape import to_shape, from_shape # Requires shapely
19
```
20
21
## Basic Usage
22
23
```python
24
from sqlalchemy import Column, Integer, String, create_engine
25
from sqlalchemy.ext.declarative import declarative_base
26
from sqlalchemy.orm import sessionmaker
27
from geoalchemy2 import Geometry, Geography, functions as func
28
from geoalchemy2 import WKTElement
29
30
Base = declarative_base()
31
32
class Lake(Base):
33
__tablename__ = 'lake'
34
35
id = Column(Integer, primary_key=True)
36
name = Column(String)
37
geom = Column(Geometry('POLYGON', srid=4326))
38
39
# Create engine and session
40
engine = create_engine('postgresql://user:pass@localhost/gis_db')
41
Base.metadata.create_all(engine)
42
Session = sessionmaker(bind=engine)
43
session = Session()
44
45
# Insert data with WKT
46
lake = Lake(
47
name='Example Lake',
48
geom=WKTElement('POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))', srid=4326)
49
)
50
session.add(lake)
51
session.commit()
52
53
# Query with spatial functions
54
lakes = session.query(Lake).filter(
55
func.ST_Area(Lake.geom) > 1000
56
).all()
57
58
# Use spatial relationships
59
nearby_lakes = session.query(Lake).filter(
60
func.ST_DWithin(Lake.geom, WKTElement('POINT(0.5 0.5)', srid=4326), 1000)
61
).all()
62
```
63
64
## Architecture
65
66
GeoAlchemy2 extends SQLAlchemy's type system and function capabilities to provide comprehensive spatial database support:
67
68
- **Type System**: Geometry, Geography, and Raster column types with database-specific compilation
69
- **Element System**: WKT, WKB, and Raster elements for handling spatial data interchange
70
- **Function Registry**: 376+ spatial functions dynamically mapped to database-specific implementations
71
- **Dialect System**: Database-specific optimizations for PostGIS, SpatiaLite, MySQL, and MariaDB
72
- **Admin System**: DDL event listeners for automatic spatial index creation and metadata management
73
74
## Capabilities
75
76
### Spatial Column Types
77
78
Define spatial columns in SQLAlchemy models using Geometry, Geography, and Raster types with support for all major spatial databases and automatic spatial indexing.
79
80
```python { .api }
81
class Geometry:
82
def __init__(
83
geometry_type: str = "GEOMETRY",
84
srid: int = -1,
85
dimension: int = None,
86
spatial_index: bool = True,
87
use_N_D_index: bool = False,
88
use_typmod: bool = None
89
): ...
90
91
class Geography:
92
def __init__(
93
geometry_type: str = "GEOMETRY",
94
srid: int = -1,
95
dimension: int = None,
96
spatial_index: bool = True,
97
use_N_D_index: bool = False,
98
use_typmod: bool = None
99
): ...
100
101
class Raster:
102
def __init__(
103
spatial_index: bool = True,
104
nullable: bool = True
105
): ...
106
```
107
108
[Spatial Types](./spatial-types.md)
109
110
### Spatial Elements
111
112
Handle spatial data interchange with WKT, WKB, and Raster elements that provide transparent conversion between database representations and Python objects.
113
114
```python { .api }
115
class WKTElement:
116
def __init__(data: str, srid: int = -1, extended: bool = None): ...
117
118
class WKBElement:
119
def __init__(data: bytes, srid: int = -1, extended: bool = None): ...
120
121
class RasterElement:
122
def __init__(data: bytes, srid: int = -1): ...
123
```
124
125
[Spatial Elements](./spatial-elements.md)
126
127
### Spatial Functions
128
129
Access to 376+ spatial functions covering geometry construction, spatial relationships, measurements, transformations, and analysis operations.
130
131
```python { .api }
132
# Geometry construction
133
def ST_MakePoint(x: float, y: float, z: float = None, m: float = None): ...
134
def ST_MakeLine(*points): ...
135
def ST_MakePolygon(shell, holes=None): ...
136
137
# Spatial relationships
138
def ST_Contains(geom1, geom2): ...
139
def ST_Within(geom1, geom2): ...
140
def ST_Intersects(geom1, geom2): ...
141
142
# Measurements
143
def ST_Area(geom): ...
144
def ST_Length(geom): ...
145
def ST_Distance(geom1, geom2): ...
146
```
147
148
[Spatial Functions](./spatial-functions.md)
149
150
### Shapely Integration
151
152
Convert between GeoAlchemy2 spatial elements and Shapely geometries for advanced geometric operations and analysis.
153
154
```python { .api }
155
def to_shape(element: Union[WKBElement, WKTElement]): ...
156
def from_shape(shape, srid: int = -1, extended: bool = None): ...
157
```
158
159
[Shapely Integration](./shapely-integration.md)
160
161
### Database Administration
162
163
Manage spatial databases with automatic DDL event handling, spatial index creation, and dialect-specific optimizations.
164
165
```python { .api }
166
def setup_ddl_event_listeners(): ...
167
def load_spatialite(dbapi_conn, *args): ...
168
def load_spatialite_gpkg(dbapi_conn, *args, **kwargs): ...
169
170
class GeoEngine: ...
171
```
172
173
[Database Administration](./database-administration.md)
174
175
### Migration Support
176
177
Integrate spatial schema changes with Alembic migrations using specialized operations for spatial columns, tables, and indexes.
178
179
```python { .api }
180
class AddGeospatialColumnOp: ...
181
class DropGeospatialColumnOp: ...
182
class CreateGeospatialTableOp: ...
183
class DropGeospatialTableOp: ...
184
```
185
186
[Migration Support](./migration-support.md)
187
188
## Error Handling
189
190
GeoAlchemy2 defines specific exceptions for spatial operations:
191
192
```python { .api }
193
class ArgumentError(Exception):
194
"""Raised when an invalid or conflicting function argument is supplied."""
195
```