Skip to content

Instantly share code, notes, and snippets.

@suhjohn
Created July 16, 2023 02:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save suhjohn/861367eeb0a50cbaba94becaadf4bf09 to your computer and use it in GitHub Desktop.
Save suhjohn/861367eeb0a50cbaba94becaadf4bf09 to your computer and use it in GitHub Desktop.
Prisma generate new migration with down migration
/**
* 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.');
@jvolonda42
Copy link

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

import * as childeProcess from 'child_process';

childeProcess.execSync(
  `npx prisma migrate dev --name ${migrationName}`,
  { stdio: 'inherit' },
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment