Github PyPI

TL;DR You can now install PostgreSQL like it’s a Python package:

PGVERSION=17.4 pip install pgvenv

I frequently work with Python and PostgreSQL across multiple projects. Each project might need a different Postgres version or a custom build with different options & extensions. I don’t like checking in build scripts, and I’ve never found git submodules satisfying.

I wanted something as smooth as a venv, b ut for Postgres — something that disappears when the project does, lives entirely inside the environment, and doesn’t require installing Postgres globally. That’s the motivation behind pgvenv.

pgvenv is a Python package that embeds a fully isolated PostgreSQL installation inside your virtual environment. When you install it, it builds PostgreSQL from source using –prefix=$VENVPATH, placing the psql, pg_config, postgres, and other binaries right next to pip and python under venv/bin.

The workflow looks a bit like this.

python3.11 -m venv ./venv

source ./venv/bin/activate

PGVERSION=17.4 pip install pgvenv --force-reinstall --no-cache-dir

initdb ./pgdata

postgres -D ./pgdata

You can customize the Postgres build using environment variables during pip install.

  • PGVERSION: specifies the Postgres version to build (e.g. 17.4, 15.7, etc).
  • You can pass the usual environmant variables that configure expects, like CC, CFLAGS etc.
  • PGCONFIGUREFLAGS: passed directly to the ./configure script for options not exposed via env vars (e.g. --without-icu, --with-openssl, etc).

When switching versions you should also pass the --force-reinstall --no-cache-dir flags.

PGVERSION=16.3 \
CFLAGS="-O2 -march=native" \
PGCONFIGUREFLAGS="--without-readline --without-icu" \
pip install pgvenv --force-reinstall --no-cache-dir