Skip to content

Commit

Permalink
Balances Squash script
Browse files Browse the repository at this point in the history
  • Loading branch information
casesandberg committed Sep 28, 2024
1 parent 5afb6e1 commit 894ef6c
Showing 1 changed file with 72 additions and 0 deletions.
72 changes: 72 additions & 0 deletions packages/database/scripts/balances-squash.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// @ts-nocheck
import db from '../prisma'

const startBalanceIds = ['cm1hmp45500254quvzhzazvrf', 'cm1hmpbwu003c4quvvj5z4up5']
const endBalanceId = 'cm0apnra5006n65jijps76cg4'

async function main() {
try {
let numberSquashed = 0

await db.$transaction(async (tx) => {
const endBalance = await tx.balance.findUniqueOrThrow({
where: {
id: endBalanceId,
},
})

for (const balanceId of startBalanceIds) {
const balance = await tx.balance.findUnique({
where: {
id: balanceId,
},
})

if (balance) {
const newSubtotals = { ...endBalance.subtotals }
for (const key in balance.subtotals) {
if (endBalance.subtotals[key]) {
newSubtotals[key] += balance.subtotals[key]
} else {
newSubtotals[key] = balance.subtotals[key]
}
}

await tx.balance.update({
where: {
id: endBalanceId,
},
data: {
total: {
increment: balance.total,
},
subtotals: newSubtotals,
},
})

await tx.balance.delete({
where: {
id: balanceId,
},
})

numberSquashed++
}
}
})

console.log(`Squashed ${numberSquashed} balances into endBalanceId`)
} catch (fetchError) {
const error = fetchError as Error
console.error(`An error occurred while fetching users: ${error.message}`)
} finally {
await db.$disconnect()
console.log('Database connection closed.')
}
}

main().catch((e) => {
const error = e as Error
console.error(`Unexpected error: ${error.message}`)
process.exit(1)
})

0 comments on commit 894ef6c

Please sign in to comment.