Skip to content

Python basics

The pgmem package ships a platform wheel with the pgmem binary inside. It has no runtime dependencies; bring the PostgreSQL driver you already use.

Terminal window
pip install pgmem "psycopg[binary]"

Python 3.9 or newer. Wheels exist for Linux and macOS on x86-64 and arm64, and for Windows on x86-64. On other platforms, build the binary with go build ./cmd/pgmem and point PGMEM_BINARY at it.

  1. Start the process. pgmem.start() spawns the binary and waits until its template server accepts connections.

    import pgmem
    with pgmem.start(database="app") as pg:
    print(pg.template.dsn) # postgres://postgres@127.0.0.1:54321/app?sslmode=disable

    It also takes user, params (a list of postgres -c settings such as ["log_statement=all"]), log=True to pass the server log to stderr, and binary to override the lookup.

  2. Register the schema by running migrations against pg.template.dsn. See migration tools.

  3. Load seed data. See seed data.

  4. Use it with the official drivers.

    import psycopg
    with psycopg.connect(pg.template.dsn) as conn:
    row = conn.execute("SELECT name FROM users WHERE id = %s", (1,)).fetchone()
from pathlib import Path
with psycopg.connect(pg.template.dsn) as conn:
conn.execute(Path("schema.sql").read_text())

psycopg accepts several statements in one string when there are no parameters.

with psycopg.connect(pg.template.dsn) as conn:
conn.execute(Path("seed.sql").read_text())
with pgmem.start(database="app") as pg:
migrate(pg.template.dsn)
snap = pg.template.snapshot() # waits for open transactions, 30 s by default
with snap.fork() as fork: # a private copy of the prepared database
with psycopg.connect(fork.dsn) as conn:
conn.execute("DELETE FROM orders")
with snap.fork() as fork: # still has every order
...

Close or commit every connection to the template before snapshot(). The pytest plugin on the next page does all of this for you.