|
| 1 | +const SCHEMA = 'prisma/schema.prisma'; |
| 2 | +const BACKUP = 'prisma/schema.prisma.backup'; |
| 3 | +const ANNOTATION = '/// @view'; |
| 4 | + |
| 5 | +import { readFile, writeFile, copyFile, rename, unlink } from 'fs/promises'; |
| 6 | +import { argv } from 'process'; |
| 7 | +import { spawnSync } from 'child_process'; |
| 8 | +const spawnOptions = { stdio: 'inherit', shell: true }; |
| 9 | + |
| 10 | +// Backup the schema |
| 11 | +await copyFile(SCHEMA, BACKUP); |
| 12 | +console.log('Backed up schema to', BACKUP); |
| 13 | + |
| 14 | +// Remove all views |
| 15 | +console.log('Removing views from schema...'); |
| 16 | +const schema = await readFile(SCHEMA, 'utf-8'); |
| 17 | +const viewRegex = new RegExp(`\n?${ANNOTATION}\nmodel ([a-zA-Z]+) {[^}]+}\n?`, 'g'); |
| 18 | +const modelNames = [...schema.matchAll(viewRegex)].map(([_, name]) => name); |
| 19 | +let modifiedSchema = schema.replace(viewRegex, ''); |
| 20 | +for (const modelName of modelNames) { |
| 21 | + const modelRegex = new RegExp(`^.+${modelName}.*\n?`, 'gm'); |
| 22 | + modifiedSchema = modifiedSchema.replace(modelRegex, ''); |
| 23 | +} |
| 24 | +await writeFile(SCHEMA, modifiedSchema, 'utf-8'); |
| 25 | +console.log('Removing views from schema... Done'); |
| 26 | + |
| 27 | +try { |
| 28 | + // Run the migration |
| 29 | + console.log('Running `prisma migrate dev`... '); |
| 30 | + let { error } = spawnSync('prisma migrate dev', argv.slice(2), spawnOptions); |
| 31 | + if (error) throw error; |
| 32 | + console.log('Running `prisma migrate dev`... Done'); |
| 33 | + |
| 34 | + // Restore the schema |
| 35 | + console.log('Restoring backup and running `npx prisma generate`... '); |
| 36 | + await unlink(SCHEMA); |
| 37 | + await rename(BACKUP, SCHEMA); |
| 38 | + ({ error } = spawnSync('prisma generate', spawnOptions)); |
| 39 | + if (error) throw error; |
| 40 | + console.log('Restoring backup and running `npx prisma generate`... Done'); |
| 41 | +} catch (error) { |
| 42 | + // Restore the schema |
| 43 | + console.log('Restoring backup... '); |
| 44 | + await unlink(SCHEMA); |
| 45 | + await rename(BACKUP, SCHEMA); |
| 46 | + console.log('Restoring backup... Done'); |
| 47 | + |
| 48 | + // Rethrow the error |
| 49 | + throw error; |
| 50 | +} |
0 commit comments