|
| 1 | +import { PrismaClient } from '@klicker-uzh/prisma/client' |
| 2 | +import { getInitialInstanceStatistics } from '@klicker-uzh/util' |
| 3 | +import { PrismaPg } from '@prisma/adapter-pg' |
| 4 | + |
| 5 | +// ! IMPORTANT INFORMATION |
| 6 | +// Find all element instances that do not have instance statistics assigned yet to make them properly required |
| 7 | + |
| 8 | +const DRY_RUN = false |
| 9 | + |
| 10 | +async function run() { |
| 11 | + const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL }) |
| 12 | + const prisma = new PrismaClient({ adapter }) |
| 13 | + |
| 14 | + // find all element instances that do not have instance statistics assigned yet |
| 15 | + const instancesWithoutStatistics = await prisma.elementInstance.count({ |
| 16 | + where: { instanceStatistics: null }, |
| 17 | + }) |
| 18 | + console.log('Found instances without statistics:', instancesWithoutStatistics) |
| 19 | + |
| 20 | + if (DRY_RUN) { |
| 21 | + console.log('DRY RUN is enabled, not making any changes. Exiting now...') |
| 22 | + return |
| 23 | + } |
| 24 | + |
| 25 | + // loop over the instances in batches of 100 and add instance statistics to the ones with missing ones |
| 26 | + const batchSize = 100 |
| 27 | + for (let i = 0; i < instancesWithoutStatistics; i += batchSize) { |
| 28 | + const instances = await prisma.elementInstance.findMany({ |
| 29 | + where: { instanceStatistics: null }, |
| 30 | + orderBy: { id: 'desc' }, |
| 31 | + take: batchSize, |
| 32 | + }) |
| 33 | + |
| 34 | + console.log(`Processing batch ${i / batchSize + 1}...`) |
| 35 | + |
| 36 | + for (const instance of instances) { |
| 37 | + await prisma.elementInstance.update({ |
| 38 | + where: { id: instance.id, instanceStatistics: null }, |
| 39 | + data: { |
| 40 | + instanceStatistics: { |
| 41 | + create: getInitialInstanceStatistics(instance.type), |
| 42 | + }, |
| 43 | + }, |
| 44 | + }) |
| 45 | + |
| 46 | + console.log( |
| 47 | + `Added instance statistics for element instance with ID ${instance.id}` |
| 48 | + ) |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + console.log('Done adding missing instance statistics.') |
| 53 | + |
| 54 | + // return / exit the process |
| 55 | + return process.exit(0) |
| 56 | +} |
| 57 | + |
| 58 | +await run() |
0 commit comments