TypeORM - use QueryBuilder for database seeding

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,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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.

Share