or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

database-administration.mdindex.mdmigration-support.mdshapely-integration.mdspatial-elements.mdspatial-functions.mdspatial-types.md
tile.json

tessl/pypi-geoalchemy2

Using SQLAlchemy with Spatial Databases

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/geoalchemy2@0.18.x

To install, run

npx @tessl/cli install tessl/pypi-geoalchemy2@0.18.0

index.mddocs/

GeoAlchemy2

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.

Package Information

  • Package Name: GeoAlchemy2
  • Language: Python
  • Installation: pip install GeoAlchemy2
  • Optional Dependencies: pip install GeoAlchemy2[shapely] for Shapely integration

Core Imports

import geoalchemy2
from geoalchemy2 import Geometry, Geography, Raster
from geoalchemy2 import WKTElement, WKBElement, RasterElement
from geoalchemy2 import functions as func
from geoalchemy2.shape import to_shape, from_shape  # Requires shapely

Basic Usage

from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from geoalchemy2 import Geometry, Geography, functions as func
from geoalchemy2 import WKTElement

Base = declarative_base()

class Lake(Base):
    __tablename__ = 'lake'
    
    id = Column(Integer, primary_key=True)
    name = Column(String)
    geom = Column(Geometry('POLYGON', srid=4326))

# Create engine and session
engine = create_engine('postgresql://user:pass@localhost/gis_db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

# Insert data with WKT
lake = Lake(
    name='Example Lake',
    geom=WKTElement('POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))', srid=4326)
)
session.add(lake)
session.commit()

# Query with spatial functions
lakes = session.query(Lake).filter(
    func.ST_Area(Lake.geom) > 1000
).all()

# Use spatial relationships
nearby_lakes = session.query(Lake).filter(
    func.ST_DWithin(Lake.geom, WKTElement('POINT(0.5 0.5)', srid=4326), 1000)
).all()

Architecture

GeoAlchemy2 extends SQLAlchemy's type system and function capabilities to provide comprehensive spatial database support:

  • Type System: Geometry, Geography, and Raster column types with database-specific compilation
  • Element System: WKT, WKB, and Raster elements for handling spatial data interchange
  • Function Registry: 376+ spatial functions dynamically mapped to database-specific implementations
  • Dialect System: Database-specific optimizations for PostGIS, SpatiaLite, MySQL, and MariaDB
  • Admin System: DDL event listeners for automatic spatial index creation and metadata management

Capabilities

Spatial Column Types

Define spatial columns in SQLAlchemy models using Geometry, Geography, and Raster types with support for all major spatial databases and automatic spatial indexing.

class Geometry:
    def __init__(
        geometry_type: str = "GEOMETRY",
        srid: int = -1,
        dimension: int = None,
        spatial_index: bool = True,
        use_N_D_index: bool = False,
        use_typmod: bool = None
    ): ...

class Geography:
    def __init__(
        geometry_type: str = "GEOMETRY", 
        srid: int = -1,
        dimension: int = None,
        spatial_index: bool = True,
        use_N_D_index: bool = False,
        use_typmod: bool = None
    ): ...

class Raster:
    def __init__(
        spatial_index: bool = True,
        nullable: bool = True
    ): ...

Spatial Types

Spatial Elements

Handle spatial data interchange with WKT, WKB, and Raster elements that provide transparent conversion between database representations and Python objects.

class WKTElement:
    def __init__(data: str, srid: int = -1, extended: bool = None): ...

class WKBElement:  
    def __init__(data: bytes, srid: int = -1, extended: bool = None): ...

class RasterElement:
    def __init__(data: bytes, srid: int = -1): ...

Spatial Elements

Spatial Functions

Access to 376+ spatial functions covering geometry construction, spatial relationships, measurements, transformations, and analysis operations.

# Geometry construction
def ST_MakePoint(x: float, y: float, z: float = None, m: float = None): ...
def ST_MakeLine(*points): ...
def ST_MakePolygon(shell, holes=None): ...

# Spatial relationships  
def ST_Contains(geom1, geom2): ...
def ST_Within(geom1, geom2): ...
def ST_Intersects(geom1, geom2): ...

# Measurements
def ST_Area(geom): ...
def ST_Length(geom): ...
def ST_Distance(geom1, geom2): ...

Spatial Functions

Shapely Integration

Convert between GeoAlchemy2 spatial elements and Shapely geometries for advanced geometric operations and analysis.

def to_shape(element: Union[WKBElement, WKTElement]): ...
def from_shape(shape, srid: int = -1, extended: bool = None): ...

Shapely Integration

Database Administration

Manage spatial databases with automatic DDL event handling, spatial index creation, and dialect-specific optimizations.

def setup_ddl_event_listeners(): ...
def load_spatialite(dbapi_conn, *args): ...
def load_spatialite_gpkg(dbapi_conn, *args, **kwargs): ...

class GeoEngine: ...

Database Administration

Migration Support

Integrate spatial schema changes with Alembic migrations using specialized operations for spatial columns, tables, and indexes.

class AddGeospatialColumnOp: ...
class DropGeospatialColumnOp: ...
class CreateGeospatialTableOp: ...
class DropGeospatialTableOp: ...

Migration Support

Error Handling

GeoAlchemy2 defines specific exceptions for spatial operations:

class ArgumentError(Exception):
    """Raised when an invalid or conflicting function argument is supplied."""