TypeORM - Migrations

TypeORM is an Object Relational Mapping (ORM) framework for TypeScript and JavaScript, which allows developers to manage and interact with relational databases using object-oriented programming concepts. TypeORM provides an easy-to-use API for developers to perform common database operations such as querying, creating, updating, and deleting records from a database.

It supports a wide range of databases such as MySQL, PostgreSQL, SQLite, SQL Server, Oracle, and MongoDB. It also supports various platforms such as Node.js, Browser, React Native, and Electron.

Prerequisites :-

A particular entity, or repository(Instance) must be created/edited before working with migration in TypeORM, Local DB Setup(with .env changes in backend- DB - LocalHost)

Migrations : -

Migrations are scripts that enable developers to modify the database schema, and query builder is an abstraction layer over SQL that enables developers to construct SQL queries using JavaScript or TypeScript syntax.

Migrations can be done in 2 different ways(Generation and Creation) and it comprises of method UP()and Down() which we will be discussing later in this blog.

Migration Generation :-

ts-node ./node_modules/typeorm/cli.js migration:generate -n <YourMigrationName>

This command generates a new migration file based on changes made to the entity files. It inspects the current state of the entity files and generates a new migration file that contains the SQL statements to update the database schema to match the changes made to the entities.

This process will auto generate the Indexes and Foreign Key Constraints based on the relations we define, which is a preferable approach.

Migration Create :-

typeorm migration:create -n  src/typeorm/migration/<YourMigrationName>

This command creates an empty migration file with a specified name. This command is typically used when there are no changes to the entity files but there is a need to make changes to the database schema, such as adding or modifying a database index, or changing a column data type.

In creation, we have to manually add the constraints. Up and Down Functions will have no queries residing(should be added manually).

In summary, Migration-generation is used to create a migration file that reflects changes made to the entity files, while Migration-Creation is used to create a new migration file for changes that are not related to the entity files.