package db import ( "context" "crypto/rand" "encoding/hex" "errors" "net/url" "os" "strings" "testing" "github.com/golang-migrate/migrate/v4" "github.com/golang-migrate/migrate/v4/source/iofs" "github.com/jackc/pgx/v5" ) // TestMigrationsRoundTrip applies every migration up, every one after the // baseline down, and every one up again, in a database of its own. After the // down pass the schema must equal a database migrated to the baseline alone, // so a down file that leaves a column, index or constraint behind fails here // rather than on someone's rollback. // // The baseline is the whole schema and its down file refuses to run on // purpose, so the round trip stops at it. func TestMigrationsRoundTrip(t *testing.T) { dsn := testDSN(t) ctx := context.Background() scratch := scratchDatabase(ctx, t, dsn) src, err := iofs.New(migrationsFS, "migrations") if err != nil { t.Fatalf("iofs source: %v", err) } baseline, err := src.First() if err != nil { t.Fatalf("first migration: %v", err) } m, err := newMigrator(scratch) if err != nil { t.Fatal(err) } t.Cleanup(func() { m.Close() }) step := func(name string, run func() error) { t.Helper() if err := run(); err != nil && !errors.Is(err, migrate.ErrNoChange) { t.Fatalf("%s: %v", name, err) } } step("migrate to the baseline", func() error { return m.Migrate(baseline) }) want := schemaOf(ctx, t, scratch) step("up", m.Up) step("down to the baseline", func() error { return m.Migrate(baseline) }) got := schemaOf(ctx, t, scratch) if missing, extra := diffLines(want, got); len(missing)+len(extra) > 0 { t.Errorf("the down migrations do not return the schema to the baseline\n"+ "missing after down:\n %s\nleft behind by down:\n %s", strings.Join(missing, "\n "), strings.Join(extra, "\n ")) } step("up again", m.Up) } // testDSN is dbtest.URL for this package, which dbtest imports and so cannot // import back: it skips under -short, and without MINSTREL_TEST_DATABASE_URL // it skips, or fails when MINSTREL_TEST_DATABASE_REQUIRED is set. func testDSN(t *testing.T) string { t.Helper() if testing.Short() { t.Skip("database test; skipped under -short") } dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") if dsn == "" { if os.Getenv("MINSTREL_TEST_DATABASE_REQUIRED") != "" { t.Fatal("MINSTREL_TEST_DATABASE_URL is not set, and MINSTREL_TEST_DATABASE_REQUIRED says this run needs a database") } t.Skip("MINSTREL_TEST_DATABASE_URL not set") } return dsn } // scratchDatabase creates an empty database beside the one dsn names and // returns its URL. It is dropped when the test ends, so the shared test // database the other packages truncate is never migrated down. func scratchDatabase(ctx context.Context, t *testing.T, dsn string) string { t.Helper() admin, err := pgx.Connect(ctx, dsn) if err != nil { t.Fatalf("connect: %v", err) } t.Cleanup(func() { admin.Close(context.Background()) }) b := make([]byte, 6) if _, err := rand.Read(b); err != nil { t.Fatal(err) } name := "migrations_roundtrip_" + hex.EncodeToString(b) if _, err := admin.Exec(ctx, "CREATE DATABASE "+name); err != nil { t.Fatalf("create database: %v", err) } t.Cleanup(func() { if _, err := admin.Exec(context.Background(), "DROP DATABASE IF EXISTS "+name+" WITH (FORCE)"); err != nil { t.Logf("drop %s: %v", name, err) } }) u, err := url.Parse(dsn) if err != nil { t.Fatalf("parse dsn: %v", err) } u.Path = "/" + name return u.String() } // schemaOf lists the public schema as sorted lines: every column with its type, // nullability and default, every index, constraint, sequence, enum value, // function and trigger. schema_migrations is left out; its version moves. func schemaOf(ctx context.Context, t *testing.T, dsn string) []string { t.Helper() conn, err := pgx.Connect(ctx, dsn) if err != nil { t.Fatalf("connect: %v", err) } defer conn.Close(ctx) const q = ` SELECT 'column ' || table_name || '.' || column_name || ' ' || data_type || CASE WHEN is_nullable = 'NO' THEN ' not null' ELSE '' END || COALESCE(' default ' || column_default, '') FROM information_schema.columns WHERE table_schema = 'public' AND table_name <> 'schema_migrations' UNION ALL SELECT 'index ' || indexdef FROM pg_indexes WHERE schemaname = 'public' AND tablename <> 'schema_migrations' UNION ALL SELECT 'constraint ' || c.conrelid::regclass || ' ' || c.conname || ' ' || pg_get_constraintdef(c.oid) FROM pg_constraint c JOIN pg_namespace n ON n.oid = c.connamespace WHERE n.nspname = 'public' AND c.conrelid <> 0 AND c.conrelid::regclass::text <> 'schema_migrations' UNION ALL SELECT 'sequence ' || sequence_name FROM information_schema.sequences WHERE sequence_schema = 'public' UNION ALL SELECT 'enum ' || t.typname || ' ' || e.enumlabel FROM pg_enum e JOIN pg_type t ON t.oid = e.enumtypid JOIN pg_namespace n ON n.oid = t.typnamespace WHERE n.nspname = 'public' UNION ALL SELECT 'function ' || p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')' FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = 'public' UNION ALL SELECT 'trigger ' || event_object_table || ' ' || trigger_name || ' ' || event_manipulation FROM information_schema.triggers WHERE trigger_schema = 'public' ORDER BY 1` rows, err := conn.Query(ctx, q) if err != nil { t.Fatalf("read schema: %v", err) } lines, err := pgx.CollectRows(rows, pgx.RowTo[string]) if err != nil { t.Fatalf("read schema: %v", err) } return lines } // diffLines returns the lines of want missing from got, and the lines of got // that want lacks. Both inputs are sorted. func diffLines(want, got []string) (missing, extra []string) { i, j := 0, 0 for i < len(want) || j < len(got) { switch { case j == len(got) || (i < len(want) && want[i] < got[j]): missing = append(missing, want[i]) i++ case i == len(want) || got[j] < want[i]: extra = append(extra, got[j]) j++ default: i++ j++ } } return missing, extra }