( tableDef: PgTable, idCol: PgColumn, ids: string[], tableName: string, chunkSize: number = DEFAULT_DELETE_CHUNK_SIZE )
| 228 | * Partial progress survives chunk-level failures. |
| 229 | */ |
| 230 | export async function deleteRowsById( |
| 231 | tableDef: PgTable, |
| 232 | idCol: PgColumn, |
| 233 | ids: string[], |
| 234 | tableName: string, |
| 235 | chunkSize: number = DEFAULT_DELETE_CHUNK_SIZE |
| 236 | ): Promise<TableCleanupResult> { |
| 237 | const result: TableCleanupResult = { table: tableName, deleted: 0, failed: 0 } |
| 238 | if (ids.length === 0) return result |
| 239 | |
| 240 | const chunks = chunkArray(ids, chunkSize) |
| 241 | for (const [chunkIdx, chunkIds] of chunks.entries()) { |
| 242 | try { |
| 243 | const deleted = await db |
| 244 | .delete(tableDef) |
| 245 | .where(inArray(idCol, chunkIds)) |
| 246 | .returning({ id: idCol }) |
| 247 | result.deleted += deleted.length |
| 248 | } catch (error) { |
| 249 | // Upper bound: Postgres rolls back the chunk on error, so actual deletes = 0, |
| 250 | // but we can't tell which IDs in the chunk would have matched. The next cron |
| 251 | // run picks up whatever's still expired, so this only inflates the metric. |
| 252 | result.failed += chunkIds.length |
| 253 | logger.error( |
| 254 | `[${tableName}] Delete chunk ${chunkIdx + 1}/${chunks.length} failed (up to ${chunkIds.length} rows):`, |
| 255 | { error } |
| 256 | ) |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | logger.info( |
| 261 | `[${tableName}] Deleted ${result.deleted} rows across ${chunks.length} chunk(s)${result.failed > 0 ? `, ${result.failed} failed` : ''}` |
| 262 | ) |
| 263 | return result |
| 264 | } |
no test coverage detected