Migrations

It's time to apply this mapping to the database with a versioning system.

When we map an entity to the database, we can run a command that will generate an SQL file to create the corresponding table. This file is called a migration. When we make any changes to this entity, new migrations can be generated to reflect these changes. They are a great versioning tool for the changes we make to our database schema, kind of like Git.

To deal with migrations, TypeORM requires a Data Source. We will create one in database -> data-source with the following

export default new DataSource({
  type: 'postgres',
  username: 'postgres',
  password: 'pass123',
  host: 'localhost',
  port: 5432,
  database: 'postgres',
  entities: ['dist/domain/**/*.entity.js'],
  migrations: ['dist/database/migrations/*.js'],
});

Aside from the database credentials, it must also hold the path to the already compiled entities and migrations. They are required for, respectively, generating and running the migrations.

However, once again we are exposing our credentials, and also duplicating data. As was said already, these matters will soon be addressed in the Configuration section.

Before we actually use migrations, let's first go to the package.json file and insert some scripts that will make our lives a bit easier. Inside it, at the end of the scripts object, let's add the following scripts

"migration:create": "yarn typeorm migration:create",
"premigration:generate": "yarn build",
"migration:generate": "yarn typeorm migration:generate -d dist/database/data-source -p",
"premigration:run": "yarn build",
"migration:run": "yarn typeorm migration:run -d dist/database/data-source",
"migration:revert": "yarn typeorm migration:revert -d dist/database/data-source"

This is how these scripts help us

  • Call the TypeORM CLI to manage migrations

  • pre scripts to automatically build when necessary

  • -d directive is mandatory for the data source path

  • -p flag makes migrations better formatted (pretty)

We can then use these commands to manage our migrations in a less verbose way, like this.

Generate a migration

yarn migration:generate src/database/migrations/name-here

A recent change in TypeORM makes it necessary to include the full path when generating a migration and not just its name, unfortunately.

Run pending migrations

yarn migration:run

Revert the last migration

yarn migration:revert

Now, generate and run the migration create-user and we can proceed.

Commit - Creating a data source and generating the first migration

Last updated