Files
archie/internal/infrastructure/postgres/postgres_test.go
T
sam 4dc04deb7a 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.
2026-09-24 01:03:08 +10:00

83 lines
2.1 KiB
Go

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)
}
}