Implementing database migrations with TypeORM in Nest.js primarily involves the following steps:
1. Configure the TypeORM Module
First, make sure you have installed the @nestjs/typeorm and typeorm packages.
Next, configure the TypeORM module in your Nest.js project. You can import TypeOrmModule and configure the database connection using the forRoot method within the root module (typically AppModule).
typescriptimport { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [ TypeOrmModule.forRoot({ type: 'postgres', // Database type host: 'localhost', port: 5432, username: 'user', password: 'pass', database: 'test', entities: [__dirname + '/**/*.entity{.ts,.js}'], synchronize: false, // Set to false in production environments }), ], }) export class AppModule {}
2. Create Migration Scripts
You can either manually create migration scripts or generate them using the TypeORM CLI tool.
To utilize the CLI tool, add an ormconfig.json file to your project's root directory, containing the same database connection configuration.
json{ "type": "postgres", "host": "localhost", "port": 5432, "username": "user", "password": "pass", "database": "test", "entities": ["dist/**/*.entity.js"], "migrationsTableName": "migration", "migrations": ["dist/migration/*.js"], "cli": { "migrationsDir": "src/migration" } }
Then, run the following command to generate a migration file:
bashnpx typeorm migration:create -n MigrationName
3. Write Migration Logic
In the generated migration file, you need to write up and down methods, which define how to apply and revert the migration, respectively. For example:
typescriptimport { MigrationInterface, QueryRunner } from 'typeorm'; export class MigrationName implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(`CREATE TABLE "user" (...);`); } public async down(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(`DROP TABLE "user";`); } }
4. Run Migrations
To apply migrations, you can use the TypeORM CLI tool:
bashnpx typeorm migration:run
To revert the most recent migration:
bashnpx typeorm migration:revert
Example
For instance, suppose we need to add a new column age to the user table. First, generate a migration file, then add the new column in the up method and remove it in the down method.
typescriptimport { MigrationInterface, QueryRunner } from 'typeorm'; export class AddUserAge1600000000000 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(`ALTER TABLE "user" ADD "age" int;`); } public async down(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(`ALTER TABLE "user" DROP COLUMN "age";`); } }
Then run the migration to apply this change.
This completes the basic process of implementing database migrations with TypeORM in a Nest.js project. These steps ensure version control and change management for the database structure.