TypeORM - How to create new table and run migration automatically in production mode?

Viewed 18082

I would like to create new table in MySQL and run TypeORM migration automatically when application running in production mode.

Note: This new table is not created prior starting of application in production mode.

According to Migration Documentation, it need to use typeorm migration:run command to run migration.

Due to my new table only created when application called CreateNewTableTimeStamp(inputTableName).up, at this point it will trigger to create new table into my database.

But I found no solution how to do this migration automatically, since it is impossible for me to run typeorm migration:run manually each time application called this method to create new table.

After this table is created, I will write new data into this new table afterwards.

Could anyone assist on this issue?

Thanks.

My New Table Code:

class CreateNewTableTimeStamp implements MigrationInterface  {

  tableName: string;

  constructor (inputTableName: string) {
    this.tableName = inputTableName
  }

  async up(queryRunner: QueryRunner): Promise<any> {
    await queryRunner.createTable(new Table({
          name: this.tableName,
          columns: [
              {
                  name: "id",
                  type: "int",
                  isPrimary: true
              },
              {
                  name: "email",
                  type: "varchar",
              }
          ]
      }), true)
  }

  async down(queryRunner: QueryRunner): Promise<any> {
    const table = await queryRunner.getTable(this.tableName);
    await queryRunner.dropTable(this.tableName);
  }
}
3 Answers

For people wanting to run migrations for the purpose of Testing: NOT in production environment.

import {
  createConnection,
  ConnectionOptions,
  Connection,
} from 'typeorm';

import { YourEntity } from 'path/to/your/entity.ts';

const testConfig: ConnectionOptions = {
  type: 'mongodb',
  url: 'mongodb://localhost:27017',
  database: 'test',
  useUnifiedTopology: true,
  entities: [YourEntity],
  synchronize: true,
  migrations: ['migrations/*YourMigrations.ts'],
};

let connection: Connection;

connection = await createConnection({ ...testConfig });
await connection.synchronize(true);

await connection.runMigrations({
 transaction: 'all',
});

Run using:

node -r ts-node/register ./path/to/migrations.ts

or

node ./path/to/compiled/migrations.js

As mentioned by @zenbeni in the comment, it is not recommended to running migrations from your server code, as the migration should always be immutable and replayed.

Therefore, I would change my design not to do migrations from my server code.

Run

yarn typeorm migration:create -n users(table_name)

Table code example:

   import { MigrationInterface, QueryRunner, Table } from 'typeorm';

export class createUsers1585025619325 implements MigrationInterface {
  private table = new Table({
    name: 'users',
    columns: [
      {
        name: 'id',
        type: 'integer',
        isPrimary: true,
        isGenerated: true, // Auto-increment
        generationStrategy: 'increment',
      },
      {
        name: 'email',
        type: 'varchar',
        length: '255',
        isUnique: true,
        isNullable: false,
      },
      {
        name: 'created_at',
        type: 'timestamptz',
        isNullable: false,
        default: 'now()',
      },
      {
        name: 'updated_at',
        type: 'timestamptz',
        isNullable: false,
        default: 'now()',
      },
    ],
  });

  public async up(queryRunner: QueryRunner): Promise<any> {
    await queryRunner.createTable(this.table);
  }
  public async down(queryRunner: QueryRunner): Promise<any> {
    await queryRunner.dropTable(this.table);
  }
}

Run created migrations with:

yarn typeorm migration:run
Related