// Read local backup artifacts only. This script has no database or network connection. const fs = require('node:fs'), path = require('node:path'), crypto = require('node:crypto'), assert = require('node:assert/strict') const backup = path.resolve(process.argv[2] || '') const allowed = path.resolve(__dirname, '../../.codex-tmp/database-backups') assert.ok(backup.startsWith(allowed + path.sep), 'Use a target backup inside the named backup directory') const manifest = JSON.parse(fs.readFileSync(path.join(backup, 'manifest.json'), 'utf8')) assert.equal(manifest.database, 'cmvr-project-dev'); assert.equal(manifest.complete, true); assert.equal(manifest.readOnly, true) const sql = fs.readFileSync(path.join(backup, 'cmvr-project-dev.sql'), 'utf8') assert.equal(crypto.createHash('sha256').update(sql).digest('hex'), manifest.sha256) assert.ok(sql.endsWith('-- BACKUP COMPLETE\n')) const tables = new Map(Object.keys(manifest.tables).map(name => [name, []])) for (const line of sql.split('\n')) { if (!line.startsWith('INSERT INTO ')) continue const m = /^INSERT INTO `([^`]+)` \(([^)]+)\) VALUES \((.*)\);$/.exec(line) assert.ok(m, 'Unexpected backup insert format') const columns = m[2].split(',').map(v => v.replaceAll('`', '')), values = m[3].split(',') // Generated by BackupReplayTarget: string and binary values are hex, so literals contain no commas. assert.equal(columns.length, values.length) tables.get(m[1]).push(Object.fromEntries(columns.map((col,i) => [col, values[i]]))) } for (const [name, rows] of tables) assert.equal(rows.length, manifest.tables[name].rows, 'Backup row count: ' + name) const protectedTables = [...tables.keys()].filter(name => name.startsWith('pm_') || name === 'project_member') const protectedRows = new Map(protectedTables.map(name => [name, new Set(tables.get(name))])) // The legacy membership mapper has logical references even when MySQL has no FK. for (const [column,table,key] of [['project_id','project_info','id'],['user_id','sys_user','user_id']]) { const wanted=new Set((tables.get('project_member')||[]).map(row=>row[column]).filter(value=>value&&value!=='NULL')) if(!protectedRows.has(table))protectedRows.set(table,new Set()) for(const row of tables.get(table)||[])if(wanted.has(row[key]))protectedRows.get(table).add(row) } let changed = true while (changed) { changed = false for (const fk of manifest.foreignKeys) { const rows = protectedRows.get(fk.TABLE_NAME) if (!rows) continue const values = new Set([...rows].map(row => row[fk.COLUMN_NAME]).filter(value => value != null && value !== 'NULL')) for (const row of tables.get(fk.REFERENCED_TABLE_NAME) || []) { if (!values.has(row[fk.REFERENCED_COLUMN_NAME])) continue if (!protectedRows.has(fk.REFERENCED_TABLE_NAME)) protectedRows.set(fk.REFERENCED_TABLE_NAME, new Set()) const keep = protectedRows.get(fk.REFERENCED_TABLE_NAME) if (!keep.has(row)) { keep.add(row); changed = true } } } } const externalReferences = [...protectedRows].filter(([name]) => !protectedTables.includes(name)).map(([table, rows]) => ({table, protectedRows:rows.size})) const result = { target:'cmvr-project-dev', source:'wms-dev', databaseWrites:0, backupValidated:true, backup:path.join(backup,'cmvr-project-dev.sql'), backupSha256:manifest.sha256, backedUpTables:tables.size, backedUpRows:[...tables.values()].reduce((sum,rows) => sum+rows.length,0), protectedTables:protectedTables.map(table => ({table, rows:tables.get(table).length, fingerprint:manifest.tables[table].rowFingerprint})), externalReferences, protectedProjectIds:[...protectedRows.get('project_info') || []].map(row => Number(row.id)), protectedUserIds:[...protectedRows.get('sys_user')||[]].map(row=>Number(row.user_id)), unresolvedBeforeDeletion:[], deletionPerformed:false, replayPerformed:false } fs.writeFileSync(path.join(backup,'preservation-preflight.json'), JSON.stringify(result,null,2), {flag:'wx'}) console.log(JSON.stringify({backupValidated:result.backupValidated,backedUpTables:result.backedUpTables,backedUpRows:result.backedUpRows,protectedTables:protectedTables.length,externalReferences,protectedProjectIds:result.protectedProjectIds,databaseWrites:0},null,2))