This document explains how to use TypeORM migrations in the TradeFlow API project.
Migrations provide a way to safely manage database schema changes without losing data. This replaces the dangerous synchronize: true option which should never be used in production.
src/datasource.ts- TypeORM configuration for CLI commandssrc/entities/user.entity.ts- User entity definitionsrc/entities/invoice.entity.ts- Invoice entity definitionsrc/migrations/- Directory containing migration filessrc/migration-runner.ts- Manual migration runner for testing
# Generate a new migration
npm run migration:generate -- MigrationName
# Run all pending migrations
npm run migration:run
# Revert the last migration
npm run migration:revert
# Run migrations manually (for testing)
npm run migration:manualThe initial migration (1708665600000-InitialMigration.ts) creates:
id(UUID, primary key)publicKey(varchar, unique)email(varchar, nullable)isActive(boolean, default: true)createdAt(timestamp)updatedAt(timestamp)
id(int, primary key, auto-increment)amount(decimal 10,2)date(timestamp)customer(varchar)description(text, nullable)riskScore(int, default: 0)status(varchar, enum: Pending/Approved/High Risk/Rejected)processedAt(timestamp, default: CURRENT_TIMESTAMP)userId(uuid, foreign key to users, nullable)createdAt(timestamp)updatedAt(timestamp)
- Foreign key from
invoices.userIdtousers.id - Index on
invoices.statusfor performance
- Make entity changes - Modify entity files in
src/entities/ - Generate migration - Run
npm run migration:generate -- DescriptionOfChanges - Review migration - Check the generated migration file
- Run migration - Execute
npm run migration:run - Verify - Check that tables are created/updated correctly
TypeORM automatically creates a migrations table to track which migrations have been applied. This prevents re-running the same migration and ensures proper ordering.
synchronize: falseis set in bothdatasource.tsanddatabase.providers.ts- All schema changes must go through migrations
- Migrations are reversible with
up()anddown()methods - Foreign key constraints maintain data integrity
Configure database connection using these environment variables:
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=password
DB_DATABASE=tradeflowWhen using Docker Compose, the database will be available at localhost:5432 and migrations can be run after the container starts:
docker-compose up -d db
npm run migration:run