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)) var version int var dirty bool if err := tx.QueryRow(ctx, `SELECT version,dirty FROM schema_migrations LIMIT 1`).Scan(&version, &dirty); err != nil || version != 74 || dirty { return PostgresSnapshot{}, errors.New("before-image schema contract mismatch") } exporter := PostgresExporter{db: tx} snapshot := PostgresSnapshot{} for _, table := range productionLibraryTables { rows, err := exporter.queryRows(ctx, fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s ORDER BY (%s)::text`, table, table, scopeWhere(table), identityExpr(table)), identity.TenantID, identity.KnowledgeBaseID) if err != nil { return PostgresSnapshot{}, err } snapshot.Tables = append(snapshot.Tables, newTableSnapshot(table, rows)) } var bodies []json.RawMessage for _, table := range snapshot.Tables { bodies = append(bodies, table.Rows...) } 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 }