This project uses TypeORM for database migrations. Here's how to work with migrations:
The migration system is already configured with:
- Data source:
src/data-source.ts - Migrations directory:
src/migrations/ - TypeORM CLI configured in
package.json
Generate a migration based on entity changes:
npm run migration:generate src/migrations/MigrationNameCreate an empty migration file:
npm run migration:create src/migrations/MigrationNameApply all pending migrations:
npm run migration:runRevert the most recent migration:
npm run migration:revertView which migrations have been applied:
npm run migration:showEach migration file should follow this pattern:
import { MigrationInterface, QueryRunner } from "typeorm";
export class MigrationName1700000000000 implements MigrationInterface {
name = 'MigrationName1700000000000'
public async up(queryRunner: QueryRunner): Promise<void> {
// Migration logic here
// Example: await queryRunner.query(`CREATE TABLE "users" ("id" SERIAL PRIMARY KEY, "email" VARCHAR NOT NULL)`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
// Rollback logic here
// Example: await queryRunner.query(`DROP TABLE "users"`);
}
}- Always test migrations in a development environment first
- Include rollback logic in the
down()method - Use descriptive names for migration files
- Keep migrations small and focused on one change
- Never modify existing migrations that have been applied to production
- Use transactions for complex migrations when possible
Make sure these environment variables are set:
DB_HOST: Database hostDB_PORT: Database port (default: 5432)DB_USERNAME: Database usernameDB_PASSWORD: Database passwordDB_NAME: Database name
- Make changes to your entities
- Generate migration:
npm run migration:generate src/migrations/AddUserTable - Review the generated migration file
- Run migration:
npm run migration:run - Test your application
- If migrations fail, check the database connection in
src/data-source.ts - Ensure all entities are properly imported in the data source
- Check that the migrations directory path is correct
- Verify that the database user has sufficient permissions