Search code examples
mysqlnode.jsexpresstypeorm

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


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);
  }
}

Solution

  • 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.