pg_regress: the PostgreSQL testing tool you already have installed
You don't need to write your own SQL test runner in bash or PHP. Since 2006, PostgreSQL has shipped pg_regress, a test tool written in C. Here's how it works, where it comes from, and how to use it in your own project.
I’ve run into the same thing several times in practice: a team needs to run SQL tests against PostgreSQL, so they write their own runner. The first time it was a very simple bash script. The second time it was written in PHP, then rewritten in bash, complete with parallel test execution and custom options for selecting groups, databases and files. Today that second runner is gradually being replaced by the real pg_regress. And all of it only because nobody knew that pg_regress exists.
It’s not some obscure utility, either. It’s the tool used to test PostgreSQL itself, and it’s sitting on your disk next to the server. You still have to write the tests. But you save yourself the work of developing and maintaining the tool that runs them.
A bit of history
PostgreSQL’s regression tests are as old as the project itself. They were originally run by a shell script, pg_regress.sh, which called psql and compared the output with diff. It worked well on Unix, but on Windows it was unusable without MSYS.
So in July 2006, Magnus Hagander and Tom Lane rewrote pg_regress in C (during the 8.2 development cycle). The behavior stayed the same; it just stopped depending on a shell. Since then it has been a single standalone binary used by the whole ecosystem: PostgreSQL core, contrib modules and most extensions that have tests.
How it works
The principle is trivially simple. You have two directories:
sql/ ← tests: plain .sql files
expected/ ← expected output: .out files
pg_regress runs every file from sql/ through psql, saves the output to results/ and compares it with expected/. A test passes if the outputs match. If they differ, you get a regression.diffs file with an ordinary unified diff.
So a test is just SQL. No asserts, no framework:
-- sql/orders.sql
CREATE TEMP TABLE t(id int);
INSERT INTO t VALUES (1), (2);
SELECT count(*) FROM t;
The expected output is exactly what psql would print. You don’t have to write it by hand: run the test once, check the result in results/ by eye and copy it to expected/.
The simplest usage
The quickest route is a temporary instance. pg_regress starts a fresh PostgreSQL in an empty directory on its own, runs the tests and throws it away again:
mkdir expected && touch expected/orders.out # the file must exist on the first run
pg_regress --bindir=/usr/lib/postgresql/17/bin \
--temp-instance=/tmp/pgtest \
--no-locale \
orders
The output looks like this:
# initializing database system by running initdb
# using temp instance on port 65312 with PID 31968
ok 1 - orders 23 ms
1..1
# All 1 tests passed.
If the result isn’t what you expected, you’ll see not ok and the exact difference in regression.diffs:
diff -U3 expected/orders.out results/orders.out
--- expected/orders.out
+++ results/orders.out
@@ -3,6 +3,6 @@
SELECT count(*) FROM t;
count
-------
- 3
+ 2
(1 row)
The exit code is 0 on success, 1 when a test fails and 2 when the tests couldn’t be run at all. So it plugs into CI with no extra glue.
Heads up: If a test has no file in
expected/, the run ends with aBail out!message and exit code 2 (verified on PostgreSQL 16 and 18). Just create an empty file (touch); the test then “fails” once, and you approve the result by copying it over fromresults/.
Against an existing database
If you don’t want to start a new instance (say, because you’re testing against a prepared database with extensions), use --use-existing:
createdb mytest
pg_regress --use-existing --dbname=mytest --host=localhost --user=tester orders
In this mode the database is neither created nor dropped; that’s up to you.
Parallel runs: the schedule
This is where people most often reinvent the wheel. Parallelism is built into pg_regress. All you need is a schedule file:
test: setup
test: orders customers invoices
test: cleanup
Tests on the same line run concurrently, while the lines are executed one after another. You can limit the number of concurrent connections with --max-concurrent-tests.
pg_regress --temp-instance=/tmp/pgtest --schedule=schedule
When you develop an extension
With an extension you don’t have to take care of anything yourself. PGXS has everything ready; in the Makefile all you need is:
REGRESS = setup orders customers
PGXS := $(shell pg_config --pgxs)
include $(PGXS)
Then make install && make installcheck installs the extension and runs the tests against a running instance. PGXS doesn’t support a temporary instance (make check) outside the PostgreSQL source tree; you arrange that either through REGRESS_OPTS = --temp-instance=... or by running pg_regress directly, as shown above.
Concurrency and locks: pg_isolation_regress
Plain pg_regress runs each test in a single session, so it doesn’t test what tends to be the most treacherous part of databases: concurrent transactions. For that there’s a sibling, pg_isolation_regress. It has the same interface and the same expected/, but instead of .sql files it reads .spec files, in which you describe several sessions and the order of their steps.
# specs/lost-update.spec
setup { CREATE TABLE acc (id int PRIMARY KEY, bal int); INSERT INTO acc VALUES (1, 100); }
teardown { DROP TABLE acc; }
session s1
setup { BEGIN ISOLATION LEVEL READ COMMITTED; }
step r1 { SELECT bal FROM acc WHERE id = 1; }
step w1 { UPDATE acc SET bal = bal - 10 WHERE id = 1; }
step c1 { COMMIT; }
session s2
setup { BEGIN ISOLATION LEVEL READ COMMITTED; }
step w2 { UPDATE acc SET bal = bal - 20 WHERE id = 1; }
step c2 { COMMIT; }
step r2 { SELECT bal FROM acc WHERE id = 1; }
permutation r1 w1 w2 c1 c2 r2
The output shows exactly what happened, including the fact that the second session waited for a lock:
Parsed test spec with 2 sessions
starting permutation: r1 w1 w2 c1 c2 r2
step r1: SELECT bal FROM acc WHERE id = 1;
bal
---
100
(1 row)
step w1: UPDATE acc SET bal = bal - 10 WHERE id = 1;
step w2: UPDATE acc SET bal = bal - 20 WHERE id = 1; <waiting ...>
step c1: COMMIT;
step w2: <... completed>
step c2: COMMIT;
step r2: SELECT bal FROM acc WHERE id = 1;
bal
---
70
(1 row)
If you omit permutation, the tool tries every possible interleaving of the steps. Concurrency bugs that a hand-written script would only catch by luck can be found systematically. In an extension you enable it with the ISOLATION = lost-update variable in the Makefile.
Where to find it
The weak spot is distribution. Neither pg_regress nor pg_isolation_regress is in the usual client package; they’re part of the development files (the second one sits next to the first, in src/test/isolation/):
- Debian/Ubuntu: package
postgresql-server-dev-17, path/usr/lib/postgresql/17/lib/pgxs/src/test/regress/pg_regress - Homebrew: formula
postgresql@NN, notlibpq - Postgres.app:
…/lib/postgresql/pgxs/src/test/regress/pg_regress
In general: $(pg_config --pkglibdir)/pgxs/src/test/regress/pg_regress.
Why use it instead of your own script
- You develop and maintain nothing. The runner belongs to PostgreSQL and evolves with it. You only write the tests.
- Parallelism, diffs, exit codes and a temporary instance are done and battle-tested on thousands of PostgreSQL’s own tests.
- Overhead. Total test time is of course mostly down to the database. But if you run hundreds of small tests, the startup of a scripting language and the extra process spawning start to show. A native C program doesn’t have that overhead.
- AI agents know it. pg_regress is well documented and sits in the training data, from the PostgreSQL sources to thousands of extensions. An agent doesn’t have to study a proprietary implementation someone wrote three years ago, and it knows what
expected/andscheduleshould look like.
When not to
pg_regress compares text, and everything runs within a single session (concurrency is handled by the pg_isolation_regress mentioned above). It isn’t a good fit when you need nondeterministic output (timings, OIDs, random data); you have to work around that in the results (ORDER BY, don’t print timings and OIDs, \o /dev/null for nondeterministic queries). And if you want individual asserts like is() / ok() and detailed per-test reports, reach for pgTAP. The two tools complement each other well.
| Custom script | pg_regress | pgTAP | |
|---|---|---|---|
| Runner development and maintenance | yours | none | none |
| Parallel runs | you have to write it | schedule | via pg_prove |
| Principle | anything | output diff | asserts in SQL |
| Dependencies | shell/PHP / … | in PostgreSQL | extension + Perl |
| Temporary instance | you have to write it | --temp-instance | no |
Migrating from a custom runner
If you already have your own runner, moving to pg_regress could be cheap, but it depends on how yours behaves. If it already works with pairs of a .sql file and expected/*.out and runs psql, the switch will be easier. Keep in mind that pg_regress runs psql with the -a (echo input) and -q switches and sets its own PGTZ, PGDATESTYLE and other variables. If your old runner called plain psql, the outputs will differ. A different runner may have a different output format or test structure, and then you won’t get around editing the expected files.
The --launcher option helps here, as it lets you insert your own wrapper between pg_regress and psql. In one project with thousands of tests it worked out: about twenty lines of bash that strip those switches and variables were enough, and the existing expected files stayed unchanged. Nothing had to be regenerated. And the parallel execution that had previously been hand-coded in bash now works there thanks to schedule. That’s one experience, though, not a guarantee. Before you start, try pg_regress on a small part of your tests first and see how many output differences come up.
Summary
Before you start writing your own SQL test runner, open pg_regress --help. You already have it installed, it’s written in C, it handles parallelism, a temporary instance and CI exit codes, and it has worked the same way since 2006. You still have to write the tests. But you no longer have to write the runner.