Spatial Databases

File-based Spatial Databases

A spatial database does not have to be a server. SQLite stores a complete relational database in one ordinary file, and two spatial formats build on it: SpatiaLite, which adds spatial types, functions and indexes to SQLite, and the OGC GeoPackage standard, which defines how layers, attribute tables and coordinate systems are stored in that file. Both need no installation beyond a library, can be copied or emailed, and open in QGIS, ArcGIS, GDAL and Python. This notebook works through both with Atlas data for New York and ends with a practical question: when is a file enough, and when should the data move to PostGIS?

Learning objectives

  1. Create a SpatiaLite database from Python, add a geometry column, build an R*Tree index and query it in SQL.
  2. Store several vector layers and a non-spatial attribute table in one GeoPackage, and read and write them with pyogrio.
  3. Look inside a GeoPackage (its metadata tables and R-tree), and run SQL across its layers.
  4. Recognize the limits of single-file databases (one writer at a time, network drives) and decide when to move to PostGIS.

Data

Data Source Use
US county boundaries USA Health Data Atlas (assets/geojson_counties_fips.json) Layers, joins
EPA Superfund NPL sites USA Health Data Atlas (assets/superfund_npl_data.js) SpatiaLite points
EPA AirData PM2.5 monitors USA Health Data Atlas (assets/air_quality_data.js) GeoPackage layer
County Health Rankings 2024 (CHR) USA Health Data Atlas (data/county_health_ranking/chr_county_2024.csv) Attribute table

Contents

  1. Setup
  2. SQLite and SpatiaLite basics
  3. Spatial indexes in SpatiaLite
  4. GeoPackage: layers and attribute tables
  5. Inside a GeoPackage
  6. Reading and writing with pyogrio
  7. When file-based storage is enough, and when to move to PostGIS
  8. 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 control
warnings.filterwarnings("ignore", category=UserWarning)  # hide routine library warnings

import sqlite3  # SQLite (part of the Python standard library)
import threading  # run two writers at the same time
import time  # timing
import numpy as np  # arrays
import pandas as pd  # tables
import geopandas as gpd  # vector data
import shapely  # geometry encodings
import pyogrio  # fast vector I/O through GDAL/OGR
import matplotlib.pyplot as plt  # figures

from geolattice import geolatticedb as pdb  # GeoLattice spatial database tools

plt.rcParams.update({"figure.dpi": 110})  # figure resolution
Code
import os  # environment variables
import json  # JSON parsing
import urllib.request  # download files over HTTP
from 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 notebook
ROOT = 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 folder
DATA = ROOT / "Data" / "06_spatialDB"  # data folder of this module
OUT = DATA / "outputs" / "06_01_03"  # outputs written by this notebook
OUT.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 GitHub
ATLAS = "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 path
    if not path.exists():  # download only if missing
        path.parent.mkdir(parents=True, exist_ok=True)  # create the cache folder
        print(f"Downloading {rel} ...")  # progress message
        urllib.request.urlretrieve(f"{base}/{rel}", path)  # copy the URL to the local path
    return path  # the local path

def 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 text
    return json.loads(text[text.index("=") + 1:].strip().rstrip(";"))  # strip the assignment and parse

def 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 names
    return g[["fips", "statefp", "name", "census_sqmi", "geometry"]].set_crs(4326, allow_override=True)

def superfund_sites():  # EPA Superfund National Priorities List sites from the Atlas
    """Superfund NPL sites as points (EPSG:4326)."""
    s = pd.DataFrame(atlas_js("assets/superfund_npl_data.js")["sites"])  # one row per site
    s = s.dropna(subset=["lat", "lon"])  # keep sites with coordinates
    s = s[["epa_id", "name", "status", "state", "city", "county", "score", "listed", "lat", "lon"]]  # main fields
    return gpd.GeoDataFrame(s, geometry=gpd.points_from_xy(s.lon, s.lat), crs=4326)  # points

def chr_county(year):  # County Health Rankings (CHR) county table of one year, from the Atlas
    """County Health Rankings & Roadmaps measures for all counties in one release year (2020-2025)."""
    d = pd.read_csv(fetch(f"data/county_health_ranking/chr_county_{year}.csv"), dtype={"fips": str}, low_memory=False)
    d["fips"] = d["fips"].str.zfill(5)  # restore leading zeros (01001, ...)
    return d[~d["fips"].str.endswith("000")].reset_index(drop=True)  # drop state and national rows

# PostGIS connection string (see 06_01_02 for the Docker container); override with GEOLATTICE_PG_DSN
PG_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
Code
counties = atlas_counties()  # all US counties
ny = counties[counties.statefp == "36"].reset_index(drop=True)  # 62 New York counties
sites = superfund_sites()  # Superfund NPL sites
aq = pd.DataFrame(atlas_js("assets/air_quality_data.js")["sites"])  # EPA AirData monitors
pm = aq[(aq.p == "PM25")].dropna(subset=["lat", "lon"]).copy()  # PM2.5 monitors
pm["pm25_2024"] = [(m or {}).get("2024") for m in pm["means"]]  # annual mean 2024 (µg/m³)
pm = gpd.GeoDataFrame(pm[["id", "n", "st", "city", "pm25_2024"]].rename(columns={"id": "site_id", "n": "name", "st": "state"}),
                      geometry=gpd.points_from_xy(pm.lon, pm.lat), crs=4326)  # monitors as points
chr24 = chr_county(2024)  # County Health Rankings, 2024 release
print(f"{len(ny)} NY counties, {len(sites):,} Superfund sites, {len(pm):,} PM2.5 monitors, CHR {chr24.shape}")
62 NY counties, 1,840 Superfund sites, 1,546 PM2.5 monitors, CHR (3150, 250)

SQLite and SpatiaLite basics

SQLite ships with Python as the sqlite3 module. It knows tables, indexes, transactions and SQL, but no geometry. SpatiaLite is a loadable extension (mod_spatialite) that adds about 500 SQL functions, a spatial_ref_sys table with the EPSG registry, geometry columns and R*Tree spatial indexes. Loading an extension has to be allowed explicitly on the connection:

Code
def open_spatialite(path):  # a sqlite3 connection with SpatiaLite loaded
    """Open (or create) a SQLite file and load the SpatiaLite extension."""
    con = sqlite3.connect(path)  # plain SQLite connection
    # Some Python builds omit enable_load_extension; this calls libsqlite3 either way
    pdb._load_spatialite(con, pdb._find_spatialite())  # library names/paths to try (conda, Homebrew, apt)
    return con

db = OUT / "health.sqlite"  # the database file
db.unlink(missing_ok=True)  # start fresh
con = open_spatialite(db)  # create it
con.execute("SELECT InitSpatialMetadata(1)")  # create spatial_ref_sys, geometry_columns, ... (1 = in one transaction)
print("SpatiaLite", con.execute("SELECT spatialite_version()").fetchone()[0],
      "| GEOS", con.execute("SELECT geos_version()").fetchone()[0])
print("EPSG codes in spatial_ref_sys:", con.execute("SELECT count(*) FROM spatial_ref_sys").fetchone()[0])
SpatiaLite 5.1.0 | GEOS 3.15.0-CAPI-1.21.0
EPSG codes in spatial_ref_sys: 6559

A geometry column is added with AddGeometryColumn(table, column, srid, type, dimension). SpatiaLite then records the column in geometry_columns and installs triggers that reject geometries of the wrong type or SRID. Geometries are created with SQL functions such as MakePoint(x, y, srid) or GeomFromText(wkt, srid):

Code
con.execute("""CREATE TABLE superfund (
    epa_id TEXT PRIMARY KEY, name TEXT, status TEXT, state TEXT, score REAL)""")  # attribute columns
con.execute("SELECT AddGeometryColumn('superfund', 'geom', 4326, 'POINT', 'XY')")  # typed geometry column
con.executemany("INSERT INTO superfund VALUES (?, ?, ?, ?, ?, MakePoint(?, ?, 4326))",  # parameters
                sites[["epa_id", "name", "status", "state", "score", "lon", "lat"]].itertuples(index=False))
con.commit()  # save
print(con.execute("SELECT count(*), GeometryType(geom), SRID(geom) FROM superfund").fetchone())  # check

try:  # the triggers enforce the declared type
    con.execute("INSERT INTO superfund (epa_id, geom) VALUES ('X', GeomFromText('LINESTRING(0 0, 1 1)', 4326))")
except sqlite3.IntegrityError as e:
    print("rejected:", str(e)[:90])
(1840, 'POINT', 4326)
rejected: superfund.geom violates Geometry constraint [geom-type or SRID not allowed]

Counties come from a GeoDataFrame, so we write their WKB directly. The query below then answers a spatial question in SQL: which New York counties contain Superfund sites with a Hazard Ranking System (HRS) score above 50? SpatiaLite’s ST_Area returns the area in the units of the SRID, so the polygons are transformed to the CONUS Albers projection (EPSG:5070) first to get square metres.

Code
con.execute("CREATE TABLE counties (fips TEXT PRIMARY KEY, name TEXT, statefp TEXT)")  # attributes
con.execute("SELECT AddGeometryColumn('counties', 'geom', 4326, 'MULTIPOLYGON', 'XY')")  # geometry column
rows = [(r.fips, r.name, r.statefp, shapely.to_wkb(shapely.MultiPolygon([r.geometry])
         if r.geometry.geom_type == "Polygon" else r.geometry)) for r in counties.itertuples()]  # promote to multi
con.executemany("INSERT INTO counties VALUES (?, ?, ?, CastToMulti(GeomFromWKB(?, 4326)))", rows)  # WKB in
con.commit()  # save

q = """
SELECT c.name, count(*) AS sites_hrs_gt50, round(ST_Area(Transform(c.geom, 5070)) / 1e6) AS area_km2
FROM counties c JOIN superfund s ON ST_Within(s.geom, c.geom)
WHERE c.statefp = '36' AND s.score > 50
GROUP BY c.fips ORDER BY 2 DESC LIMIT 5
"""
pd.read_sql(q, con)  # SQL result as a DataFrame
name sites_hrs_gt50 area_km2
0 Nassau 3 832.0
1 Saratoga 2 2237.0
2 Niagara 2 1372.0
3 Erie 2 2774.0
4 Ulster 1 2985.0

Spatial indexes in SpatiaLite

The query above tested every site against every New York county. SpatiaLite stores spatial indexes as SQLite **R*Tree virtual tables** named idx_<table>_<column>, holding one bounding box per row. Unlike PostGIS, the index is not used automatically: the query must ask for it, either through the R*Tree table or through the SpatialIndex virtual table.

Code
con.execute("SELECT CreateSpatialIndex('counties', 'geom')")  # builds idx_counties_geom (R*Tree)
con.execute("SELECT CreateSpatialIndex('superfund', 'geom')")  # builds idx_superfund_geom
con.commit()  # save
print(pd.read_sql("SELECT * FROM idx_counties_geom LIMIT 3", con))  # what the R*Tree stores: rowid + box

def timed(sql, n=5):  # median run time of a query
    ts = []  # run times
    for _ in range(n):  # repeat
        t0 = time.perf_counter(); res = con.execute(sql).fetchall(); ts.append(time.perf_counter() - t0)
    return res, np.median(ts) * 1000  # result and milliseconds

no_idx = """SELECT c.fips, count(*) FROM counties c JOIN superfund s ON ST_Within(s.geom, c.geom)
GROUP BY c.fips"""  # exact test on every pair
with_idx = """SELECT c.fips, count(*) FROM superfund s JOIN counties c ON ST_Within(s.geom, c.geom)
AND c.ROWID IN (SELECT ROWID FROM SpatialIndex
                WHERE f_table_name = 'counties' AND search_frame = s.geom)
GROUP BY c.fips"""  # R*Tree first, exact test on candidates
r1, t1 = timed(no_idx, 1); r2, t2 = timed(with_idx)  # run both
print(f"without index: {t1:8.0f} ms | with R*Tree: {t2:6.0f} ms | same result: {sorted(r1) == sorted(r2)}")
   pkid        xmin        xmax       ymin       ymax
0    14 -173.120773 -153.001251  58.551842  62.295334
1    19 -171.849991 -159.384750  62.937527  66.581116
2   679 -166.850647 -141.002670  67.998940  71.352562
without index:     2103 ms | with R*Tree:     34 ms | same result: True

The R*Tree turns a scan of millions of point-in-polygon tests into a few thousand box lookups followed by exact tests on the candidates, and gives the same answer. Forgetting the SpatialIndex clause is the most common performance mistake with SpatiaLite; PostGIS and DuckDB use their indexes without being asked.

Code
con.close()  # close the SpatiaLite file
print(f"health.sqlite: {db.stat().st_size / 1e6:.1f} MB, one file with {len(counties):,} counties and {len(sites):,} sites")
health.sqlite: 9.7 MB, one file with 3,221 counties and 1,840 sites

GeoPackage: layers and attribute tables

GeoPackage (.gpkg, OGC standard 12-128) is the open replacement for the shapefile. It removes the shapefile’s limits (2 GB, 10-character field names, one layer, no real dates, separate .dbf/.prj/.shx files) and keeps everything in one SQLite file:

  • feature layers (tables with a geometry column), each with its own SRID;
  • attribute tables without geometry, such as a table of health measures;
  • tile matrix sets for raster tiles;
  • metadata and extensions (R-tree indexes, schemas, related tables).

We write four tables into ny_health.gpkg with pyogrio: counties, Superfund sites and PM2.5 monitors as layers, and the County Health Rankings as an attribute table.

Code
gpkg = OUT / "ny_health.gpkg"  # the GeoPackage file
gpkg.unlink(missing_ok=True)  # start fresh
measures = ["fips", "county", "adult_obesity_pct", "adult_smoking_pct", "physical_inactivity_pct",
            "years_of_potential_life_lost_rate", "air_pollution_particulate_matter_average_daily_pm2_5",
            "uninsured", "median_household_income"]  # a few CHR measures
chr_ny = chr24[chr24.state_abbr == "NY"][measures].copy()  # New York counties only

pyogrio.write_dataframe(ny, gpkg, layer="counties")  # layer 1: polygons (EPSG:4326)
pyogrio.write_dataframe(sites[sites.state == "NY"], gpkg, layer="superfund")  # layer 2: points
pyogrio.write_dataframe(pm[pm.state == "New York"].to_crs(32618), gpkg, layer="pm25_monitors")  # layer 3: UTM 18N
pyogrio.write_dataframe(chr_ny, gpkg, layer="chr_2024")  # table 4: attributes only (no geometry)

pyogrio.list_layers(gpkg)  # layer names and geometry types (None = attribute table)
array([['counties', 'MultiPolygon'],
       ['superfund', 'Point'],
       ['pm25_monitors', 'Point'],
       ['chr_2024', None]], dtype=object)
Code
info = []  # one row per layer
for name, gtype in pyogrio.list_layers(gpkg):  # every layer
    i = pyogrio.read_info(gpkg, layer=name)  # metadata without reading features
    info.append({"layer": name, "geometry": gtype, "features": i["features"], "crs": i["crs"],
                 "fields": len(i["fields"]), "first fields": ", ".join(i["fields"][:4])})
pd.DataFrame(info)  # show the table
layer geometry features crs fields first fields
0 counties MultiPolygon 62 EPSG:4326 4 fips, statefp, name, census_sqmi
1 superfund Point 122 EPSG:4326 10 epa_id, name, status, state
2 pm25_monitors Point 42 EPSG:32618 5 site_id, name, state, city
3 chr_2024 NaN 62 NaN 9 fips, county, adult_obesity_pct, adult_smoking...

Each layer keeps its own coordinate system: the monitors are stored in UTM zone 18N (EPSG:32618) next to lon/lat layers, and the CHR table has no geometry at all. A shapefile would need four sets of files for the same content.

Inside a GeoPackage

Because a GeoPackage is an SQLite database, the standard sqlite3 module can open it. The standard defines a few metadata tables:

Table Contents
gpkg_contents one row per layer or table: name, type (features, attributes, tiles), extent, SRID
gpkg_geometry_columns geometry column, type and SRID of each feature layer
gpkg_spatial_ref_sys coordinate systems used in the file (WKT definitions)
gpkg_extensions extensions in use, e.g. the R-tree index
rtree_<layer>_<column> the R-tree index of each layer (SQLite R*Tree)
Code
raw = sqlite3.connect(gpkg)  # open the GeoPackage as plain SQLite (no SpatiaLite needed)
print(pd.read_sql("SELECT table_name, data_type, srs_id, round(min_x, 2) AS min_x, round(max_y, 2) AS max_y "
                  "FROM gpkg_contents", raw))  # the layer catalog
print(pd.read_sql("SELECT srs_id, organization, substr(definition, 1, 45) AS wkt FROM gpkg_spatial_ref_sys", raw))
print([r[0] for r in raw.execute("SELECT name FROM sqlite_master WHERE name LIKE 'rtree_%' AND type = 'table'")])
      table_name   data_type  srs_id      min_x       max_y
0       counties    features    4326     -79.76       45.02
1      superfund    features    4326     -79.13       44.98
2  pm25_monitors    features   32618  145108.30  4916166.03
3       chr_2024  attributes       0        NaN         NaN
   srs_id organization                                            wkt
0      -1         NONE                                      undefined
1       0         NONE                                      undefined
2    4326         EPSG  GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WG
3   32618         EPSG  PROJCS["WGS 84 / UTM zone 18N",GEOGCS["WGS 84
['rtree_counties_geom', 'rtree_counties_geom_rowid', 'rtree_counties_geom_node', 'rtree_counties_geom_parent', 'rtree_superfund_geom', 'rtree_superfund_geom_rowid', 'rtree_superfund_geom_node', 'rtree_superfund_geom_parent', 'rtree_pm25_monitors_geom', 'rtree_pm25_monitors_geom_rowid', 'rtree_pm25_monitors_geom_node', 'rtree_pm25_monitors_geom_parent']

Geometries are stored as GeoPackage binary (GPB): a short header with the magic bytes GP, a version, the SRID and an optional envelope, followed by standard WKB. Decoding one by hand shows the structure:

Code
blob = raw.execute("SELECT geom FROM superfund LIMIT 1").fetchone()[0]  # one geometry blob
flags = blob[3]  # header flags byte
env_len = {0: 0, 1: 32, 2: 48, 3: 48, 4: 64}[(flags >> 1) & 0b111]  # envelope size from the flags
srid = int.from_bytes(blob[4:8], "little" if flags & 1 else "big")  # SRID in the header
geom = shapely.from_wkb(blob[8 + env_len:])  # the rest is ordinary WKB
print(f"magic={blob[:2]!r} version={blob[2]} srid={srid} envelope={env_len} bytes -> {geom}")
raw.close()  # close
magic=b'GP' version=0 srid=4326 envelope=0 bytes -> POINT (-73.657844 40.737337)

Reading and writing with pyogrio

pyogrio reads GeoPackages (and every other OGR format) much faster than the older Fiona-based path, because it moves whole columns at once, optionally as Apache Arrow. It can also push work into the file: read only some columns, filter by attribute (where) or by bounding box (bbox, which uses the R-tree), or run SQL that joins layers.

Code
t0 = time.perf_counter()  # time a full read
full = pyogrio.read_dataframe(gpkg, layer="counties")  # all features and fields
t_full = time.perf_counter() - t0

onondaga_bbox = tuple(ny.loc[ny.fips == "36067"].total_bounds)  # box around Onondaga County
part = pyogrio.read_dataframe(gpkg, layer="counties", bbox=onondaga_bbox, columns=["fips", "name"])  # R-tree filter
big = pyogrio.read_dataframe(gpkg, layer="superfund", where="score > 50")  # attribute filter (SQL WHERE)
arrow = pyogrio.read_dataframe(gpkg, layer="counties", use_arrow=True)  # Arrow transfer
print(f"full read: {len(full)} counties in {t_full * 1000:.0f} ms")
print(f"bbox read: {len(part)} counties touch the Onondaga box -> {', '.join(part.name)}")
print(f"where read: {len(big)} NY Superfund sites with HRS score > 50")
full read: 62 counties in 4 ms
bbox read: 5 counties touch the Onondaga box -> Cayuga, Oswego, Cortland, Madison, Onondaga
where read: 15 NY Superfund sites with HRS score > 50

SQL with sql_dialect="SQLITE" can join a feature layer to the attribute table and use SpatiaLite functions, so a choropleth of premature death can be read directly from the file:

Code
sql = """
SELECT c.fips, c.name, h.years_of_potential_life_lost_rate AS ypll, h.adult_obesity_pct AS obesity,
       (SELECT count(*) FROM superfund s WHERE ST_Within(s.geom, c.geom)) AS n_superfund, c.geom
FROM counties c JOIN chr_2024 h ON h.fips = c.fips
"""
joined = pyogrio.read_dataframe(gpkg, sql=sql, sql_dialect="SQLITE")  # one query, three tables
fig, axes = plt.subplots(1, 2, figsize=(14, 5))  # two maps
joined.plot("ypll", ax=axes[0], cmap="OrRd", legend=True, edgecolor="0.5", lw=0.3,
            legend_kwds={"label": "years of potential life lost per 100,000"})  # premature death
joined.plot("obesity", ax=axes[1], cmap="PuBu", legend=True, edgecolor="0.5", lw=0.3,
            legend_kwds={"label": "adult obesity (%)"})  # obesity
sites[sites.state == "NY"].plot(ax=axes[0], color="k", markersize=6, label="Superfund site")  # sites
axes[0].legend(loc="lower right")  # legend
for ax, t in zip(axes, ["Premature death (YPLL), CHR 2024", "Adult obesity, CHR 2024"]):  # titles
    ax.set_title(t); ax.set_axis_off()
plt.tight_layout(); plt.show()  # arrange and draw
joined.drop(columns="geometry").sort_values("ypll", ascending=False).head(5)  # highest premature death

fips name ypll obesity n_superfund
61 36009 Cattaraugus 9635.023897 41.4 3
46 36015 Chemung 9354.575723 36.3 2
57 36105 Sullivan 9184.999426 37.0 0
36 36017 Chenango 9148.970854 38.6 1
17 36035 Fulton 9064.641344 35.4 1

Premature death, measured as years of potential life lost before age 75 (YPLL) per 100,000 people, is highest in rural counties of the Southern Tier and the Catskills (Cattaraugus 9,635, Chemung 9,355, Sullivan 9,185) and, within New York City, in the Bronx (8,835). It is lowest in Putnam, Nassau, Westchester and Manhattan (4,300 to 4,780), about half the Cattaraugus rate. Hamilton County, the least populated county in the state, has no YPLL estimate. Adult obesity follows a similar rural pattern. YPLL comes from vital statistics and obesity from the CDC Behavioral Risk Factor Surveillance System, as compiled by County Health Rankings.

Writing back is just as simple. append=True adds features to an existing layer, and layer_options passes GeoPackage creation options to GDAL:

Code
summary = joined[["fips", "name", "ypll", "obesity", "n_superfund", "geometry"]]  # a derived layer
pyogrio.write_dataframe(summary, gpkg, layer="county_summary", layer_options={"SPATIAL_INDEX": "YES"})  # with R-tree
pyogrio.write_dataframe(pm[pm.state == "New Jersey"].to_crs(32618), gpkg, layer="pm25_monitors", append=True)  # add NJ
print(pyogrio.read_info(gpkg, layer="pm25_monitors")["features"], "monitors after appending New Jersey")
print([l[0] for l in pyogrio.list_layers(gpkg)])  # all layers now in the file
64 monitors after appending New Jersey
['counties', 'superfund', 'pm25_monitors', 'county_summary', 'chr_2024']

When file-based storage is enough, and when to move to PostGIS

SQLite allows many readers but only one writer at a time: a write locks the whole file. The test below starts two threads that each insert 200 rows into the same GeoPackage, the way two people editing a shared file would. With no waiting allowed (timeout=0), one of them fails:

Code
def writer(path, tag, errors, timeout):  # insert rows in many small transactions
    c = sqlite3.connect(path, timeout=timeout)  # timeout: how long to wait for the lock
    try:
        for i in range(200):  # 200 separate commits
            c.execute("INSERT INTO chr_2024 (fips, county) VALUES (?, ?)", (f"T{tag}{i:03d}", "test"))
            c.commit()
    except sqlite3.OperationalError as e:  # typically "database is locked"
        errors.append(f"writer {tag}: {e}")
    finally:
        c.close()

for timeout in (0, 5):  # no waiting, then wait up to 5 s for the lock
    errors = []  # failures of this round
    threads = [threading.Thread(target=writer, args=(gpkg, t, errors, timeout)) for t in "AB"]  # two writers
    [t.start() for t in threads]; [t.join() for t in threads]  # run them at the same time
    print(f"timeout={timeout}s:", errors[0] if errors else "both writers finished (they took turns)")
with sqlite3.connect(gpkg) as c:  # remove the test rows
    c.execute("DELETE FROM chr_2024 WHERE county = 'test'")
timeout=0s: writer A: database is locked
timeout=5s: both writers finished (they took turns)

With a timeout the writers take turns, which works for a few users but serializes all edits. PostgreSQL locks individual rows, so many users and applications can write at once. The same test against PostGIS:

Code
import psycopg  # PostgreSQL driver

def pg_writer(tag, errors):  # same workload against PostGIS
    try:
        with psycopg.connect(PG_DSN) as c:  # each thread has its own connection
            for i in range(200):  # 200 separate commits
                c.execute("INSERT INTO write_test VALUES (%s)", (f"{tag}{i:03d}",)); c.commit()
    except psycopg.Error as e:
        errors.append(str(e))

try:
    with psycopg.connect(PG_DSN, autocommit=True) as c:  # create the test table
        c.execute("DROP TABLE IF EXISTS write_test"); c.execute("CREATE TABLE write_test (id text)")
    errors = []  # failures
    threads = [threading.Thread(target=pg_writer, args=(t, errors)) for t in "AB"]  # two writers
    t0 = time.perf_counter(); [t.start() for t in threads]; [t.join() for t in threads]  # run together
    with psycopg.connect(PG_DSN) as c:
        n = c.execute("SELECT count(*) FROM write_test").fetchone()[0]  # rows written
        c.execute("DROP TABLE write_test"); c.commit()  # clean up
    print(f"PostGIS: {n} rows from 2 concurrent writers in {time.perf_counter() - t0:.2f} s, errors: {errors or 'none'}")
except psycopg.OperationalError as e:  # server not running
    print("PostGIS not reachable (see 06_01_02):", str(e).splitlines()[0])
PostGIS: 400 rows from 2 concurrent writers in 0.07 s, errors: none

Use this checklist to decide:

Situation File (GeoPackage / SpatiaLite) Server (PostGIS)
Users editing at the same time one (or a few, taking turns) many
Data size up to a few GB per file works well terabytes, partitioned tables
Where the data live local disk (not network drives: SQLite locking is unreliable on SMB/NFS) a server everyone reaches
Access control whoever has the file has everything users, roles, row-level security
Web maps and APIs read-only, small GeoServer, pg_tileserv, pg_featureserv, OGC API
Functions needed vector SQL, R*Tree plus rasters, topology, routing (pgRouting), time series
Delivery send one file; open in QGIS/ArcGIS pg_dump, or export to GeoPackage/GeoParquet

A common pattern combines both: PostGIS holds the shared, edited master data, and GeoPackage files carry extracts to field laptops, collaborators and archives. Moving between them is one ogr2ogr command or one geolatticedb call, covered in notebook 06_02_01.

Code
with pdb.connect("postgis", dsn=PG_DSN) as pg:  # copy every GeoPackage layer to PostGIS with geolatticedb
    for name, gtype in pyogrio.list_layers(gpkg):  # every layer
        if gtype is not None:  # feature layers (attribute tables go through pandas, see 06_02_01)
            pg.load(gpkg, f"ny_{name}", layer=name)  # read the layer, keep its SRID, build a GiST index
    loaded = [f"ny_{n}" for n, g in pyogrio.list_layers(gpkg) if g is not None]  # the new tables
    print({t: pg.srid(t) for t in loaded})  # each table kept the SRID of its layer
{'ny_counties': 4326, 'ny_superfund': 4326, 'ny_pm25_monitors': 32618, 'ny_county_summary': 4326}

Summary and exercises

Main points

  • SQLite stores a whole database in one file; SpatiaLite adds geometry columns, about 500 spatial functions and R*Tree indexes through the mod_spatialite extension.
  • In SpatiaLite the spatial index must be requested in the query (SpatialIndex or the idx_ R*Tree table); then it gives the same answer as a full scan, much faster.
  • GeoPackage holds several feature layers (each with its own SRID), attribute tables and tiles in one standard file; its metadata tables and R-trees are ordinary SQLite tables.
  • pyogrio reads and writes GeoPackages quickly and can filter by columns, attributes, bounding box (R-tree) or SQL across layers.
  • SQLite allows one writer at a time and is unreliable on network drives. Move to PostGIS for many concurrent editors, large data, access control, web services or advanced functions.

Functions used: InitSpatialMetadata, AddGeometryColumn, MakePoint, GeomFromWKB, CastToMulti, CreateSpatialIndex, Transform, ST_Within (SpatiaLite SQL); pyogrio.write_dataframe, pyogrio.read_dataframe, pyogrio.read_info, pyogrio.list_layers; pdb.connect, con.load, con.srid, con.tables (geolattice.geolatticedb).

Exercises

  1. Add a chr_2020 table from the 2020 CHR release to ny_health.gpkg and compute, in one SQL query, the change in adult obesity between the 2020 and 2024 releases for each county.
  2. Rewrite the indexed SpatiaLite query using the idx_counties_geom R*Tree table directly (MbrMinX, MbrMaxX, …). Is it faster than SpatialIndex?
  3. Write all PM2.5 monitors in the US to a GeoPackage with and without SPATIAL_INDEX. Compare file sizes and the time of a bbox read around Syracuse.
  4. Open ny_health.gpkg in QGIS and check that the CHR table appears as a non-spatial table that can be joined to the counties.
Back to top