feat(postgres): pool that refuses servers before PG 18, goose migrations under an advisory lock, testcontainers harness

internal/infrastructure/postgres opens a pgx pool, checks server_version_num >= 180000, and applies goose migrations with a Postgres session advisory lock so processes starting together apply each migration once. internal/infrastructure/postgres/pgtest starts postgres:18 through testcontainers per test binary and gives each test its own database. Adds jackc/pgx/v5 v5.11.0, pressly/goose/v3 v3.28.0 and testcontainers-go v0.44.0. The database URL config, sqlc, the Compose service and the ownership lock move to archie-core-7r0x.2, where they have consumers.
This commit is contained in:
sam committed 2026-09-24 01:03:08 +10:00
1 parent 01586f1630
commit c620e00396
7 files changed
+374 -12

No files matched your search

@@ -0,0 +1,87 @@
// Package pgtest runs a throwaway PostgreSQL 18 container for one test binary
// and gives each test its own database on it.
//
// A package using it calls Main from TestMain:
//
// func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
//
// It needs a running Docker daemon.
package pgtest
import (
"context"
"fmt"
"net/url"
"os"
"sync/atomic"
"testing"
"github.com/jackc/pgx/v5"
"github.com/testcontainers/testcontainers-go"
tcpostgres "github.com/testcontainers/testcontainers-go/modules/postgres"
)
// image is the server tests run against: the same major version archie
// requires.
const image = "postgres:18"
var (
adminURL string
nextDB atomic.Int64
)
// Main starts the container, runs the tests and removes the container,
// returning the exit code. A container that cannot start is a test failure,
// not a skip.
func Main(m *testing.M) int {
ctx := context.Background()
container, err := tcpostgres.Run(ctx, image,
tcpostgres.WithDatabase("postgres"),
tcpostgres.WithUsername("archie"),
tcpostgres.WithPassword("archie"),
tcpostgres.BasicWaitStrategies(),
)
defer func() { _ = testcontainers.TerminateContainer(container) }()
if err != nil {
fmt.Fprintf(os.Stderr, "pgtest: start %s (is Docker running?): %v\n", image, err)
return 1
}
adminURL, err = container.ConnectionString(ctx, "sslmode=disable")
if err != nil {
fmt.Fprintf(os.Stderr, "pgtest: connection string: %v\n", err)
return 1
}
return m.Run()
}
// URL creates an empty database for t, drops it when t ends, and returns a
// connection URL for it.
func URL(t testing.TB) string {
t.Helper()
if adminURL == "" {
t.Fatal("pgtest: no container running; call pgtest.Main from TestMain")
}
name := fmt.Sprintf("t%d", nextDB.Add(1))
exec(t, "CREATE DATABASE "+name)
t.Cleanup(func() { exec(t, "DROP DATABASE "+name+" WITH (FORCE)") })
u, err := url.Parse(adminURL)
if err != nil {
t.Fatalf("pgtest: parse connection string: %v", err)
}
u.Path = "/" + name
return u.String()
}
func exec(t testing.TB, sql string) {
t.Helper()
ctx := context.Background()
conn, err := pgx.Connect(ctx, adminURL)
if err != nil {
t.Fatalf("pgtest: connect: %v", err)
}
defer func() { _ = conn.Close(ctx) }()
if _, err := conn.Exec(ctx, sql); err != nil {
t.Fatalf("pgtest: %s: %v", sql, err)
}
}
@@ -0,0 +1,65 @@
// Package postgres opens archie's PostgreSQL database and applies its schema
// migrations.
package postgres
import (
"context"
"errors"
"fmt"
"io/fs"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/jackc/pgx/v5/stdlib"
"github.com/pressly/goose/v3"
"github.com/pressly/goose/v3/lock"
)
// minServerVersion is PostgreSQL 18 in server_version_num form.
const minServerVersion = 180000
// ErrServerTooOld is returned for a server older than PostgreSQL 18.
var ErrServerTooOld = errors.New("postgres: server is older than PostgreSQL 18")
func checkServerVersion(num int) error {
if num < minServerVersion {
return fmt.Errorf("%w (server_version_num %d)", ErrServerTooOld, num)
}
return nil
}
// Open connects a pool to url and refuses a server older than PostgreSQL 18.
func Open(ctx context.Context, url string) (*pgxpool.Pool, error) {
pool, err := pgxpool.New(ctx, url)
if err != nil {
return nil, fmt.Errorf("postgres: open: %w", err)
}
var num int
if err := pool.QueryRow(ctx, "SELECT current_setting('server_version_num')::int").Scan(&num); err != nil {
pool.Close()
return nil, fmt.Errorf("postgres: read server version: %w", err)
}
if err := checkServerVersion(num); err != nil {
pool.Close()
return nil, err
}
return pool, nil
}
// Migrate applies the goose migrations in fsys. A session-level advisory lock
// makes processes that start together apply each migration once.
func Migrate(ctx context.Context, pool *pgxpool.Pool, fsys fs.FS) error {
locker, err := lock.NewPostgresSessionLocker()
if err != nil {
return fmt.Errorf("postgres: migration lock: %w", err)
}
db := stdlib.OpenDBFromPool(pool)
defer func() { _ = db.Close() }()
provider, err := goose.NewProvider(goose.DialectPostgres, db, fsys, goose.WithSessionLocker(locker))
if err != nil {
return fmt.Errorf("postgres: migrations: %w", err)
}
if _, err := provider.Up(ctx); err != nil {
return fmt.Errorf("postgres: migrate: %w", err)
}
return nil
}
@@ -0,0 +1,82 @@
package postgres
import (
"errors"
"os"
"sync"
"testing"
"testing/fstest"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
)
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
func TestCheckServerVersion(t *testing.T) {
tests := []struct {
num int
want error
}{
{num: 180000},
{num: 180006},
{num: 190000},
{num: 179999, want: ErrServerTooOld},
{num: 170011, want: ErrServerTooOld},
}
for _, tt := range tests {
if err := checkServerVersion(tt.num); !errors.Is(err, tt.want) {
t.Errorf("checkServerVersion(%d) = %v, want %v", tt.num, err, tt.want)
}
}
}
func TestOpenConnectsToPostgres18(t *testing.T) {
pool, err := Open(t.Context(), pgtest.URL(t))
if err != nil {
t.Fatalf("Open: %v", err)
}
defer pool.Close()
var one int
if err := pool.QueryRow(t.Context(), "SELECT 1").Scan(&one); err != nil || one != 1 {
t.Fatalf("SELECT 1 = %d, %v", one, err)
}
}
// Each migration inserts one row, so the row count is the number of times
// it was applied.
var countingMigrations = fstest.MapFS{
"00001_create.sql": {Data: []byte("-- +goose Up\nCREATE TABLE applied (n int);\nINSERT INTO applied VALUES (1);\n")},
"00002_again.sql": {Data: []byte("-- +goose Up\nINSERT INTO applied VALUES (2);\n")},
}
func TestMigrateAppliesEachMigrationOnce(t *testing.T) {
pool, err := Open(t.Context(), pgtest.URL(t))
if err != nil {
t.Fatal(err)
}
defer pool.Close()
// Two processes starting together, then a later restart.
var wg sync.WaitGroup
errs := make([]error, 2)
for i := range errs {
wg.Go(func() { errs[i] = Migrate(t.Context(), pool, countingMigrations) })
}
wg.Wait()
for i, err := range errs {
if err != nil {
t.Fatalf("concurrent Migrate %d: %v", i, err)
}
}
if err := Migrate(t.Context(), pool, countingMigrations); err != nil {
t.Fatalf("Migrate on restart: %v", err)
}
var rows int
if err := pool.QueryRow(t.Context(), "SELECT count(*) FROM applied").Scan(&rows); err != nil {
t.Fatal(err)
}
if rows != 2 {
t.Fatalf("applied rows = %d, want 2 (each migration exactly once)", rows)
}
}