migrate.ts•4.26 kB
/// <reference types="node" />
/**
* Database migration script
*
* This script provides commands for managing database migrations:
* - create: Creates a new migration based on schema changes
* - apply: Applies pending migrations to the database
* - reset: Resets the database and applies all migrations
* - status: Shows the status of migrations
*/
import * as childProcess from 'child_process';
import * as path from 'path';
import * as fs from 'fs';
// Use execSync from child_process
const { execSync } = childProcess;
// Ensure the script is run from the project root
const projectRoot = path.resolve(__dirname, '..');
process.chdir(projectRoot);
// Command line arguments
const command = process.argv[2];
const migrationName = process.argv[3];
// Available commands
const COMMANDS = {
CREATE: 'create',
APPLY: 'apply',
RESET: 'reset',
STATUS: 'status',
};
/**
* Create a new migration
*/
function createMigration(name: string): void {
if (!name) {
console.error('Migration name is required');
console.log('Usage: npm run migrate:create <migration-name>');
process.exit(1);
}
try {
console.log(`Creating migration: ${name}...`);
execSync(`npx prisma migrate dev --name ${name}`, { stdio: 'inherit' });
console.log(`Migration ${name} created successfully!`);
} catch (error) {
console.error('Failed to create migration:', error);
process.exit(1);
}
}
/**
* Apply pending migrations
*/
function applyMigrations(): void {
try {
console.log('Applying pending migrations...');
execSync('npx prisma migrate deploy', { stdio: 'inherit' });
console.log('Migrations applied successfully!');
// Generate Prisma client
console.log('Generating Prisma client...');
execSync('npx prisma generate', { stdio: 'inherit' });
console.log('Prisma client generated successfully!');
} catch (error) {
console.error('Failed to apply migrations:', error);
process.exit(1);
}
}
/**
* Reset database and apply all migrations
*/
function resetDatabase(): void {
try {
console.log('Resetting database...');
execSync('npx prisma migrate reset --force', { stdio: 'inherit' });
console.log('Database reset successfully!');
} catch (error) {
console.error('Failed to reset database:', error);
process.exit(1);
}
}
/**
* Show migration status
*/
function showStatus(): void {
try {
// Get list of migrations from the migrations directory
const migrationsDir = path.join(projectRoot, 'prisma', 'migrations');
const migrations = fs.readdirSync(migrationsDir)
.filter(file => !file.startsWith('.') && file !== 'migration_lock.toml')
.sort();
console.log('Migration status:');
console.log('=================');
if (migrations.length === 0) {
console.log('No migrations found.');
} else {
migrations.forEach(migration => {
const migrationPath = path.join(migrationsDir, migration);
const stats = fs.statSync(migrationPath);
const date = new Date(stats.birthtime).toLocaleString();
console.log(`- ${migration} (created: ${date})`);
});
}
// Show database connection status
try {
console.log('\nDatabase connection:');
console.log('===================');
execSync('npx prisma db pull --print', { stdio: 'inherit' });
} catch (error) {
console.error('Error connecting to database:', error);
}
} catch (error) {
console.error('Failed to show migration status:', error);
process.exit(1);
}
}
// Entry point
switch (command) {
case COMMANDS.CREATE:
createMigration(migrationName);
break;
case COMMANDS.APPLY:
applyMigrations();
break;
case COMMANDS.RESET:
resetDatabase();
break;
case COMMANDS.STATUS:
showStatus();
break;
default:
console.log('Usage: npm run migrate <command> [options]');
console.log('\nAvailable commands:');
console.log(` ${COMMANDS.CREATE} <name> Create a new migration`);
console.log(` ${COMMANDS.APPLY} Apply pending migrations`);
console.log(` ${COMMANDS.RESET} Reset database and apply all migrations`);
console.log(` ${COMMANDS.STATUS} Show migration status`);
}