0
0
NestJSframework~10 mins

Migrations in NestJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Migrations
Write Migration Script
Run Migration Command
Migration Tool Reads Script
Apply Changes to Database
Update Migration History Table
Migration Complete
This flow shows how a migration script is written, run, applied to the database, and recorded to keep track of changes.
Execution Sample
NestJS
import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddUsersTable1680000000000 implements MigrationInterface {
  async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(100));`);
  }
  async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE users;`);
  }
}
This migration creates a 'users' table when applied and removes it when rolled back.
Execution Table
StepActionQueryRunner MethodDatabase ChangeMigration History Update
1Start migrationN/ANo change yetNo update
2Run up()queryRunner.query()Create 'users' tableRecord migration as applied
3Migration completeN/A'users' table existsMigration history updated
4Run down() to rollbackqueryRunner.query()Drop 'users' tableRemove migration record
5Rollback completeN/A'users' table removedMigration history updated
6ExitN/ADatabase matches migration stateMigration tracking consistent
💡 Migration process ends after applying or rolling back changes and updating history.
Variable Tracker
VariableStartAfter Step 2After Step 4Final
Database SchemaEmptyHas 'users' tableNo 'users' tableMatches migration state
Migration HistoryEmptyContains AddUsersTable recordEmptyConsistent with schema
Key Moments - 2 Insights
Why do we need both up() and down() methods in a migration?
The up() method applies changes, while down() reverts them. This allows safe rollbacks if needed, as shown in steps 2 and 4 of the execution_table.
What happens if the migration history is not updated after applying changes?
Without updating migration history (step 3), the system won't know the migration ran, risking repeated runs or conflicts.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what database change happens at step 2?
ADrop 'users' table
BNo change
CCreate 'users' table
DUpdate migration history only
💡 Hint
Refer to the 'Database Change' column in step 2 of the execution_table.
At which step is the migration recorded as applied?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Check the 'Migration History Update' column for when the migration is recorded.
If the down() method is not implemented, what impact is seen in the execution_table?
AStep 4 would fail to drop the table
BStep 2 would not create the table
CMigration history would not update at step 3
DNo impact, migration runs normally
💡 Hint
Look at step 4 where down() runs queryRunner.query() to drop the table.
Concept Snapshot
Migrations in NestJS with TypeORM:
- Use MigrationInterface with up() and down() methods
- up() applies DB changes (e.g., create table)
- down() reverts changes (e.g., drop table)
- Run migrations via CLI to update DB and migration history
- Keeps DB schema in sync and allows safe rollbacks
Full Transcript
Migrations in NestJS help manage database changes safely. You write a migration class with up() to apply changes and down() to undo them. When you run the migration command, the system executes up(), updates the database schema, and records the migration in a history table. This history prevents running the same migration twice. If needed, you can rollback by running down(), which reverts the changes and updates the history. This process keeps your database structure consistent with your code. The execution table shows each step: starting migration, applying changes, updating history, and rolling back if necessary. Variables like the database schema and migration history change accordingly. Remember, both up() and down() are important for safe migrations.