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
#
The Commands#
Generating Migrations AutomaticallyUsually, 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.
#
Run the migrations#
Revert the last migration#
A Complete Example 1. Create a new User
entity.
2. Make the migration file.
A new file xxx-migration.ts
appears in src/directory
.
3. Run the migration.
4. Add new columns to the entity.
5. Generate another migration file.
Another file xxx-migration.ts
appears in src/directory
.
6. Run the migration.
synchronize
and dropSchema
options#
The These two options are particularly useful for testing.
synchronize
- Indicates if database schema should be auto created on every application launch.dropSchema
- Drops the schema each time connection is being established.
Using the synchronize
option for production is not recommended as you could loose data by mistake.
#
AdvancedThe TypeORM documentation gives more details on how to write migrations.