TypeORM - use QueryBuilder for database seeding

TypeORM - use QueryBuilder for database seeding

TypeORM is a Object Relation Mapping library for TypeScript that allows for abstraction of your database operations in a clean way. It depicts tables as entity classes, provides for automatic synchronization with the database and supports migrations.

While most entity changes (data type, column names, etc) are handled effectively by generated migrations, database seeding using TypeORM can be achieved using custom migrations.

In the official documentation for migrations, the examples show the use of raw queries and QueryRunner API to create migrations, I noticed that the QueryRunner instance also exposes the createQueryBuilder() method through the connection parameter. Therefore, you can use the same API that you would query the database from your application code to write the migration queries as well.

For instance,

export class seedTable1589221559012 implements MigrationInterface {

  public async up(queryRunner: QueryRunner): Promise<any> {
    await queryRunner.connection
      .createQueryBuilder()
      .insert()
      .into(<Entity>)
      .values([
        {
          id: 1,
          column1: 'abc',
          column2: 123
        },
        {
          id: 2,
          column1: 'def',
          column2: 456
        }
      ])
      .execute();
  }

  public async down(queryRunner: QueryRunner): Promise<any> {
    await queryRunner.connection
      .createQueryBuilder()
      .delete()
      .from(<Entity>)
      .where('id IN (0, 1)')
      .execute();
  }

}

This could help avoid having to write raw SQLs and enable type checking while inserting data.