package metadata import ( "context" "testing" ) func TestReferenceMigrationPreservesV1AndRetriesAtomically(t *testing.T) { for _, backend := range []Backend{SQLite, PostgreSQL} { t.Run(string(backend), func(t *testing.T) { r := testRepository(t, backend) ctx := context.Background() id, err := r.CreatePage(ctx, "test", "/existing") if err != nil { t.Fatal(err) } // Reconstruct the preceding portable schema using its unchanged v1 // ledger. None of this targets legacy or production application data. for _, q := range []string{`DROP TABLE revision_document_refs`, `DROP TABLE activity_outbox`, `DROP TABLE activity_outbox_heads`, `DELETE FROM schema_migration_steps WHERE component='core-metadata' AND version=2`} { if _, err := r.database.ExecContext(ctx, q); err != nil { t.Fatal(err) } } _, err = r.database.ExecContext(ctx, `INSERT INTO revisions(uuid,object_uuid,document_hash,lang,content_type,created_at_ms,created_at) VALUES ('existing-revision',`+r.p(1)+`,`+r.p(2)+`,'und','text/plain',1000,1)`, id, hash("old")) if err != nil { t.Fatal(err) } // An unrelated existing table must stop adoption. The earlier DDL in // the same migration must roll back and permit an explicit retry. if _, err := r.database.ExecContext(ctx, `CREATE TABLE activity_outbox(unrelated INTEGER)`); err != nil { t.Fatal(err) } if err := r.InitializeFresh(ctx); err == nil { t.Fatal("unmanaged outbox table adopted") } var count int if err := r.database.QueryRowContext(ctx, `SELECT count(*) FROM revision_document_refs`).Scan(&count); err == nil { t.Fatal("partial v2 DDL remained") } if err := r.database.QueryRowContext(ctx, `SELECT count(*) FROM schema_migration_steps WHERE component='core-metadata' AND version=2`).Scan(&count); err != nil || count != 0 { t.Fatal("failed migration recorded", err) } if _, err := r.database.ExecContext(ctx, `DROP TABLE activity_outbox`); err != nil { t.Fatal(err) } if err := r.InitializeFresh(ctx); err != nil { t.Fatal("migration retry failed", err) } old, err := r.Head(ctx, "test", id, "und") if err != nil || old.UUID != "existing-revision" || old.DocumentHash != hash("old") { t.Fatal("v1 revision altered", err) } if got, err := r.ResolvePath(ctx, "test", "/existing"); err != nil || got != id { t.Fatal("v1 binding altered", err) } if _, err := r.AppendRevision(ctx, "test", Revision{ObjectUUID: id, DocumentHash: hash("new"), ContentType: "text/plain"}, old.UUID); err != nil { t.Fatal("post-migration save failed", err) } if err := r.database.QueryRowContext(ctx, `SELECT count(*) FROM activity_outbox`).Scan(&count); err != nil || count != 1 { t.Fatal("historical revisions spuriously notified", err, count) } }) } }