svg

The Easiest Way to Use Multiple Versions of the PostgreSQL CLI Client

postgresql cli linux nix-shell

When working on multiple projects, I often need to switch between different versions of the PostgreSQL CLI client to interact with various databases. Installing multiple versions of PostgreSQL CLI client on a single machine can be challenging, but there’s a simple solution: using nix-shell.

TL;DR

nix-shell -p postgresql_17
nix-shell -p postgresql_15
nix-shell -p postgresql_16

I already use Nix and Home Manager to manage and install various CLI tools on my machine. With nix-shell, I can effortlessly create isolated environments ensuring I use the correct PostgreSQL CLI version.

For example, I frequently back up and restore development databases using the pg_dump and pg_restore command. Occasionally, I also need to dump and restore databases across different PostgreSQL versions.

Here’s how I use nix-shell to manage multiple PostgreSQL CLI versions:

~/Backups
> tree
.
├── default.nix
├── pg_15.nix
└── pg_16.nix

1 directory, 3 files

The pg_15.nix file specifies PostgreSQL 15:

{ pkgs ? import <nixpkgs> {} }:

pkgs.mkShell {
  buildInputs = [
    pkgs.postgresql_15
  ];
}

To use the PostgreSQL 15 client, I activate a nix-shell environment with:

nix-shell pg_15.nix

Then, I can verify the version:

~/Backups via ❄️  impure (nix-shell)
> pg_dump -V
pg_dump (PostgreSQL) 15.9

The default.nix file defines the default PostgreSQL CLI version I use:

{ pkgs ? import <nixpkgs> {} }:

pkgs.mkShell {
  buildInputs = [
    pkgs.postgresql_17
  ];
}

Running nix-shell without arguments loads the default version:

nix-shell
~/Backups via ❄️  impure (nix-shell)
> pg_dump -V
pg_dump (PostgreSQL) 17.1

Or you can quickly launch nix-shell from any directory without any configuration file

nix-shell -p postgresql_17

By using nix-shell, I can seamlessly switch between PostgreSQL versions without cluttering my system with multiple installations.