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.
Migrations 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
If 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.
You can use it via CLI:
migration:down commands you can specify
-o) options to run only a subset of migrations:
To run TS migration files, you will need to enable
useTsNodeflag in your
Or 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
In some cases you might want to control the transaction context yourself:
If 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.
There 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.