-
Notifications
You must be signed in to change notification settings - Fork 0
Migrations
ModularORM provides a very flexible system of table migrations. The library can automatically generate migrations for new, deleted and updated columns, migrations for JOIN tables, as well as down-migrations for all of this. Moreover, migrations work for each table separately. You can enable automatic migration or migration in a file.
Let's look at an example. Let's assume that we have a table with API keys
@Table()
@NamedTable('api_keys')
export class ApiKeys extends Module {
@Column(DefaultColumn.AUTOINCREMENT_ID)
public id!: number;
@Column(DefaultColumn.LONG_VARCHAR)
public key!: string;
@Column(DefaultColumn.DATETIME)
public expiresIn!: Date;
@Column(DefaultColumn.TEXT)
public scopes!: string;
}Now let's remove the scopes column, add the isBanned column, rename "key" and change "expiresIn"
@Table()
@NamedTable('api_keys')
export class ApiKeys extends Module {
@Column(DefaultColumn.AUTOINCREMENT_ID)
public id!: number;
@Column(DefaultColumn.LONG_VARCHAR)
@RenamedColumn("key")
public api_key!: string;
@Column({ type: ColumnType.INTEGER, index: true })
public expiresIn!: number;
@Column(DefaultColumn.BOOL_DEFAULT_FALSE)
public isBanned!: boolean;
}Now it is enough to perform 3 actions for ModularORM to create migrations and update the physical table in the database:
- Specify
migrations: truein table settings:
@Table({ migrations: true })- Select the required migration type when running ORM:
await ModularORM.getInstance().start({
// ...
migrations: 'file'
})- Restart the application
Now ModularORM will create 2 files: ModularORM_migrations.txt and ModularORM_down_migration.txt
The first file will list line by line all SQL queries for changing the physical table, and the second one will list queries for canceling the migration in case of errors.
To apply migrations, just run the application a second time. The library will check for the presence of the file "ModularORM_migrations.txt", then execute each sql query line by line and delete this file (the file with down-migrations will not be deleted)
You can also specify the type "auto", in which case the file with migrations will not be created, and all SQL queries will be executed immediately upon application startup, removing the intermediate link. But the file with down-migrations will still be created