Skip to main content

Chapter 2: Setting up PostgreSQL, PostGIS and Python

Chapter 2: Setting up PostgreSQL, PostGIS and Python

TipAt a glance
  • You will build: The database crop_insurance with PostGIS and PostGIS raster, its four schemas, and a tested connection from Python
  • You need: Rights to install software on your computer (tested on Windows 11); a conda installation such as Miniforge
  • Time to run: The installers, then a few seconds of code (the checkpoint prints how long the code took)
  • Level: Beginner

Every later chapter stores its data and runs its analysis in one PostgreSQL database with the PostGIS extension. This chapter installs the database server and PostGIS, gives Python a way to log in without a password in any notebook, creates the tutorial database crop_insurance with the spatial and raster extensions, and tests the result with four checks whose right answers are known in advance: a map projection, a datum shift, an area on the globe and a raster written to GeoTIFF and read back.

NoteLearning objectives

By the end of this chapter you will be able to:

  • install PostgreSQL and PostGIS on Windows, and know which installer choices this series relies on;
  • let Python connect to PostgreSQL through a password file instead of a password in code;
  • create a database, the postgis and postgis_raster extensions and the schemas of the series from Python;
  • store settings on a database with ALTER DATABASE ... SET, and explain why they apply to new sessions only;
  • check an installation with queries whose right answers you know in advance.

Before running this chapter, read Chapter 1 for the plan of the series. You need the right to install software on your computer. The notebook itself needs the Python environment of section 2 and a running PostgreSQL server.

1. Install PostgreSQL and PostGIS

PostgreSQL is the database server. PostGIS is an extension that adds geometry types (coordinates on a flat map), geography types (coordinates on the globe) and raster types, with the functions that work on them (ledger L129). On Windows both come as installers. This series was tested with PostgreSQL 18.7 and PostGIS 3.7.0 on Windows 11 (ledger L14).

Step 1: PostgreSQL. Download the Windows installer for PostgreSQL 18 from the PostgreSQL download page for Windows and run it:

  • keep the components Server, Command Line Tools and Stack Builder; pgAdmin, a graphical client, is optional and not used in this series;
  • give the postgres user a password and keep it for section 3;
  • keep port 5432 unless the installer proposes another one (it does when another PostgreSQL already uses 5432); whatever port you keep goes into config.yml;
  • keep the default locale and the default data directory; if you change the data directory, keep it out of folders a cloud client syncs, such as OneDrive.

Step 2: PostGIS. Install the PostGIS bundle for your PostgreSQL version, either from Stack Builder (category Spatial Extensions) or from the PostGIS downloads for Windows. Bundle 3.7.0 is offered for PostgreSQL 15 to 19 and includes raster support, vector tile support and the loaders raster2pgsql and shp2pgsql (ledger L16). conda, where the Python packages come from, has no Windows build of PostGIS, so it cannot replace this step (ledger L15). If the installer offers to create a sample spatial database, leave it off: section 4 creates the database.

The bundle then asks five questions, each about a system-wide setting (ledger L23). This series answered yes to all five:

Question What it sets Used here
PROJ_LIB where PROJ finds its coordinate system data yes: the server needs it to look up EPSG codes
GDAL_DATA where GDAL finds its data files the database also gets this path in section 5
key GDAL drivers which raster file formats PostGIS may use section 5 narrows it to GeoTIFF for this database
out-db rasters whether rasters may stay as files outside the database section 5 switches it off for this database
SSL bundle certificates for secure web requests not by the server; see Troubleshooting

Step 3: restart the PostgreSQL service. A service that is already running does not see variables set after it started. On the machine tested here, the server ran on without a restart: it reported the raster settings as off (ledger L24), and GDAL inside it could not resolve EPSG codes (ledger L134). Restart it from the Windows Services app (postgresql-x64-18 for version 18, ledger L14), or restart the computer. Test 4 in section 6 tells you whether this step took effect.

macOS and Linux. The PostGIS project’s Getting Started page has instructions for macOS, Ubuntu and Debian, Red Hat, SUSE and Docker (ledger L136). Set gdal_datapath in config.yml to null there. This series was tested on Windows only.

2. The Python environment

The file environment.yml at the root of the repository lists the Python packages the chapters use; its comments give the versions the chapters were run with. Those runs used an existing conda environment with these packages, not one freshly created from the file. On Windows, open the Miniforge Prompt (or another conda prompt), go to the repository folder and run:

conda env create -f environment.yml
conda activate crop-insurance
jupyter lab

In Jupyter, open en/02-setup.ipynb and check that the notebook runs on the Python of that environment (Kernel menu, Change Kernel).

The chapters read their settings from config.yml at the root of the repository: where the database is, what it is called, two raster settings and where downloaded data goes. Change it if your server or folders differ. It holds no password.

The first cell also sets one environment variable before anything imports numpy. In the environment this series was tested in, a numpy matrix product ended the Python process without a message unless MKL_THREADING_LAYER was set to SEQUENTIAL (ledger L128). The first cell of every chapter sets it.

import os
os.environ.setdefault("MKL_THREADING_LAYER", "SEQUENTIAL")   # before numpy is imported (ledger L128)

import sys
import time
from importlib.metadata import version
from pathlib import Path

import psycopg
import pyproj
import yaml
from psycopg import sql

T0 = time.perf_counter()

# The repository root, whether the notebook runs from en/, id/ or the root itself
ROOT = Path.cwd() if (Path.cwd() / "tutorial.yml").exists() else Path.cwd().parent
if not (ROOT / "config.yml").exists():
    raise FileNotFoundError("config.yml not found: start Jupyter in the repository folder and open en/02-setup.ipynb")
CONFIG = yaml.safe_load((ROOT / "config.yml").read_text(encoding="utf-8"))
DB = CONFIG["database"]

print("Python", sys.version.split()[0])
print("psycopg", psycopg.__version__, "| libpq", psycopg.pq.version())
print("pyproj", pyproj.__version__, "| PROJ", pyproj.proj_version_str, "| PROJ data:", Path(pyproj.datadir.get_data_dir()).name,
      "inside the environment" if Path(sys.prefix) in Path(pyproj.datadir.get_data_dir()).parents else "OUTSIDE the environment")
print("later chapters:", {p: version(p) for p in ["geopandas", "rasterio", "sqlalchemy", "geoalchemy2", "requests", "beautifulsoup4"]})
print("database settings:", DB)
Python 3.14.10
psycopg 3.3.9 | libpq 180007
pyproj 3.7.2 | PROJ 9.7.1 | PROJ data: proj inside the environment
later chapters: {'geopandas': '1.2.0', 'rasterio': '1.5.0', 'sqlalchemy': '2.1.8', 'geoalchemy2': '0.20.0', 'requests': '2.34.2', 'beautifulsoup4': '4.15.0'}
database settings: {'host': 'localhost', 'port': 5432, 'user': 'postgres', 'dbname': 'crop_insurance'}

Look before moving on. psycopg talks to the server through libpq, PostgreSQL’s client library; its version is printed as one number, 180007 for 18.7. pyproj’s PROJ data should be inside the environment: if it says outside, Python reads another program’s coordinate data (Troubleshooting). The packages of later chapters should all have versions; a PackageNotFoundError means the notebook runs on another Python than the environment of this section. The database settings should match your installation.

3. A password file instead of a password

PostgreSQL’s client library looks for passwords in a file, one line per connection in the form hostname:port:database:username:password. Each of the first four fields can be *, which matches anything, and the first matching line wins. A colon or backslash inside a field, for example in the password, is written with a backslash before it (ledger L126). With the file in place no notebook in this series contains a password.

On Windows the file is %APPDATA%\postgresql\pgpass.conf (ledger L126). To create it:

  1. Press Windows+R, type %APPDATA% and press Enter. Explorer opens your Roaming folder.
  2. If there is no folder postgresql, create it.
  3. In Notepad, write one line, localhost:5432:*:postgres:YOUR_PASSWORD, with your port and the password from section 1.
  4. Save it in that folder with “Save as type: All files” and the name pgpass.conf. Otherwise Notepad saves pgpass.conf.txt, and Explorer hides the .txt.

On macOS and Linux the file is ~/.pgpass, and PostgreSQL ignores it unless only you can read it (chmod 0600 ~/.pgpass). The variable PGPASSFILE can point to a file elsewhere (ledger L126).

The next cell looks for the file and lists the names in its folder. It does not read the file.

if os.environ.get("PGPASSFILE"):
    pgpass, shown = Path(os.environ["PGPASSFILE"]), "$PGPASSFILE"
elif os.name == "nt":
    pgpass, shown = Path(os.environ["APPDATA"], "postgresql", "pgpass.conf"), r"%APPDATA%\postgresql\pgpass.conf"
else:
    pgpass, shown = Path.home() / ".pgpass", "~/.pgpass"

print(shown, "exists" if pgpass.is_file() else "is MISSING")
if pgpass.parent.is_dir():
    print("files in its folder:", sorted(p.name for p in pgpass.parent.iterdir()))
else:
    print("its folder does not exist yet")
%APPDATA%\postgresql\pgpass.conf exists
files in its folder: ['pgpass.conf']

Look before moving on. The file should exist. If the folder lists pgpass.conf.txt instead, rename it. The next cell connects to postgres, the default database for connecting that every new server has; the server also creates two templates, template0 and template1, which new databases are copied from (ledger L133).

SERVER = dict(host=DB["host"], port=DB["port"], user=DB["user"])

with psycopg.connect(dbname="postgres", **SERVER) as conn:
    print(conn.execute("SELECT version()").fetchone()[0])
    print("data directory:", conn.execute("SHOW data_directory").fetchone()[0])
    for name, version_ in conn.execute(
            "SELECT name, default_version FROM pg_available_extensions WHERE name LIKE 'postgis%' ORDER BY name"):
        print(f"available extension: {name} {version_}")
PostgreSQL 18.7 on x86_64-windows, compiled by msvc-19.44.35230, 64-bit
data directory: E:/pgdata/pg18
available extension: postgis 3.7.0
available extension: postgis_raster 3.7.0
available extension: postgis_sfcgal 3.7.0
available extension: postgis_tiger_geocoder 2025.2
available extension: postgis_topology 3.7.0

Look before moving on. The first line names the PostgreSQL version and platform. “Available” means the extension’s files are installed on the server; it is not yet switched on in any database (section 5 does that). The list must include postgis and postgis_raster; the others come with the bundle and are not used here. If the list is empty, the PostGIS bundle is not installed for this server. If the cell fails with fe_sendauth: no password supplied, the password file is missing or its line does not match the host, port or user in config.yml; password authentication failed means the file was found but the password is wrong or a : or \ in it is not escaped.

4. Create the database

CREATE DATABASE has no IF NOT EXISTS option and cannot run inside a transaction block (ledger L127). A transaction block is a group of statements that succeed or fail together. psycopg starts one with the first statement on a connection and keeps it open until commit or rollback, unless the connection is in autocommit mode (ledger L130). The cell therefore connects with autocommit=True, looks the name up in pg_database, the system table that lists the databases, and creates the database only if it is missing.

TEMPLATE template0 copies the empty template, which accepts any encoding; copying template1 would fail where its encoding is not UTF8 (ledger L133). sql.Identifier quotes the name as SQL requires, which is safer than pasting it into the statement as text (ledger L130).

with psycopg.connect(dbname="postgres", autocommit=True, **SERVER) as conn:
    exists = conn.execute("SELECT 1 FROM pg_database WHERE datname = %s", [DB["dbname"]]).fetchone()
    if exists:
        print(f"database {DB['dbname']} already exists: nothing to do")
    else:
        conn.execute(sql.SQL("CREATE DATABASE {} TEMPLATE template0 ENCODING 'UTF8'").format(sql.Identifier(DB["dbname"])))
        print(f"created database {DB['dbname']}")
database crop_insurance already exists: nothing to do

On a first run the cell prints “created database crop_insurance”. Run it again and it reports that the database exists: every setup cell in this chapter is safe to repeat. The output saved with this notebook comes from a machine where the database already existed.

5. Extensions, raster settings and schemas

Extensions. The bundle put PostGIS on the server; CREATE EXTENSION switches it on in one database. Since PostGIS 3.0, raster support is a separate extension, postgis_raster (ledger L129).

with psycopg.connect(dbname=DB["dbname"], autocommit=True, **SERVER) as conn:
    for ext in ("postgis", "postgis_raster"):
        conn.execute(sql.SQL("CREATE EXTENSION IF NOT EXISTS {}").format(sql.Identifier(ext)))
    print(conn.execute("SELECT postgis_full_version()").fetchone()[0])
POSTGIS="3.7.0 3.7.0" [EXTENSION] PGSQL="180" GEOS="3.15.1-CAPI-1.21.2" PROJ="9.8.1 NETWORK_ENABLED=OFF URL_ENDPOINT=https://cdn.proj.org USER_WRITABLE_DIRECTORY=C:\WINDOWS\ServiceProfiles\NetworkService\AppData\Local/proj DATABASE_PATH=C:\Program Files\PostgreSQL\18\share\contrib\postgis-3.7\proj\proj.db" (compiled against PROJ 9.8.1) GDAL="GDAL 3.13.1 "Iowa City", released 2026/06/01" LIBXML="2.12.5" LIBJSON="0.16" LIBPROTOBUF="1.2.1" WAGYU="0.5.0 (Internal)" RASTER

Look before moving on. The line lists PostGIS and the libraries it runs with (GEOS, PROJ, GDAL) and should end with RASTER. If it contains “GDAL_DATA not found”, test 4 below tells you whether that matters; on the machine tested here it went with the EPSG fault of section 1, step 3 (ledger L134).

Raster settings. ALTER DATABASE ... SET stores a setting on the database. It becomes the default of every session started later in that database, not of the current one (ledger L127), and these PostGIS settings can only be changed by a superuser such as postgres (ledger L131). Three are stored:

  • postgis.gdal_enabled_drivers: the file formats raster functions may read and write. A standard installation enables none (ledger L131); the series needs GeoTIFF only, from config.yml.
  • postgis.enable_outdb_rasters: whether rasters may stay as files outside the database. With it on, a plain SELECT can make the server read files from its own disk, which was measured on the machine tested here (ledger L135). No table of the series needs it, so the cell switches it off, also against the system- wide default the installer set.
  • postgis.gdal_datapath: where GDAL’s data files are, from config.yml (Windows only; skipped when null).

ALTER DATABASE ... SET cannot take the value as a %s parameter, so the value goes through sql.Literal (ledger L130). The setting’s name has two parts, postgis and gdal_enabled_drivers, and sql.Identifier quotes each.

RASTER_SETTINGS = {
    "postgis.gdal_enabled_drivers": CONFIG["postgis"]["gdal_enabled_drivers"],
    "postgis.enable_outdb_rasters": "off",
}
if CONFIG["postgis"].get("gdal_datapath"):
    RASTER_SETTINGS["postgis.gdal_datapath"] = CONFIG["postgis"]["gdal_datapath"]

with psycopg.connect(dbname=DB["dbname"], autocommit=True, **SERVER) as conn:
    for name, value in RASTER_SETTINGS.items():
        conn.execute(sql.SQL("ALTER DATABASE {} SET {} = {}").format(
            sql.Identifier(DB["dbname"]), sql.Identifier(*name.split(".")), sql.Literal(value)))
    print("in this session: postgis.gdal_enabled_drivers =",
          conn.execute("SELECT current_setting('postgis.gdal_enabled_drivers')").fetchone()[0])
in this session: postgis.gdal_enabled_drivers = GTiff

Look before moving on. Nothing to check yet: the value printed is the one this session started with, not the one just stored. On a database created a moment ago it is the server’s default, which was DISABLE_ALL on the machine tested here (ledger L24). The stored values are read in a new session below.

Schemas. A schema is a named group of tables inside a database (ledger L127). The series uses four (Chapter 1, section 5).

SCHEMAS = ["ref", "raw", "idx", "out"]

with psycopg.connect(dbname=DB["dbname"], autocommit=True, **SERVER) as conn:
    for schema in SCHEMAS:
        conn.execute(sql.SQL("CREATE SCHEMA IF NOT EXISTS {}").format(sql.Identifier(schema)))
    print("schemas:", [r[0] for r in conn.execute(
        "SELECT nspname FROM pg_namespace WHERE nspname = ANY(%s) ORDER BY nspname", [SCHEMAS])])
schemas: ['idx', 'out', 'raw', 'ref']

A connection for the rest of the series. Later chapters open their sessions with the function below. Used as with connect() as conn:, a session commits its work when the block ends and rolls it back if the block raises an error (ledger L130), so a failed cell leaves no half-written table behind.

def connect(**kwargs):
    """A new session in the tutorial database, with the settings of config.yml."""
    return psycopg.connect(dbname=DB["dbname"], **SERVER, **kwargs)

with connect() as conn:
    for name in RASTER_SETTINGS:
        print(f"new session: {name} = {conn.execute('SELECT current_setting(%s)', [name]).fetchone()[0]}")
new session: postgis.gdal_enabled_drivers = GTiff
new session: postgis.enable_outdb_rasters = off
new session: postgis.gdal_datapath = C:/Program Files/PostgreSQL/18/gdal-data

Look before moving on. The new session shows the stored values: GTiff, off and, on Windows, the GDAL data path of config.yml.

6. Test with answers you know

An installation check is only useful if you know the right answer before running it. The next cell runs four tests inside the database and computes the same answers with pyproj in Python, which uses its own copy of PROJ (9.7.1 in the environment tested, against 9.8.1 in the server; ledger L134).

  1. A map projection. The point 110 E, 7 S, in Kab. Batang, Jawa Tengah (ledger L134), projected from longitude and latitude (EPSG:4326) to UTM zone 49 South (EPSG:32749). Both sides use the same datum, so this tests that PROJ runs inside the server.
  2. A datum shift. The same point converted to the Batavia datum (EPSG:4211), once used for maps of Java. The point moves by about 120 m (ledger L134); the server must read the datum parameters from its PROJ data.
  3. An area on the globe. A cell of 0.01 by 0.01 degree, as geography, measured on the spheroid in square metres (ledger L132). pyproj’s Geod measures the same cell. The cell is about 122 ha, because 0.01 degree is about 1.1 km this close to the equator.
  4. A raster round trip. A 10 by 10 raster filled with 5.5 in EPSG:4326 is written to GeoTIFF bytes and read back. The bytes carry the EPSG code (ledger L134), so the raster should come back with SRID 4326, the same 100 cells and the same grid. SRID 0 means GDAL inside the server cannot resolve EPSG codes.
ROUND_TRIP = """
    WITH r AS (SELECT ST_AsRaster(ST_MakeEnvelope(110, -7.1, 110.1, -7, 4326),  -- the area to cover
                                  0.01, -0.01,                               -- cell size in degrees (y counts down)
                                  '32BF', 5.5, -9999) AS rast),              -- 32-bit float, value, nodata
         g AS (SELECT rast, ST_AsGDALRaster(rast, 'GTiff') AS tif FROM r)
    SELECT length(tif), ST_SRID(ST_FromGDALRaster(tif)), ST_Count(ST_FromGDALRaster(tif)),
           (ST_SummaryStats(ST_FromGDALRaster(tif))).mean, ST_SameAlignment(rast, ST_FromGDALRaster(tif, 4326))
    FROM g"""

def run_tests():
    """The four tests: the server's answers and pyproj's, side by side."""
    with connect() as conn:
        utm_db = conn.execute("SELECT ST_X(g), ST_Y(g) FROM ST_Transform(ST_SetSRID(ST_MakePoint(110, -7), 4326), 32749) g").fetchone()
        bat_db = conn.execute("SELECT ST_X(g), ST_Y(g) FROM ST_Transform(ST_SetSRID(ST_MakePoint(110, -7), 4326), 4211) g").fetchone()
        area_db = conn.execute("SELECT ST_Area(ST_MakeEnvelope(110, -7.01, 110.01, -7, 4326)::geography)").fetchone()[0]
        drivers = [r[0] for r in conn.execute("SELECT short_name FROM ST_GDALDrivers() ORDER BY short_name")]
        raster = conn.execute(ROUND_TRIP).fetchone() if drivers else None
    utm_py = pyproj.Transformer.from_crs(4326, 32749, always_xy=True).transform(110, -7)
    bat_py = pyproj.Transformer.from_crs(4326, 4211, always_xy=True).transform(110, -7)
    area_py = abs(pyproj.Geod(ellps="WGS84").polygon_area_perimeter([110, 110.01, 110.01, 110], [-7.01, -7.01, -7, -7])[0])
    return dict(utm_db=utm_db, utm_py=utm_py, bat_db=bat_db, bat_py=bat_py, area_db=area_db, area_py=area_py,
                drivers=drivers, raster=raster)

t = run_tests()
print(f"1. projection  PostGIS {t['utm_db'][0]:.2f} {t['utm_db'][1]:.2f} | pyproj {t['utm_py'][0]:.2f} {t['utm_py'][1]:.2f}"
      f"  ({pyproj.CRS.from_epsg(32749).name})")
print(f"2. datum       PostGIS {t['bat_db'][0]:.8f} {t['bat_db'][1]:.8f} | pyproj {t['bat_py'][0]:.8f} {t['bat_py'][1]:.8f}"
      f"  ({pyproj.CRS.from_epsg(4211).name})")
print(f"3. area        PostGIS {t['area_db']:,.2f} m2 | pyproj {t['area_py']:,.2f} m2 | difference {abs(t['area_db'] - t['area_py']):.4f} m2")
print(f"4. raster      drivers {t['drivers']}; GeoTIFF {t['raster'][0]} bytes, read back: SRID {t['raster'][1]}, "
      f"{t['raster'][2]} cells, mean {t['raster'][3]}, same grid {t['raster'][4]}" if t["raster"] else "4. raster      no GDAL drivers")
1. projection  PostGIS 389543.49 9226133.65 | pyproj 389543.49 9226133.65  (WGS 84 / UTM zone 49S)
2. datum       PostGIS 109.99890164 -7.00025357 | pyproj 109.99890164 -7.00025357  (Batavia)
3. area        PostGIS 1,221,962.44 m2 | pyproj 1,221,962.44 m2 | difference 0.0000 m2
4. raster      drivers ['GTiff']; GeoTIFF 784 bytes, read back: SRID 4326, 100 cells, mean 5.5, same grid True

Look before moving on. Tests 1 and 2 should agree to the printed digits. In test 2 the longitude moves by about 0.0011 degree, the datum shift; a result equal to the input would mean the server applied no shift. Test 3 should differ by far less than a square metre (a sphere instead of the spheroid would give about 2,700 m2 less, ledger L132). Test 4 should list only GTiff, and read back SRID 4326, 100 cells, mean 5.5 and the same grid. SRID 0 means the server still runs without its PROJ data: restart the service (section 1, step 3). An empty driver list means the raster settings did not reach this session: open a new connection.

Checkpoint

The cell below runs the tests again in a new session, together with the settings and objects the next chapters need, and stops with an error if anything is not as expected. It depends only on the setup cell and the functions defined above.

t = run_tests()
with connect() as conn:
    ext = dict(conn.execute("SELECT extname, extversion FROM pg_extension").fetchall())
    schemas = {r[0] for r in conn.execute("SELECT nspname FROM pg_namespace")}
    setting = lambda name: conn.execute("SELECT current_setting(%s)", [name]).fetchone()[0]
    drivers_setting, outdb = setting("postgis.gdal_enabled_drivers"), setting("postgis.enable_outdb_rasters")

assert {"postgis", "postgis_raster"} <= set(ext), f"missing extensions: {ext}"
assert set(SCHEMAS) <= schemas, f"missing schemas: {set(SCHEMAS) - schemas}"
assert drivers_setting == CONFIG["postgis"]["gdal_enabled_drivers"], f"drivers setting is {drivers_setting!r}"
assert outdb == "off", "postgis.enable_outdb_rasters is not off in new sessions"
assert all(abs(a - b) < 0.01 for a, b in zip(t["utm_db"], t["utm_py"])), "PostGIS and pyproj project differently"
assert all(abs(a - b) < 1e-7 for a, b in zip(t["bat_db"], t["bat_py"])), "PostGIS and pyproj shift the datum differently"
assert abs(t["bat_db"][0] - 110) > 0.001, "no datum shift: the server lacks PROJ's datum data"
assert abs(t["area_db"] - t["area_py"]) < 1.0, "geography area differs from pyproj by a square metre or more"
assert t["raster"], "PostGIS raster has no GDAL driver: check the raster settings (section 5)"
nbytes, srid, cells, mean, same_grid = t["raster"]
assert cells == 100 and mean == 5.5 and same_grid, "the raster changed in the GeoTIFF round trip"
assert srid == 4326, "the raster came back with SRID 0: restart the PostgreSQL service (section 1, step 3)"
print(f"checkpoint passed: PostGIS {ext['postgis']}, PostGIS raster {ext['postgis_raster']}, schemas {sorted(SCHEMAS)}; "
      f"code cells took {time.perf_counter() - T0:.1f} s since the setup cell")
checkpoint passed: PostGIS 3.7.0, PostGIS raster 3.7.0, schemas ['idx', 'out', 'raw', 'ref']; code cells took 1.9 s since the setup cell

Troubleshooting

Symptom Cause Fix
FileNotFoundError: config.yml not found Jupyter was started outside the repository start jupyter lab in the repository folder (section 2)
ModuleNotFoundError or PackageNotFoundError the notebook runs on another Python choose the kernel of the crop-insurance environment (section 2)
fe_sendauth: no password supplied no password file, or its line does not match host, port or user create the file of section 3; check the fields against config.yml
password authentication failed for user "postgres" the file was found, the password is wrong correct the password; escape : and \ with a backslash (section 3)
connection refused the service is not running, or listens on another port start postgresql-x64-18 in Services (ledger L14); check port in config.yml
postgis missing from the available extensions, or could not open extension control file the PostGIS bundle is not installed for this PostgreSQL version run the bundle installer for your version (ledger L16)
conda install postgis fails on Windows conda-forge has no Windows build (ledger L15) use the PostGIS bundle (section 1)
permission denied to set parameter the user is not a superuser (ledger L131) run section 5 as postgres
empty driver list, DISABLE_ALL in a new session the settings of section 5 were not stored re-run section 5, then open a new connection
test 4 reads back SRID 0 the server started before the PostGIS installer set PROJ_LIB (ledger L134) restart the PostgreSQL service (section 1, step 3)
pyproj’s PROJ data outside the environment, or a pyproj error about proj.db Python reads the PostGIS installer’s PROJ data through PROJ_LIB (ledger L23) start Jupyter from the activated environment (section 2)
HTTPS errors about certificates in later chapters Python picks up the installer’s certificate bundle through CURL_CA_BUNDLE (ledger L23) start Jupyter from the activated environment
the kernel dies without a message during a numpy step the numpy threading issue of section 2 (ledger L128) keep the first cell’s MKL_THREADING_LAYER=SEQUENTIAL

Summary

You now have:

  • PostgreSQL with the PostGIS bundle, and a password file so that no notebook holds a password;
  • the database crop_insurance with the extensions postgis and postgis_raster;
  • three raster settings stored on the database: GeoTIFF as the only file format, out-of-database rasters off, and on Windows the GDAL data path;
  • four empty schemas, ref, raw, idx and out;
  • config.yml and the function connect(), which every later chapter uses to reach the database.

What comes next

Chapter 3 loads the administrative boundaries of Java into ref and collects the Ministry of Agriculture’s damage reports into raw.

References

  • PostgreSQL 18 documentation: the password file, CREATE DATABASE, ALTER DATABASE, schemas, template databases (ledger L126, ledger L127, ledger L133)
  • PostGIS documentation: installing on Windows, Getting Started, raster settings, ST_Area (ledger L16, ledger L136, ledger L131, ledger L132)
  • psycopg 3 documentation: transactions and SQL composition (ledger L130)