Generar y Ejecutar Migraciones
Database migrations are a way of propagating changes you make to your entities into your database schema. The changes you make to your models (adding a field, deleting an entity, etc.) do not automatically modify your database. You have to do it yourself.
You have two options: update the database schema manually (using database software, for example) or run migrations.
Migrations are a programmatic technique for updating or reverting a database schema in a predictable and repeatable way. They are defined with classes, each of which has an up
method and a down
method. The first one contains SQL queries to update the database schema to reflect the new models. The second contains SQL queries to revert the changes made by the up
method.
Theses classes are located in separate files in the src/migrations
directory.
Example of a migration file
import { MigrationInterface, QueryRunner } from 'typeorm';
export class PostRefactoringTIMESTAMP implements MigrationInterface {
async up(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(`ALTER TABLE "post" RENAME COLUMN "title" TO "name"`);
}
async down(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(`ALTER TABLE "post" RENAME COLUMN "name" TO "title"`); // reverts things made in "up" method
}
}
The Commands
Generating Migrations Automatically
Usually, you do not need to write migrations manually. TypeORM offers a powerful feature to generate your migration files based on the changes you make to your entities.
npm run makemigrations
Run the migrations
npm run migrations
Revert the last migration
npm run revertmigration
A Complete Example
1. Create a new User
entity.
import { Entity, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
}
2. Make the migration file.
npm run makemigrations