run-migrations.ts
1 /* eslint-disable no-console */ 2 3 import { Sequelize } from 'sequelize'; 4 import { Umzug, SequelizeStorage } from 'umzug'; 5 import getSchema from '../src/utils/getSchema'; 6 7 export async function runMigrations(): Promise<void> { 8 const connectionString = process.env.POSTGRES_CONNECTION_STRING; 9 if (!connectionString) { 10 throw new Error( 11 "'POSTGRES_CONNECTION_STRING' environment variable is missing.", 12 ); 13 } 14 15 const sequelize = new Sequelize(connectionString, { 16 dialect: 'postgres', 17 logging: false, 18 define: { 19 underscored: true, 20 }, 21 }); 22 23 const schema = getSchema(); 24 25 await sequelize.query(`CREATE SCHEMA IF NOT EXISTS "${schema}"`); 26 27 const migrator = new Umzug({ 28 migrations: { 29 glob: './dist/src/db/migrations/*.js', // Migrations must be built before running. 30 }, 31 context: sequelize, 32 storage: new SequelizeStorage({ 33 sequelize, 34 schema, 35 tableName: 'sequelize_meta', 36 }), 37 logger: console, 38 }); 39 40 try { 41 const migrations = await migrator.up(); 42 43 if (migrations.length > 0) { 44 const appliedNames = migrations.map((m) => m.name).join(', '); 45 console.info( 46 `✅ Applied ${migrations.length} migration${migrations.length > 1 ? 's' : ''}:\n - ${appliedNames.split(', ').join('\n - ')}`, 47 ); 48 } else { 49 console.info( 50 'No migrations were applied. The database is already up-to-date. If you expected migrations to be applied, ensure that you run "npm run build" before starting the server.', 51 ); 52 } 53 } finally { 54 sequelize.close(); 55 } 56 } 57 58 runMigrations().catch((error) => { 59 console.error(`❌ Migration error: ${error.message}`, { 60 stack: error.stack, 61 cause: (error as any).cause, 62 }); 63 64 process.exitCode = 1; 65 });