From 63e826f9913ff0dac6c37dd9c4dcb85e2541a480 Mon Sep 17 00:00:00 2001 From: Baptiste Arnaud Date: Sat, 24 Jun 2023 09:02:56 +0200 Subject: [PATCH] :green_heart: (db) Fix verification bulk delete When it has more than 100000 records --- packages/scripts/cleanDatabase.ts | 35 ++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/packages/scripts/cleanDatabase.ts b/packages/scripts/cleanDatabase.ts index 5af580b18..20c590390 100644 --- a/packages/scripts/cleanDatabase.ts +++ b/packages/scripts/cleanDatabase.ts @@ -115,14 +115,35 @@ const deleteExpiredAppSessions = async () => { const deleteExpiredVerificationTokens = async () => { const threeDaysAgo = new Date() threeDaysAgo.setDate(threeDaysAgo.getDate() - 3) - const { count } = await prisma.verificationToken.deleteMany({ - where: { - expires: { - lte: threeDaysAgo, + let totalVerificationTokens + do { + const verificationTokens = await prisma.verificationToken.findMany({ + where: { + expires: { + lte: threeDaysAgo, + }, }, - }, - }) - console.log(`Deleted ${count} expired verifiations tokens.`) + select: { + token: true, + }, + take: 80000, + }) + + totalVerificationTokens = verificationTokens.length + + console.log(`Deleting ${verificationTokens.length} expired tokens...`) + const chunkSize = 1000 + for (let i = 0; i < verificationTokens.length; i += chunkSize) { + const chunk = verificationTokens.slice(i, i + chunkSize) + await prisma.verificationToken.deleteMany({ + where: { + token: { + in: chunk.map((verificationToken) => verificationToken.token), + }, + }, + }) + } + } while (totalVerificationTokens === 80000) } const resetQuarantinedWorkspaces = async () =>