package v071 import ( "context" "encoding/json" "errors" "fmt" "github.com/jackc/pgx/v5" ) // Recovery bytes are not a source candidate. The selection must equal the // destructive target predicate, including tombstones and their relationships. // Semantic source validation would discard/reject exactly those historical // rows that an exact rollback must preserve. func exportLibraryBeforeImage(ctx context.Context, db librarySnapshotDB, identity PostgresIdentity) (PostgresSnapshot, error) { tx, err := db.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly}) if err != nil { return PostgresSnapshot{}, err } defer tx.Rollback(context.WithoutCancel(ctx)) profile, err := ResolveSchemaProfile(ctx, tx, "before-image source") if err != nil { return PostgresSnapshot{}, err } exporter := PostgresExporter{db: tx} rowsByTable := map[string][]json.RawMessage{} var bodies, bindings []json.RawMessage for _, table := range profile.Tables { if table == "resources" { continue } rows, err := exporter.queryRows(ctx, fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s ORDER BY (%s)::text`, table, table, scopeWhereFor(profile.Tables, table), identityExpr(table)), identity.TenantID, identity.KnowledgeBaseID) if err != nil { return PostgresSnapshot{}, err } rowsByTable[table] = rows if table != "resource_bindings" && table != "knowledge_tag_relations" { bodies = append(bodies, rows...) } if table == "resource_bindings" { bindings = rows } } // F01: the before-image needs exact rollback rows, including deleted // resources, but must not rescan every tenant resource per body table. resources, err := scopedResourceRows(ctx, &exporter, identity, true, bodies, bindings) if err != nil { return PostgresSnapshot{}, err } rowsByTable["resources"] = resources snapshot := PostgresSnapshot{SchemaVersion: profile.SchemaVersion, Profile: profile.Name} for _, table := range profile.Tables { snapshot.Tables = append(snapshot.Tables, newTableSnapshot(table, rowsByTable[table])) } handles, err := libraryResourceHandles(bodies) if err != nil { return PostgresSnapshot{}, err } resourceHandles := map[string]bool{} resourceIDs := []string{} for _, raw := range snapshot.Table("resources").Rows { var row struct { ID string `json:"id"` Handle string `json:"handle"` } if err := json.Unmarshal(raw, &row); err != nil { return PostgresSnapshot{}, err } resourceHandles[row.Handle] = true resourceIDs = append(resourceIDs, row.ID) } for _, handle := range handles { if !resourceHandles[handle] { return PostgresSnapshot{}, errors.New("before-image contains unresolved resource reference") } } if err := verifyLibraryResourceOwners(ctx, tx, resourceIDs); err != nil { return PostgresSnapshot{}, err } if err := tx.Commit(ctx); err != nil { return PostgresSnapshot{}, err } return snapshot, nil }