()
| 99 | } |
| 100 | |
| 101 | async function run() { |
| 102 | const args = parseArgs(process.argv.slice(2)); |
| 103 | const sourceDatabaseUrl = process.env.POSTGRES_URL; |
| 104 | if (!sourceDatabaseUrl) { |
| 105 | throw new Error('Missing required environment variable: POSTGRES_URL'); |
| 106 | } |
| 107 | |
| 108 | const keepDrillDatabase = args['keep-db'] === true || args['keep-db'] === 'true'; |
| 109 | const retentionDays = Number.parseInt(args['retention-days'] || process.env.BACKUP_RETENTION_DAYS || '14', 10); |
| 110 | const backupDir = path.resolve(args['backup-dir'] || process.env.BACKUP_DIR || path.join(process.cwd(), 'backups')); |
| 111 | |
| 112 | ensureCommand('pg_dump'); |
| 113 | ensureCommand('pg_restore'); |
| 114 | |
| 115 | await mkdir(backupDir, { recursive: true }); |
| 116 | |
| 117 | const stamp = createTimestamp(); |
| 118 | const backupPath = path.join(backupDir, `restore-drill-${stamp}.dump`); |
| 119 | const drillDatabaseName = `titanbot_restore_drill_${stamp}`; |
| 120 | const maintenanceUrl = buildDatabaseUrlWithName(sourceDatabaseUrl, 'postgres'); |
| 121 | const drillDatabaseUrl = buildDatabaseUrlWithName(sourceDatabaseUrl, drillDatabaseName); |
| 122 | |
| 123 | const maintenancePool = new Pool({ connectionString: maintenanceUrl }); |
| 124 | |
| 125 | logger.info('Starting restore drill', { |
| 126 | event: 'restore_drill.start', |
| 127 | drillDatabaseName |
| 128 | }); |
| 129 | |
| 130 | try { |
| 131 | runCommand('pg_dump', [ |
| 132 | '--format=custom', |
| 133 | '--no-owner', |
| 134 | '--no-privileges', |
| 135 | '--file', |
| 136 | backupPath, |
| 137 | sourceDatabaseUrl |
| 138 | ]); |
| 139 | |
| 140 | const createClient = await maintenancePool.connect(); |
| 141 | try { |
| 142 | await createClient.query(`CREATE DATABASE "${drillDatabaseName}" TEMPLATE template0`); |
| 143 | } finally { |
| 144 | createClient.release(); |
| 145 | } |
| 146 | |
| 147 | runCommand('pg_restore', [ |
| 148 | '--clean', |
| 149 | '--if-exists', |
| 150 | '--no-owner', |
| 151 | '--no-privileges', |
| 152 | '--dbname', |
| 153 | drillDatabaseUrl, |
| 154 | backupPath |
| 155 | ]); |
| 156 | |
| 157 | const verifyPool = new Pool({ connectionString: drillDatabaseUrl }); |
| 158 | try { |
no test coverage detected