Files
lincodex/backend/integration_test/postgres_migrations_test.go
T

211 lines
6.9 KiB
Go

//go:build integration
package integration_test
import (
"context"
"errors"
"sync"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
)
const (
migrationTestTimeout = 3 * time.Minute
concurrentMigrators = 4
)
const (
// identityMigrationVersion creates identityTableNames.
identityMigrationVersion = 2
// policyMigrationVersion creates policyTableNames and policyFunctionNames.
policyMigrationVersion = 3
)
var (
// Tables created by 00001, 00002, and 00003.
outboxTables = []string{"outbox_events"}
identityTableNames = []string{"users", "email_tokens", "sessions"}
policyTableNames = []string{"policy_versions"}
// Trigger functions created by 00003.
policyFunctionNames = []string{"policy_versions_refuse_change()", "policy_versions_stamp_creation()"}
)
func TestPostgresMigrations(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout)
defer cancel()
total := embeddedMigrationCount(t)
t.Run("bootstrap database has every migration applied", func(t *testing.T) {
assertAllApplied(ctx, t, newMigrator(t, env.Config.DatabaseURL), total)
})
t.Run("up, down to zero, and up again on an isolated database", func(t *testing.T) {
databaseURL := env.createIsolatedDatabase(ctx, t)
migrator := newMigrator(t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
applied, err := migrator.Up(ctx)
if err != nil {
t.Fatalf("first Up() error = %v", err)
}
if len(applied) != total {
t.Fatalf("first Up() applied %d migrations, want %d", len(applied), total)
}
assertTablesExist(ctx, t, pool, true, outboxTables...)
assertTablesExist(ctx, t, pool, true, identityTableNames...)
assertTablesExist(ctx, t, pool, true, policyTableNames...)
assertFunctionsExist(ctx, t, pool, true, policyFunctionNames...)
identityRolledBack, policyRolledBack := false, false
for rolledBack := 0; ; rolledBack++ {
result, err := migrator.DownOne(ctx)
if errors.Is(err, postgresadapter.ErrNoMigrationToRollBack) {
if rolledBack != total {
t.Fatalf("rolled back %d migrations, want %d", rolledBack, total)
}
break
}
if err != nil {
t.Fatalf("DownOne() after %d rollbacks error = %v", rolledBack, err)
}
if result.Version == policyMigrationVersion {
// The policy migration rolls back its table, triggers, and
// function and leaves the identity tables.
assertTablesExist(ctx, t, pool, false, policyTableNames...)
assertFunctionsExist(ctx, t, pool, false, policyFunctionNames...)
assertTablesExist(ctx, t, pool, true, identityTableNames...)
policyRolledBack = true
}
if result.Version == identityMigrationVersion {
// The identity migration rolls back on its own and leaves the
// outbox migration before it.
assertTablesExist(ctx, t, pool, false, identityTableNames...)
assertTablesExist(ctx, t, pool, true, outboxTables...)
identityRolledBack = true
}
}
if !identityRolledBack || !policyRolledBack {
t.Fatalf("migrations %d and %d were not both rolled back", identityMigrationVersion, policyMigrationVersion)
}
assertTablesExist(ctx, t, pool, false, outboxTables...)
assertTablesExist(ctx, t, pool, false, identityTableNames...)
assertTablesExist(ctx, t, pool, false, policyTableNames...)
var leftovers int
err = pool.QueryRow(ctx, `
SELECT count(*) FROM pg_catalog.pg_class AS c
JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace
WHERE n.nspname = 'public' AND c.relname NOT LIKE 'goose_db_version%'`).Scan(&leftovers)
if err != nil {
t.Fatalf("count leftover relations: %v", err)
}
if leftovers != 0 {
t.Fatalf("%d relations remain after rolling back every migration", leftovers)
}
var leftoverFunctions int
err = pool.QueryRow(ctx, `
SELECT count(*) FROM pg_catalog.pg_proc AS p
JOIN pg_catalog.pg_namespace AS n ON n.oid = p.pronamespace
WHERE n.nspname = 'public'`).Scan(&leftoverFunctions)
if err != nil {
t.Fatalf("count leftover functions: %v", err)
}
if leftoverFunctions != 0 {
t.Fatalf("%d functions remain after rolling back every migration", leftoverFunctions)
}
applied, err = migrator.Up(ctx)
if err != nil {
t.Fatalf("second Up() error = %v", err)
}
if len(applied) != total {
t.Fatalf("second Up() applied %d migrations, want %d", len(applied), total)
}
assertTablesExist(ctx, t, pool, true, outboxTables...)
assertTablesExist(ctx, t, pool, true, identityTableNames...)
assertTablesExist(ctx, t, pool, true, policyTableNames...)
assertFunctionsExist(ctx, t, pool, true, policyFunctionNames...)
assertAllApplied(ctx, t, migrator, total)
})
t.Run("concurrent runners apply each migration once", func(t *testing.T) {
databaseURL := env.createIsolatedDatabase(ctx, t)
migrators := make([]*postgresadapter.Migrator, concurrentMigrators)
for index := range migrators {
migrators[index] = newMigrator(t, databaseURL)
}
applied := make([]int, len(migrators))
errs := make([]error, len(migrators))
start := make(chan struct{})
var group sync.WaitGroup
for index, migrator := range migrators {
group.Go(func() {
<-start
results, err := migrator.Up(ctx)
applied[index], errs[index] = len(results), err
})
}
close(start)
group.Wait()
sum := 0
for index, err := range errs {
if err != nil {
t.Fatalf("runner %d Up() error = %v", index, err)
}
sum += applied[index]
}
if sum != total {
t.Fatalf("runners applied %d migrations in total, want %d", sum, total)
}
assertAllApplied(ctx, t, migrators[0], total)
})
}
func assertAllApplied(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator, total int) {
t.Helper()
statuses, err := migrator.Status(ctx)
if err != nil {
t.Fatalf("Status() error = %v", err)
}
if len(statuses) != total {
t.Fatalf("Status() lists %d migrations, want %d", len(statuses), total)
}
for _, status := range statuses {
if !status.Applied {
t.Fatalf("migration %s is pending", status.Name)
}
}
}
func assertTablesExist(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want bool, tables ...string) {
t.Helper()
for _, table := range tables {
var exists bool
if err := pool.QueryRow(ctx, `SELECT to_regclass($1) IS NOT NULL`, "public."+table).Scan(&exists); err != nil {
t.Fatalf("check table %s: %v", table, err)
}
if exists != want {
t.Fatalf("%s exists = %t, want %t", table, exists, want)
}
}
}
func assertFunctionsExist(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want bool, signatures ...string) {
t.Helper()
for _, signature := range signatures {
var exists bool
if err := pool.QueryRow(ctx, `SELECT to_regprocedure($1) IS NOT NULL`, "public."+signature).Scan(&exists); err != nil {
t.Fatalf("check function %s: %v", signature, err)
}
if exists != want {
t.Fatalf("function %s exists = %t, want %t", signature, exists, want)
}
}
}