//go:build integration package integration_test import ( "context" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5/pgxpool" postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/domain" ) // holdingsMigrationVersion creates the holdings table and organizations.holding_id. const holdingsMigrationVersion = 41 // legacyMembership is a membership row written without the application. type legacyMembership struct { userID uuid.UUID role string createdAt time.Time } // TestHoldingsMigrationBackfillsFoundersAndGuardsRollback runs the migration on // organizations that were created before holdings existed. The backfill must // give one holding per founder, and the rollback must refuse while a holding // groups several organizations. func TestHoldingsMigrationBackfillsFoundersAndGuardsRollback(t *testing.T) { env := bootstrap(t, postgresService) ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) defer cancel() databaseURL := env.createIsolatedDatabase(ctx, t) migrator := newMigrator(t, databaseURL) pool := newPoolFor(ctx, t, databaseURL) if _, err := migrator.Up(ctx); err != nil { t.Fatalf("Up() error = %v", err) } // The schema before holdings: the organizations are written without them. rollBackAboveMigration(ctx, t, migrator, holdingsMigrationVersion-1) now := time.Now().UTC().Truncate(time.Microsecond).Add(-24 * time.Hour) identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now} founderA := identity.createUser(t, "holding-backfill-first@example.test", domain.ScenarioEmployer, now.Add(-time.Hour)) founderB := identity.createUser(t, "holding-backfill-other@example.test", domain.ScenarioEmployer, now.Add(-time.Hour)) cofounder := identity.createUser(t, "holding-backfill-cofounder@example.test", domain.ScenarioEmployer, now.Add(-time.Hour)) first := insertLegacyOrganization(ctx, t, pool, "Legacy first", now, legacyMembership{userID: founderA.ID, role: "owner", createdAt: now}) second := insertLegacyOrganization(ctx, t, pool, "Legacy second", now.Add(time.Hour), legacyMembership{userID: founderA.ID, role: "owner", createdAt: now.Add(time.Hour)}, // A later owner does not change the founder: the earliest membership does. legacyMembership{userID: cofounder.ID, role: "owner", createdAt: now.Add(2 * time.Hour)}) other := insertLegacyOrganization(ctx, t, pool, "Legacy other", now.Add(30*time.Minute), legacyMembership{userID: founderB.ID, role: "owner", createdAt: now.Add(30 * time.Minute)}) if _, err := migrator.Up(ctx); err != nil { t.Fatalf("Up() with the holdings migration error = %v", err) } // Later migrations sit above holdings: the rollback subtests undo holdings // with DownOne, so the schema is taken back to the holdings version first. rollBackAboveMigration(ctx, t, migrator, holdingsMigrationVersion) t.Run("backfill gives each founder one holding dated by its first organization", func(t *testing.T) { firstHolding := legacyHolding(ctx, t, pool, first) if got := legacyHolding(ctx, t, pool, second); got != firstHolding { t.Fatalf("holding of the second organization = %s, want the founder's holding %s", got, firstHolding) } if got := legacyHolding(ctx, t, pool, other); got == firstHolding { t.Fatal("two founders share one holding") } assertLegacyHoldingFounder(ctx, t, pool, firstHolding, founderA.ID, now) assertLegacyHoldingFounder(ctx, t, pool, legacyHolding(ctx, t, pool, other), founderB.ID, now.Add(30*time.Minute)) var count int64 if err := pool.QueryRow(ctx, `SELECT count(*) FROM holdings`).Scan(&count); err != nil { t.Fatalf("count holdings: %v", err) } if count != 2 { t.Fatalf("holdings = %d, want one per founder (2)", count) } }) t.Run("rollback refuses while a holding groups several organizations", func(t *testing.T) { _, err := migrator.DownOne(ctx) assertPgError(t, "DownOne() with a grouped holding", err, privacyIntegrityViolation, "organizations_holding_grouped") if got := legacyHolding(ctx, t, pool, first); got != legacyHolding(ctx, t, pool, second) { t.Fatal("refused rollback changed the grouping") } }) t.Run("rollback succeeds once every holding has one organization", func(t *testing.T) { split := uuid.Must(uuid.NewV7()) if _, err := pool.Exec(ctx, ` INSERT INTO holdings (id, founder_account_id, created_at) VALUES ($1, $2, $3)`, split, cofounder.ID, now); err != nil { t.Fatalf("insert the holding of the split organization: %v", err) } if _, err := pool.Exec(ctx, `UPDATE organizations SET holding_id = $2 WHERE id = $1`, second, split); err != nil { t.Fatalf("move the second organization to its own holding: %v", err) } if _, err := migrator.DownOne(ctx); err != nil { t.Fatalf("DownOne() with single-organization holdings error = %v", err) } var holdingsGone, columnGone bool var organizations int64 if err := pool.QueryRow(ctx, ` SELECT to_regclass('public.holdings') IS NULL, NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'organizations' AND column_name = 'holding_id'), (SELECT count(*) FROM organizations)`).Scan(&holdingsGone, &columnGone, &organizations); err != nil { t.Fatalf("read the rolled-back schema: %v", err) } if !holdingsGone || !columnGone { t.Fatalf("rollback left holdings table gone = %t, holding_id column gone = %t", holdingsGone, columnGone) } if organizations != 3 { t.Fatalf("organizations after rollback = %d, want the 3 that were created", organizations) } // Applying the migration again backfills the same grouping from the // memberships, so the founders get one holding each. if _, err := migrator.Up(ctx); err != nil { t.Fatalf("Up() after the rollback error = %v", err) } if got := legacyHolding(ctx, t, pool, second); got != legacyHolding(ctx, t, pool, first) { t.Fatal("reapplied backfill does not group the founder's organizations") } }) } // insertLegacyOrganization stores an organization and its memberships in one // transaction, as creation did before holdings. The owner membership keeps the // deferred constraint satisfied at commit. func insertLegacyOrganization( ctx context.Context, t *testing.T, pool *pgxpool.Pool, name string, createdAt time.Time, memberships ...legacyMembership, ) uuid.UUID { t.Helper() organizationID := uuid.Must(uuid.NewV7()) tx, err := pool.Begin(ctx) if err != nil { t.Fatalf("begin legacy organization transaction: %v", err) } defer func() { _ = tx.Rollback(ctx) }() if _, err := tx.Exec(ctx, ` INSERT INTO organizations ( id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at ) VALUES ($1, $2, 'e0', 'confirmed_email', $3, 1, $3, $3)`, organizationID, name, createdAt); err != nil { t.Fatalf("insert legacy organization: %v", err) } for _, membership := range memberships { if _, err := tx.Exec(ctx, ` INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at) VALUES ($1, $2, $3, $4, 'active', $5, $5)`, uuid.Must(uuid.NewV7()), organizationID, membership.userID, membership.role, membership.createdAt); err != nil { t.Fatalf("insert legacy membership: %v", err) } } if err := tx.Commit(ctx); err != nil { t.Fatalf("commit legacy organization: %v", err) } return organizationID } func legacyHolding(ctx context.Context, t *testing.T, pool *pgxpool.Pool, organizationID uuid.UUID) uuid.UUID { t.Helper() var holdingID uuid.UUID if err := pool.QueryRow(ctx, `SELECT holding_id FROM organizations WHERE id = $1`, organizationID).Scan(&holdingID); err != nil { t.Fatalf("read holding of organization: %v", err) } return holdingID } func assertLegacyHoldingFounder(ctx context.Context, t *testing.T, pool *pgxpool.Pool, holdingID, founderID uuid.UUID, createdAt time.Time) { t.Helper() var gotFounder uuid.UUID var gotCreatedAt time.Time if err := pool.QueryRow(ctx, ` SELECT founder_account_id, created_at FROM holdings WHERE id = $1`, holdingID).Scan(&gotFounder, &gotCreatedAt); err != nil { t.Fatalf("read holding: %v", err) } if gotFounder != founderID { t.Fatalf("holding founder = %s, want %s", gotFounder, founderID) } if !gotCreatedAt.Equal(createdAt) { t.Fatalf("holding created_at = %s, want %s", gotCreatedAt, createdAt) } }