/** Extracts the transaction handle type from any Drizzle db. */ type TxOf = DB extends { transaction: (cb: (tx: infer Tx) => any, ...args: any[]) => any; } ? Tx : never; /** * Runs `runChunk` sequentially over `items` inside a single transaction, * passing at most `n` items per call. All chunks commit together, or the * whole thing rolls back. * * @param db Drizzle database instance. * @param items Full array of values (e.g. product ids). * @param n Max items per batch (keep under SQLite's 999 var limit). * @param runChunk Async fn that runs your query for one chunk, using `tx`. */ export async function runBatched< DB extends { transaction: (cb: (tx: any) => any, ...args: any[]) => any }, T, R, >( db: DB, items: readonly T[], n: number, runChunk: (tx: TxOf, chunk: T[]) => Promise, ): Promise { if (n < 1) throw new RangeError("`n` must be >= 1"); const result = await db.transaction(async (tx: TxOf) => { const out: R[] = []; for (let i = 0; i < items.length; i += n) { out.push(await runChunk(tx, items.slice(i, i + n))); } return out; }); return result as R[]; }