MCPcopy Index your code
hub / github.com/simstudioai/sim / chunkedBatchDelete

Function chunkedBatchDelete

apps/sim/lib/cleanup/batch-delete.ts:100–178  ·  view source on GitHub ↗
({
  tableDef,
  workspaceIds,
  tableName,
  selectChunk,
  onBatch,
  batchSize = DEFAULT_BATCH_SIZE,
  maxBatches = DEFAULT_MAX_BATCHES_PER_TABLE,
  totalRowLimit = DEFAULT_BATCH_SIZE * DEFAULT_MAX_BATCHES_PER_TABLE,
  workspaceChunkSize = DEFAULT_WORKSPACE_CHUNK_SIZE,
}: ChunkedBatchDeleteOptions<TRow>)

Source from the content-addressed store, hash-verified

98 * `DEFAULT_WORKSPACE_CHUNK_SIZE` for why.
99 */
100export async function chunkedBatchDelete<TRow extends { id: string }>({
101 tableDef,
102 workspaceIds,
103 tableName,
104 selectChunk,
105 onBatch,
106 batchSize = DEFAULT_BATCH_SIZE,
107 maxBatches = DEFAULT_MAX_BATCHES_PER_TABLE,
108 totalRowLimit = DEFAULT_BATCH_SIZE * DEFAULT_MAX_BATCHES_PER_TABLE,
109 workspaceChunkSize = DEFAULT_WORKSPACE_CHUNK_SIZE,
110}: ChunkedBatchDeleteOptions<TRow>): Promise<TableCleanupResult> {
111 const result: TableCleanupResult = { table: tableName, deleted: 0, failed: 0 }
112
113 if (workspaceIds.length === 0) {
114 logger.info(`[${tableName}] Skipped — no workspaces in scope`)
115 return result
116 }
117
118 const chunks = chunkArray(workspaceIds, workspaceChunkSize)
119 let stoppedEarly = false
120 let attempted = 0
121
122 for (const [chunkIdx, chunkIds] of chunks.entries()) {
123 if (attempted >= totalRowLimit) {
124 stoppedEarly = true
125 break
126 }
127
128 let batchesProcessed = 0
129 let hasMore = true
130
131 while (hasMore && batchesProcessed < maxBatches && attempted < totalRowLimit) {
132 let rows: TRow[] = []
133 try {
134 const remainingLimit = totalRowLimit - attempted
135 const effectiveBatchSize = Math.min(batchSize, remainingLimit)
136 if (effectiveBatchSize <= 0) {
137 hasMore = false
138 break
139 }
140
141 rows = await selectChunk(chunkIds, effectiveBatchSize)
142
143 if (rows.length === 0) {
144 hasMore = false
145 break
146 }
147
148 attempted += rows.length
149 if (onBatch) await onBatch(rows)
150
151 const ids = rows.map((r) => r.id)
152 const deleted = await db
153 .delete(tableDef)
154 .where(inArray(sql`id`, ids))
155 .returning({ id: sql`id` })
156
157 result.deleted += deleted.length

Calls 4

chunkArrayFunction · 0.85
infoMethod · 0.80
errorMethod · 0.80
deleteMethod · 0.65

Tested by

no test coverage detected