Migrations with TypeORM in NestJs
Migrations with TypeORM in NestJs
Why Do We Need Migrations in NestJs?
NestJs provides an auto-sync feature that automatically updates the database when entity changes occur. Given this, you might wonder why migrations are necessary.
The reason is that while auto-sync can be convenient, it can become risky in production environments. When your application is live and contains actual data, direct modifications to the database could lead to issues. This is why relying on synchronization in production is considered unsafe.
Advantages of Using Migrations
- You can control when migrations are applied.
- Reduces the risk of errors in production environments.
- Migration files can be automatically generated from entity changes, so you don’t need to manually write them.
Disadvantages of Migrations
- You need to generate and run migration files every time you make changes to your entities.
Example
Suppose you have an entity named Student:
Now, if you want to rename the name column to student_name, you would create a migration file with the following SQL query:
TypeORM allows you to store such queries and execute them later to modify the database. This process is known as migrations.
How to Create New Migrations
Before creating migrations, you need to configure your TypeORM settings like this:
- Disable Auto Sync: Set
"synchronize": falseto disable automatic syncing. - Specify Migration Path: Define where your migration files will be stored:
"cli": { "migrationsDir": "src/migrations" }. - Add TypeORM Script: Update your
package.jsonwith a TypeORM script:
Creating a New Migration File
After configuring TypeORM, you can create a new migration file with the command:
This generates a new file in the src/migrations folder, which looks like this:
The up method is where you write new SQL queries for changes, while the down method is used to revert them. For example, to add a new status column to the students table, you'd write:
Running Migrations
To run the migration, use the command:
This will execute the file and modify the table as specified.
Automatically Generating Migrations
Instead of writing queries for every change, TypeORM allows you to generate migration files automatically from entity changes:
This will detect changes that are not yet in the database and generate migration files to update the schema accordingly.
Conclusion
Migrations are particularly useful for live applications. For instance, if you introduce a new relationship in your entities and synchronization is enabled, data mismatches on the server might cause errors during deployment. As we've seen, migrations provide a safe and structured approach to updating database schemas.
Comments
Post a Comment