Migration Structure

This is the file that is created when you run the command:

npm run migrations:create <my-migration-name>
import { MigrationInterface, QueryRunner } from 'typeorm';

export class demoMigration1660583941591 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {}

  public async down(queryRunner: QueryRunner): Promise<void> {}
}

Every time you perform a migration, you must also declare the SQL statement that can reverse what you did.

To do so, we use the following methods:

Up method: This method executes the SQL statements by running the command:

npm run migrations:run 

Down method: This method executes the SQL statements to reverse the actions of the up method.

This method is executed with the command:

npm run migrations:rollback

To create an SQL statement, you need to include this code in the up and down method.

...
    await queryRunner.query(`SQL STATEMENT`);
...

Example 1 - Create Table

Example 2 - Alter Table

Other examples

  • If you pass a field type A to type B, in the down method you must pass the field from type B to Type A (initial data type).

  • If you create a table Z, in the down method you must delete the table Z.

  • If you add a field A to a table Z, in the down method you must delete the field A in table Z.

  • If you add an index A to a table Z, in the down method you must remove the index A from table Z.

Last updated

Was this helpful?