The notebooks in this module need a PostGIS server, a Python environment with the database clients, and a few command-line tools (psql, ogr2ogr, raster2pgsql, shp2pgsql). This notebook sets them up in two ways, a Docker container (recommended) and a conda environment, then connects from Python with psycopg, SQLAlchemy and GeoAlchemy2. It ends with geolattice.geolatticedb.connect(), the one connection interface that the rest of the module uses for PostGIS, SpatiaLite, GeoPackage and DuckDB.
Learning objectives
Start PostGIS (with pgRouting, H3 and MobilityDB) in Docker, or install it with conda.
Check that the Python packages, command-line tools and database extensions are available.
Connect with psycopg, SQLAlchemy and GeoAlchemy2, and pass parameters safely.
Open any of the four backends with geolattice.geolatticedb.connect().
Data
Data
Source
Use
EPA AirData PM2.5 monitors (active 2022-2025)
USA Health Data Atlas (assets/air_quality_data.js)
GeoAlchemy2 table
US county boundaries
USA Health Data Atlas (assets/geojson_counties_fips.json)
Connection tests
Contents
Setup
Option A: PostGIS in Docker
Option B: a conda environment
Checking the tools
Connecting with psycopg
Connecting with SQLAlchemy and GeoAlchemy2
geolattice.geolatticedb.connect(): one interface for every backend
Troubleshooting
Summary and exercises
Setup
Installation. This notebook needs installation option 6 (every GeoLattice module): pip install "geolattice[all]". See “Installation options” in the GeoLattice README.
Code
import warnings # warning controlwarnings.filterwarnings("ignore", category=UserWarning) # hide routine library warningsimport shutil # find programs on the PATHimport subprocess # run command-line toolsimport importlib.metadata as md # installed package versionsimport pandas as pd # tablesimport geopandas as gpd # vector datafrom geolattice import geolatticedb as pdb # GeoLattice spatial database tools
Code
import os # environment variablesimport json # JSON parsingimport urllib.request # download files over HTTPfrom pathlib import Path # file paths# The GeoLattice repository root: the first folder above this notebook that holds data/ and Tutorials/HERE = Path.cwd() # folder of this notebookROOT =next(p for p in [HERE, *HERE.parents] if (p /"Data").is_dir() and (p /"Tutorials").is_dir())GEOLATTICE_DATA = ROOT /"Data"# shared GeoLattice data folderDATA = ROOT /"Data"/"06_spatialDB"# data folder of this moduleOUT = DATA /"outputs"/"06_01_02"# outputs written by this notebookOUT.mkdir(parents=True, exist_ok=True) # create it if needed# USA Health Data Atlas (https://zia207.github.io/USA-Health-Data-Atlas/): raw files on GitHubATLAS ="https://raw.githubusercontent.com/zia207/USA-Health-Data-Atlas/main"def fetch(rel, base=ATLAS, folder="atlas"): # download helper"""Download a file once (default: from the Atlas repository) and return its local path.""" path = DATA / folder / rel # local cache pathifnot path.exists(): # download only if missing path.parent.mkdir(parents=True, exist_ok=True) # create the cache folderprint(f"Downloading {rel} ...") # progress message urllib.request.urlretrieve(f"{base}/{rel}", path) # copy the URL to the local pathreturn path # the local pathdef atlas_js(rel): # read an Atlas data file"""Atlas data files are JavaScript (`window.X = {...};`); return the JSON object inside.""" text = fetch(rel).read_text(encoding="utf-8") # whole file as textreturn json.loads(text[text.index("=") +1:].strip().rstrip(";")) # strip the assignment and parsedef atlas_counties(): # county polygons of the Atlas"""US county polygons (Census cartographic boundaries, EPSG:4326) with a 5-digit FIPS code.""" g = gpd.read_file(fetch("assets/geojson_counties_fips.json")) # GeoJSON from the Atlas g["fips"] = g["STATE"] + g["COUNTY"] # state + county code = FIPS g = g.rename(columns={"NAME": "name", "STATE": "statefp", "CENSUSAREA": "census_sqmi"}) # tidy namesreturn g[["fips", "statefp", "name", "census_sqmi", "geometry"]].set_crs(4326, allow_override=True)# PostGIS connection string (see 06_01_02 for the Docker container); override with GEOLATTICE_PG_DSNPG_DSN = os.environ.get("GEOLATTICE_PG_DSN", "postgresql://postgres:geolattice@localhost:5432/geolattice")print("Repository:", ROOT) # where the data are read from
Repository: /home/zia207/Github/GeoLattice
Option A: PostGIS in Docker
Docker runs PostgreSQL in an isolated container, so nothing is installed on the host and the same setup works on Linux, macOS and Windows. The official postgis/postgis image contains PostgreSQL and PostGIS. It is built on the official PostgreSQL image, which includes the PostgreSQL Global Development Group (PGDG) package repository, so we add pgRouting, H3 and MobilityDB with apt-get.
The next cell writes three files to Data/docker/:
Dockerfile: PostGIS 3.5 on PostgreSQL 17, plus pgRouting, h3-pg, MobilityDB and the PostGIS command-line loaders.
init.sql: creates the extensions when the database is first initialized.
docker-compose.yml: the database service on port 5432 with a named volume, so data survive restarts. An optional second service runs TimescaleDB (with PostGIS) on port 5433 for notebook 06_03_03.
Code
DOCKER = DATA /"docker"# folder for the container filesDOCKER.mkdir(parents=True, exist_ok=True) # create it(DOCKER /"Dockerfile").write_text("""\# PostgreSQL 17 with PostGIS 3.5FROM postgis/postgis:17-3.5# pgRouting, h3-pg, MobilityDB and the PostGIS command-line tools from the PGDG repository# refresh the package index, install those packages, then delete the apt cacheRUN apt-get update \\ && apt-get install -y --no-install-recommends \\ postgresql-17-pgrouting postgresql-17-h3 postgresql-17-mobilitydb postgis \\ && rm -rf /var/lib/apt/lists/*# run init.sql once, on the first start, after the image's own init scriptsCOPY init.sql /docker-entrypoint-initdb.d/20_geolattice_extensions.sql""") # the image definition(DOCKER /"init.sql").write_text("""\-- extensions used in the 06_spatialDB notebooks (runs once, when the volume is empty)CREATE EXTENSION IF NOT EXISTS postgis; -- geometry, geography and spatial functionsCREATE EXTENSION IF NOT EXISTS postgis_raster; -- raster type and raster functionsCREATE EXTENSION IF NOT EXISTS postgis_topology; -- topology modelCREATE EXTENSION IF NOT EXISTS pgrouting; -- shortest paths and other routingCREATE EXTENSION IF NOT EXISTS h3; -- H3 hexagonal indexCREATE EXTENSION IF NOT EXISTS h3_postgis CASCADE; -- H3 functions for PostGIS geometries; CASCADE installs what it depends onCREATE EXTENSION IF NOT EXISTS mobilitydb CASCADE; -- temporal types for moving objects; CASCADE installs what it depends on""") # extension setup(DOCKER /"docker-compose.yml").write_text("""\services: # the containers Compose starts postgis: # the PostGIS server the notebooks connect to build: . # build from the Dockerfile in this folder image: geolattice/postgis:17-3.5 # name and tag of the built image container_name: geolattice-postgis # fixed name, so later cells can find it environment: # settings read by the PostgreSQL image on first start POSTGRES_USER: postgres # superuser POSTGRES_PASSWORD: geolattice # password for local use POSTGRES_DB: geolattice # database created on the first start # load PostGIS when the server starts, and allow a larger write-ahead log for bulk loads command: ["postgres", "-c", "shared_preload_libraries=postgis-3", "-c", "max_wal_size=2GB"] ports: ["5432:5432"] # host port 5432 to the same port in the container volumes: # folders shared between the host and the container - pgdata:/var/lib/postgresql/data # named volume: the database survives restarts - ../../Data:/data:ro # the module data folder, readable inside the container healthcheck: # Compose uses this to know when the server is ready test: ["CMD-SHELL", "pg_isready -U postgres -d geolattice"] # ready when the server accepts connections interval: 5s # seconds between checks retries: 20 # failed checks allowed before the container is unhealthy timescale: # optional: docker compose --profile timescale up -d image: timescale/timescaledb-ha:pg17 # TimescaleDB on PostgreSQL 17 container_name: geolattice-timescale # fixed name for the optional server profiles: ["timescale"] # started only when this profile is requested environment: # settings read on the first start POSTGRES_PASSWORD: geolattice # same local password POSTGRES_DB: geolattice # same database name ports: ["5433:5432"] # host port 5433, so it does not clash with PostGIS on 5432volumes: # volumes Compose creates and keeps pgdata:""") # the servicesfor f insorted(DOCKER.iterdir()): # list what was writtenprint(f"{f.relative_to(ROOT)} ({f.stat().st_size} bytes)") # path and size of each file
Start the database from a terminal (these are shell commands, not Python):
cd Data/06_spatialDB/dockerdocker compose up -d--build# build the image once, then start the containerdocker compose ps # STATUS should become "healthy"docker compose logs -f postgis # follow the server log (Ctrl+C to stop following)docker exec -it geolattice-postgis psql -U postgres -d geolattice -c"SELECT postgis_full_version();"
Stop it with docker compose stop; remove the container and its data with docker compose down -v. The connection string used by every notebook is
Set the environment variable GEOLATTICE_PG_DSN before starting Jupyter to use another server, user or password. Never commit real passwords to a repository; for shared servers use a ~/.pgpass file or environment variables.
The cell below reports whether Docker is installed and whether the container is running:
Code
docker = shutil.which("docker") # path of the docker program, or Noneif docker isNone: # Docker is not installed on this machineprint("Docker not found on the PATH. Install Docker Desktop/Engine, or use Option B (conda).")else: # list the GeoLattice containers r = subprocess.run([docker, "ps", "--filter", "name=geolattice", "--format", "{{.Names}}{{.Status}}"], capture_output=True, text=True) # running containers named geolattice*print(r.stdout.strip() or"No geolattice container is running: docker compose up -d --build")
Docker not found on the PATH. Install Docker Desktop/Engine, or use Option B (conda).
Option B: a conda environment
Without Docker, conda-forge provides PostgreSQL, PostGIS and pgRouting as packages, next to GDAL and the Python libraries. The next cell writes environment.yml. TimescaleDB, MobilityDB and h3-pg are not on conda-forge; use the Docker image when you need them (the notebooks fall back to plain PostGIS when they are missing).
The next two cells list the versions of the Python packages and command-line tools this module uses. A missing package or tool is shown as missing.
Code
pkgs = ["geolattice", "geopandas", "shapely", "pyogrio", "rasterio", "pyproj", "psycopg", "sqlalchemy", "geoalchemy2","duckdb", "pyarrow", "networkx", "osmnx", "libpysal", "esda", "h3"] # Python packagesrows = [] # one row per packagefor p in pkgs: # every packagetry: rows.append({"package": p, "version": md.version(p)}) # installed versionexcept md.PackageNotFoundError: rows.append({"package": p, "version": "missing"}) # not installedpd.DataFrame(rows).set_index("package").T # one row, packages as columns
package
geolattice
geopandas
shapely
pyogrio
rasterio
pyproj
psycopg
sqlalchemy
geoalchemy2
duckdb
pyarrow
networkx
osmnx
libpysal
esda
h3
version
0.3.49
1.1.4
2.2.0
0.13.0
1.4.4
3.7.2
3.3.9
2.1.4
0.21.0
1.5.5
23.0.1
3.6.1
2.1.1
4.14.1
2.9.0
4.5.1
Code
tools = ["psql", "pg_dump", "ogr2ogr", "ogrinfo", "raster2pgsql", "shp2pgsql", "gdalinfo", "osm2pgrouting"] # CLI toolsrows = [] # one row per toolfor t in tools: # every tool path = shutil.which(t) # where it is, or None ver =""# version stringif path: # ask the tool for its version args = [path] if t in ("raster2pgsql", "shp2pgsql") else [path, "--version"] # loaders print help r = subprocess.run(args, capture_output=True, text=True) # run it lines = (r.stdout + r.stderr).strip().splitlines() # all output lines ver =next((l.strip() for l in lines if"RELEASE"in l), lines[0] if lines else"")[:60] # version line rows.append({"tool": t, "found": bool(path), "version": ver}) # storepd.DataFrame(rows) # show the table
tool
found
version
0
psql
True
psql (PostgreSQL) 18.7
1
pg_dump
True
pg_dump (PostgreSQL) 18.7
2
ogr2ogr
True
GDAL 3.13.3 "Iowa City", released 2026/08/13
3
ogrinfo
True
GDAL 3.13.3 "Iowa City", released 2026/08/13
4
raster2pgsql
True
RELEASE: 3.7.0 GDAL_VERSION=31303 (f3b3ea7)
5
shp2pgsql
True
RELEASE: 3.7.0 (f3b3ea7)
6
gdalinfo
True
GDAL 3.13.3 "Iowa City", released 2026/08/13
7
osm2pgrouting
False
If raster2pgsql and shp2pgsql are missing on the host but Docker is running, use them inside the container: docker exec geolattice-postgis raster2pgsql .... osm2pgrouting is optional; notebook 06_03_02 builds the routing graph with OSMnx and SQL instead.
Connecting with psycopg
psycopg (version 3) is the PostgreSQL driver for Python. It sends SQL to the server and returns rows as Python tuples. Everything else in this notebook (SQLAlchemy, GeoAlchemy2, GeoPandas, geolattice.geolatticedb) uses it underneath.
Code
import psycopg # PostgreSQL driverwith psycopg.connect(PG_DSN) as conn: # open a connection (closed at the end of the block)with conn.cursor() as cur: # a cursor sends SQL and fetches results cur.execute("SELECT version()") # server versionprint(cur.fetchone()[0][:70]) cur.execute("CREATE EXTENSION IF NOT EXISTS postgis") # enable PostGIS in this database cur.execute("SELECT postgis_full_version()") # PostGIS, GEOS, PROJ and GDAL versionsprint(cur.fetchone()[0][:160], "...")
PostgreSQL 18.7 on x86_64-conda-linux-gnu, compiled by x86_64-conda-li
POSTGIS="3.7.0 f3b3ea7" [EXTENSION] PGSQL="180" GEOS="3.15.0-CAPI-1.21.0" PROJ="9.9.0 NETWORK_ENABLED=OFF URL_ENDPOINT=https://cdn.proj.org USER_WRITABLE_DIRECT ...
Extensions are installed on the server but must be enabled in each database with CREATE EXTENSION. The catalog pg_available_extensions shows which ones this server offers:
Code
wanted = ["postgis", "postgis_raster", "postgis_topology", "pgrouting", "h3", "h3_postgis", "mobilitydb", "timescaledb"]with psycopg.connect(PG_DSN, autocommit=True) as conn: # autocommit: each statement is its own transaction avail =dict(conn.execute("SELECT name, default_version FROM pg_available_extensions").fetchall()) # server rows = [] # one row per extensionfor ext in wanted: # try to enable each one status ="not available on this server"# defaultif ext in avail: # the server has ittry: conn.execute(f"CREATE EXTENSION IF NOT EXISTS {ext} CASCADE") # enable it in this database status ="enabled"except psycopg.Error as e: # e.g. TimescaleDB needs shared_preload_libraries status =f"error: {e.diag.message_primary[:50]}" rows.append({"extension": ext, "version": avail.get(ext, ""), "status": status}) # storepd.DataFrame(rows) # show the table
extension
version
status
0
postgis
3.7.0
enabled
1
postgis_raster
3.7.0
enabled
2
postgis_topology
3.7.0
enabled
3
pgrouting
4.0.2
enabled
4
h3
not available on this server
5
h3_postgis
not available on this server
6
mobilitydb
not available on this server
7
timescaledb
not available on this server
Only the extensions marked enabled are used directly. Notebooks 06_03_03 and 06_03_04 check for TimescaleDB, MobilityDB and h3-pg and use plain PostGIS when they are missing.
Always pass values as parameters, never by formatting them into the SQL string. Parameters are sent separately from the SQL text, so quotes in the data cannot change the statement. A real example: O’Brien County, Iowa.
Code
counties = atlas_counties() # county polygonswith psycopg.connect(PG_DSN) as conn: # connect conn.execute("DROP TABLE IF EXISTS county_names") # small demo table conn.execute("CREATE TABLE county_names (fips text PRIMARY KEY, name text)") # two columnswith conn.cursor() as cur: # a cursor for many inserts cur.executemany("INSERT INTO county_names VALUES (%s, %s)", counties[["fips", "name"]].itertuples(index=False)) # parameters: safe for any text conn.commit() # save the table before the experiment below name ="O'Brien"# a county name with an apostrophetry: # string formatting breaks the SQL (and would allow SQL injection) conn.execute(f"SELECT fips FROM county_names WHERE name = '{name}'")except psycopg.errors.SyntaxErroras e:print("f-string SQL fails:", e.diag.message_primary) conn.rollback() # clear the failed transaction row = conn.execute("SELECT fips, name FROM county_names WHERE name = %s", (name,)).fetchone() # parameterprint("parameterized query:", row)
f-string SQL fails: syntax error at or near "Brien"
parameterized query: ('19141', "O'Brien")
Connecting with SQLAlchemy and GeoAlchemy2
SQLAlchemy adds a connection pool (connections are reused instead of opened for every query) and works with pandas and GeoPandas. GeoDataFrame.to_postgis() and geopandas.read_postgis() take a SQLAlchemy engine. The URL scheme postgresql+psycopg:// selects the psycopg 3 driver.
Code
from sqlalchemy import create_engine, text # engine and SQL textengine = create_engine(PG_DSN.replace("postgresql://", "postgresql+psycopg://", 1), pool_pre_ping=True) # poolprint(engine.url.render_as_string(hide_password=True)) # never print the passwordcounties.to_postgis("counties", engine, if_exists="replace", index=False) # GeoDataFrame -> tablewith engine.begin() as con: # a transaction (committed at the end of the block) con.execute(text("CREATE INDEX IF NOT EXISTS counties_geom_gist ON counties USING GIST (geometry)"))ny = gpd.read_postgis(text("SELECT fips, name, geometry FROM counties WHERE statefp = :st"), engine, params={"st": "36"}, geom_col="geometry") # table -> GeoDataFrame (named parameter)print(f"{len(ny)} New York counties, CRS {ny.crs.to_epsg()}") # the SRID comes back as the CRSpd.read_sql("SELECT statefp, count(*) AS n FROM counties GROUP BY 1 ORDER BY 2 DESC LIMIT 3", engine) # plain SQL
postgresql+psycopg://postgres:***@localhost:5432/geolattice
62 New York counties, CRS 4326
statefp
n
0
48
254
1
13
159
2
51
134
GeoAlchemy2 adds PostGIS types (Geometry, Geography, Raster) and functions (func.ST_DWithin, …) to SQLAlchemy. Defining tables in Python gives typed columns, constraints and the spatial index in one place. We build a table of PM2.5 monitors from the EPA AirData sites in the Atlas.
Code
from sqlalchemy import Column, Integer, String, Float, select, func # SQL building blocksfrom sqlalchemy.orm import declarative_base, Session # ORM classesfrom geoalchemy2 import Geometry, Geography # PostGIS column typesfrom geoalchemy2.shape import to_shape # database geometry -> ShapelyBase = declarative_base() # registry of table classesclass Monitor(Base): # one row per EPA monitor __tablename__ ="pm25_monitors"# table nameid= Column(Integer, primary_key=True) # surrogate primary key site_id = Column(String(12), nullable=False) # AQS site id (state-county-site) name = Column(String) # site name state = Column(String) # state name pm25_2024 = Column(Float) # annual mean PM2.5 in 2024 (µg/m³) geom = Column(Geometry("POINT", srid=4326)) # typed geometry column; GeoAlchemy2 adds a GiST indexBase.metadata.drop_all(engine, tables=[Monitor.__table__]) # start freshBase.metadata.create_all(engine) # CREATE TABLE ... and CREATE INDEX ... USING gistaq = pd.DataFrame(atlas_js("assets/air_quality_data.js")["sites"]) # all EPA monitors in the Atlaspm = aq[aq.p =="PM25"].dropna(subset=["lat", "lon"]) # PM2.5 monitors with coordinateswith Session(engine) as s: # an ORM session (a unit of work) s.add_all([Monitor(site_id=r.id, name=r.n, state=r.st, pm25_2024=(r.means or {}).get("2024"), geom=f"SRID=4326;POINT({r.lon}{r.lat})") for r in pm.itertuples()]) # EWKT input s.commit() # write all rows in one transaction n = s.scalar(select(func.count()).select_from(Monitor)) # SELECT count(*)print(f"{n:,} PM2.5 monitors stored")
1,546 PM2.5 monitors stored
Code
syracuse ="SRID=4326;POINT(-76.1474 43.0481)"# downtown Syracuse, NYwith Session(engine) as s: # query with PostGIS functions written in Python q = (select(Monitor.name, Monitor.pm25_2024, func.ST_Distance(func.Geography(Monitor.geom), func.Geography(syracuse)).label("dist_m")) .where(func.ST_DWithin(func.Geography(Monitor.geom), func.Geography(syracuse), 100_000)) # within 100 km .order_by("dist_m")) # nearest firstprint(q.compile(engine, compile_kwargs={"literal_binds": True})) # the SQL that GeoAlchemy2 generates near = pd.DataFrame(s.execute(q).all(), columns=["monitor", "pm25_2024", "dist_m"]) # run itnear.assign(dist_km=(near.dist_m /1000).round(1)).drop(columns="dist_m") # show in km
SELECT pm25_monitors.name, pm25_monitors.pm25_2024, ST_Distance(Geography(pm25_monitors.geom), Geography('SRID=4326;POINT(-76.1474 43.0481)')) AS dist_m
FROM pm25_monitors
WHERE ST_DWithin(Geography(pm25_monitors.geom), Geography('SRID=4326;POINT(-76.1474 43.0481)'), 100000) ORDER BY dist_m
monitor
pm25_2024
dist_km
0
EAST SYRACUSE
5.1533
7.2
1
EAST SYRACUSE
5.0855
7.2
The ORM query compiles to ordinary PostGIS SQL with ST_DWithin on geography, so the distance threshold is in metres and the GiST index is used. The monitors around Syracuse report annual mean PM2.5 well below the 2024 EPA annual standard of 9 µg/m³.
geolattice.geolatticedb.connect(): one interface for every backend
Each engine has its own driver and quirks: psycopg and SQLAlchemy for PostGIS, sqlite3 plus mod_spatialite for SpatiaLite and GeoPackage, the duckdb module and its spatial extension for DuckDB. geolattice.geolatticedb hides these differences behind one SpatialDB object:
Call
What it does
pdb.connect(backend, ...)
open "postgis" (DSN or host/user/…), "spatialite"/"geopackage" (path=) or "duckdb" (path= or memory)
con.load(data, table)
load a GeoDataFrame or a vector/raster file; detect the SRID; build the spatial index
con.query(sql)
run SQL and return a GeoDataFrame (or a DataFrame when no geometry is returned)
common spatial operations, written once for all engines
con.raster, con.network, con.tiles
PostGIS raster, pgRouting and vector tiles (PostGIS only)
Backend names have aliases (pg, postgres, sqlite, gpkg, duck). Connections are context managers, so with pdb.connect(...) as con: closes them automatically.
Code
opened = { # one connection per backend, all with the same call"postgis": pdb.connect("postgis", dsn=PG_DSN),"spatialite": pdb.connect("spatialite", path=OUT /"geolattice.sqlite"),"geopackage": pdb.connect("gpkg", path=OUT /"geolattice.gpkg"),"duckdb": pdb.connect("duckdb", path=OUT /"geolattice.duckdb"),}for name, con in opened.items(): # every backend con.load(counties[counties.statefp =="36"], "ny_counties") # identical loading codeprint(f"{con!r:<75} tables={con.tables()[:3]} srid={con.srid('ny_counties')}")
<SpatialDB backend='postgis' at 'postgresql+psycopg://postgres:***@localhost:5432/geolattice'> tables=['counties', 'county_names', 'ny_counties'] srid=4326
<SpatialDB backend='spatialite' at '/home/zia207/Github/GeoLattice/Data/06_spatialDB/outputs/06_01_02/geolattice.sqlite'> tables=['ny_counties'] srid=4326
<SpatialDB backend='geopackage' at '/home/zia207/Github/GeoLattice/Data/06_spatialDB/outputs/06_01_02/geolattice.gpkg'> tables=['ny_counties'] srid=4326
<SpatialDB backend='duckdb' at '/home/zia207/Github/GeoLattice/Data/06_spatialDB/outputs/06_01_02/geolattice.duckdb'> tables=['ny_counties', 'pygis_geometry_columns'] srid=4326
Code
sql ="SELECT name, ST_Area(ST_Transform(geom, 5070)) / 1e6 AS area_km2 FROM ny_counties ORDER BY 2 DESC LIMIT 3"# DuckDB's ST_Transform takes CRS strings, and always_xy keeps the lon/lat axis ordersql_duck = sql.replace("ST_Transform(geom, 5070)", "ST_Transform(geom, 'EPSG:4326', 'EPSG:5070', always_xy := true)")for name in ["postgis", "spatialite", "duckdb"]: # three engines df = opened[name].query(sql_duck if name =="duckdb"else sql) # DataFrame (no geometry selected)print(f"{name:<10}", ", ".join(f"{r.name}{r.area_km2:,.0f} km²"for r in df.itertuples()))
postgis St. Lawrence 7,322 km², Essex 4,981 km², Hamilton 4,668 km²
spatialite St. Lawrence 7,322 km², Essex 4,981 km², Hamilton 4,668 km²
duckdb St. Lawrence 7,322 km², Essex 4,981 km², Hamilton 4,668 km²
PostGIS and SpatiaLite ran the identical statement, and all three engines return the same areas. DuckDB follows the same function names but differs in details: its ST_Transform takes the source and target CRS as strings, and always_xy := true tells it that coordinates are stored as longitude/latitude (the EPSG definition of 4326 lists latitude first). Such differences are why geolatticedb writes the engine-specific SQL for its own methods (loading, indexes, joins, nearest neighbours). With echo=True it prints every statement it sends:
Code
with pdb.connect("postgis", dsn=PG_DSN) as con: # PostGIS connection con.echo =True# from now on, print every SQL statement nb_ = con.spatial_join("ny_counties", "ny_counties", predicate="touches", right_columns=["name"]) # neighboursprint(f"{len(nb_):,} rows: each shared county boundary appears twice (A touches B, B touches A)")
SELECT f_geometry_column FROM geometry_columns WHERE f_table_schema=%s AND f_table_name=%s UNION ALL SELECT f_geography_column FROM geography_columns WHERE f_table_schema=%s AND f_table_name=%s
SELECT f_geometry_column FROM geometry_columns WHERE f_table_schema=%s AND f_table_name=%s UNION ALL SELECT f_geography_column FROM geography_columns WHERE f_table_schema=%s AND f_table_name=%s
SELECT column_name FROM information_schema.columns WHERE table_schema=%s AND table_name=%s ORDER BY ordinal_position
SELECT Find_SRID(%s, %s, %s)
SELECT l."fips", l."statefp", l."name", l."census_sqmi", l."geom", r."name" AS "right_name" FROM "ny_counties" AS l JOIN "ny_counties" AS r ON ST_Touches(l."geom", r."geom")
284 rows: each shared county boundary appears twice (A touches B, B touches A)
Code
for con in opened.values(): # close every connection con.close()engine.dispose() # close the SQLAlchemy pool
Troubleshooting
Message
Cause
Fix
connection refused / could not connect to server
server not running, or another port
docker compose ps; pg_ctl status; check the port in GEOLATTICE_PG_DSN
password authentication failed
wrong user or password
check POSTGRES_PASSWORD; the password is set only when the volume is first created (docker compose down -v resets it)
extension "pgrouting" is not available
the image or conda environment lacks it
use the Dockerfile above, or conda install pgrouting
port is already allocated
a local PostgreSQL already uses 5432
stop it, or map "5434:5432" and change the DSN
Could not load mod_spatialite
SpatiaLite library missing
conda install libspatialite or apt install libsqlite3-mod-spatialite
DuckDB Failed to download extension "spatial"
no internet access
pip install duckdb-extension-spatial
PROJ: proj_create_from_database
PROJ cannot find proj.db
activate the conda environment (it sets PROJ_DATA), or set PROJ_DATA
Summary and exercises
Main points
Docker gives a complete PostGIS server (plus pgRouting, h3-pg and MobilityDB) with three files and one command; conda installs PostgreSQL, PostGIS and pgRouting without Docker.
Extensions are installed on the server and enabled per database with CREATE EXTENSION.
psycopg sends SQL; SQLAlchemy adds pooling and pandas/GeoPandas integration; GeoAlchemy2 adds PostGIS types and functions to Python table definitions.
Pass values as parameters (%s, :name), never by string formatting.
geolattice.geolatticedb.connect() opens PostGIS, SpatiaLite, GeoPackage or DuckDB with one call, and the same methods work on all four.
Start the optional TimescaleDB service (docker compose --profile timescale up -d) and connect to it on port 5433 with pdb.connect("postgis", port=5433, ...). Which extensions are available there?
Add a CHECK (pm25_2024 >= 0) constraint to the Monitor class and try to insert a negative value.
Use GeoAlchemy2 to find the five PM2.5 monitors with the highest 2024 mean within 200 km of New York City.
Connect to a GeoPackage with pdb.connect("gpkg", path=...), load the PM2.5 monitors and open the file in QGIS.