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

public async up(queryRunner: QueryRunner): Promise<void> {
  await queryRunner.query(
    `CREATE TABLE "public"."user" ("id" uuid NOT NULL uuid_generate_v4(), "email" character varying NOT NULL, "created_at" TIMESTAMP NOT NULL DEFAULT now(), "updated_at" TIMESTAMP NOT NULL DEFAULT now(), "deleted_at" TIMESTAMP , CONSTRAINT "PK_a7bc321b7d03b91d2ab32258321" PRIMARY KEY ("id"))`
  );
}
public async down(queryRunner: QueryRunner): Promise<void> {
  await queryRunner.query(
    `DROP TABLE "public"."user"`
  );
}

If you are using or will use SoftDelete, remember to include in your migration the field deleted_at with TIMESTAMP type.

Example 2 - Alter Table

public async up(queryRunner: QueryRunner): Promise<void> {
  await queryRunner.query(
    `ALTER TABLE "public"."user" ADD COLUMN deleted_at TIMESTAMP`
  );
}
public async down(queryRunner: QueryRunner): Promise<void> {
  await queryRunner.query(
    `ALTER TABLE "public"."user" DROP COLUMN deleted_at`
  );
}

Remember to make the correct SQL statement to revert the changes you make with the up method.

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.

If you create a new table in the database or add a new field to a table, you need to create an .entity.ts file or add the field to the entity you modify.

Last updated