Created
July 16, 2023 02:11
-
-
Save suhjohn/861367eeb0a50cbaba94becaadf4bf09 to your computer and use it in GitHub Desktop.
Prisma generate new migration with down migration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* generate-migration.ts | |
* | |
* This script generates a migration that moves the down.sql file to the latest migration folder. | |
* Use: | |
* ts-node generate-migration.ts <MIGRATION_NAME> | |
* yarn migrate:generate <MIGRATION_NAME> | |
*/ | |
import { execSync } from 'child_process'; | |
import { log } from 'console'; | |
import fs from 'fs'; | |
import path from 'path'; | |
// Name of the migration | |
const migrationName: string = process.argv[2]; | |
if (!migrationName) { | |
throw new Error('Please provide a name for the migration'); | |
} | |
// Directories | |
const migrationsDir: string = path.resolve(__dirname, '../prisma/migrations'); | |
const schemaFile: string = path.resolve(__dirname, '../prisma/schema.prisma'); | |
const downMigrationFile: string = path.resolve(migrationsDir, 'down.sql'); | |
// 1. Generate down migration | |
log('Generating down migration...'); | |
execSync( | |
`npx prisma migrate diff --from-schema-datamodel ${schemaFile} --to-schema-datasource ${schemaFile} --script > ${downMigrationFile}`, | |
); | |
// 2. Generate up migration and run it locally | |
log('Running up migration...'); | |
execSync(`npx prisma migrate dev --name ${migrationName}`); | |
// Get the latest migration directory | |
const latestMigrationDir: string = fs | |
.readdirSync(migrationsDir) | |
.map((dir) => ({ dir, timestamp: dir.split('_')[0] })) | |
.sort((a, b) => parseInt(b.timestamp, 10) - parseInt(a.timestamp, 10))[0].dir; | |
// 3. Move the down migration to the migrations/<YOUR MIGRATION> folder | |
log('Moving down migration to the latest migration folder...'); | |
fs.renameSync( | |
downMigrationFile, | |
path.join(migrationsDir, latestMigrationDir, 'down.sql'), | |
); | |
// 4. Run prisma generate | |
log('Running Prisma generate...'); | |
execSync('npx prisma generate'); | |
log('Migration completed successfully.'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, Thanks for your script.
I just updated the line 33 with this code otherwise prisma will fail due to not being executed in an interactive terminal