Migrations
MikroORM has integrated support for migrations via umzug. It allows you to generate migrations with current schema differences.
By default, each migration will be all executed inside a transaction, and all of them will be wrapped in one master transaction, so if one of them fails, everything will be rolled back.
#
Migration classMigrations are classes that extend Migration abstract class:
To support undoing those changed, you can implement the down
method, which throws an error by default.
Migrations are by default wrapped in a transaction. You can override this behaviour on
per migration basis by implementing the isTransactional(): boolean
method.
Configuration
object and driver instance are available in the Migration
class context.
You can execute queries in the migration via Migration.execute()
method, which
will run queries in the same transaction as the rest of the migration. The
Migration.addSql()
method also accepts instances of knex. Knex instance can be
accessed via Migration.getKnex()
;
#
Initial migrationIf you want to start using migrations, and you already have the schema generated, you can do so by creating so called initial migration:
Initial migration can be created only if there are no migrations previously generated or executed.
This will create the initial migration, containing the schema dump from
schema:create
command. The migration will be automatically marked as executed.
#
Configuration#
Using via CLIYou can use it via CLI:
For migration:up
and migration:down
commands you can specify --from
(-f
), --to
(-t
)
and --only
(-o
) options to run only a subset of migrations:
To run TS migration files, you will need to enable
useTsNode
flag in yourpackage.json
.
#
Using the Migrator programmaticallyOr you can create a simple script where you initialize MikroORM like this:
Then run this script via ts-node
(or compile it to plain JS and use node
):
#
Providing transaction contextIn some cases you might want to control the transaction context yourself:
#
Importing migrations staticallyIf you do not want to dynamically import a folder (e.g. when bundling your code with webpack) you can import migrations directly.
With the help of (webpacks context module api)[https://webpack.js.org/guides/dependency-management/#context-module-api] we can dynamically import the migrations making it possible to import all files in a folder.
#
Limitations#
MySQLThere is no way to rollback DDL changes in MySQL. An implicit commit is forced for those queries automatically, so transactions are not working as expected.