Yii 2 Migration

[size="6"]Yii 2 Migration v2[/size]

With this extension all your migrations can be generated automatically.

[size="5"]Typical use case scenario[/size]

This huge DB table on your local machine is finally polished and ready to be moved to production environment.

Now instead of writing the migration class down you can use this extension. Simply install it by adding

"bizley/migration": "*"

in the require section of your composer.json file and run composer update.

Alternatively for the same effect you can just run

composer require bizley/migration

Now add some basic configuration (preferably in the console config file):

'components' => [

    // ...


'controllerMap' => [

    'migration' => [

        'class' => 'bizley\migration\controllers\MigrationController',



And you are ready to go (fortunately it needs to be done only once).

In the console run

php yii migration/create table_name --fixHistory=1

and you can find the migration file for this table_name table in your @app/migrations folder. In addition your local migration history table has been updated with this migration entry (fixHistory parameter).

Now you can copy this migration file to your production environment and run there php yii migrate/up to apply it.

Few days later you add one additional column to the same table. And again Yii 2 Migration v2 can help.

In the console run

php yii migration/update table_name --fixHistory=1

and you can find another migration file for the table_name table in your @app/migrations folder but now it only contains methods that modifies table instead of creating it. (Local migration history table has been again updated with this migration entry).

To make both environments even again copy new migration file and run there php yii migrate/up to apply it.

[size="5"]Migration extension can generate creating and updating migrations[/size]

  • Supports databases that are supported by Yii 2 core: CUBRID, MS SQL Server, MySQL, Oracle, PostgreSQL and SQLite.

  • Scans migration history to gather all previously applied changes and create virtual table schema that can be compared with the real one.

  • Generates general schema migrations or currently-used-DB-specific ones.

  • Can generate migrations for many tables at once.

  • Can update migration history table when generating the file.

  • Can show differences between current table structure and the one saved in migration files instead of generating migration.

What is not supported (unfortunately)

  • DB indexes (except unique indexes),

  • whole table comments (column comments are supported),

  • ON UPDATE and ON DELETE actions for foreign keys.

[size="6"]For all available parameters go to the GitHub repo:


Migration v2.1

  • New actions list and create-all added (thanks to thyseus),

  • New action update-all added,

  • Namespaced migrations are properly extracted now,

  • Missing migration history file error is now properly handled.

Migration v2.1.1

New option added: skipMigrations

List of migrations from the history table that should be skipped during the update process. (default [])

Here you can place migrations containing actions that can not be covered by extractor i.e. when there is migration setting the RBAC hierarchy with authManager component. Such actions should be kept in separated migration and placed on this list to prevent them from being run during the extraction process.

Great work!

Just want to mention, though, that if you’ve developed a huge database without thinking about migrations, you are definitely doing it wrong!

But it’s great that this extension exist so that you can correct your erroneous ways in an elegant fashion!

Cheers! :)

I guess it happens quite often, especially when you start with database model to generate tables ;)

1 Like

Migration 2.1.2

  • fixed bug with argument order in one of the methods,

  • proper handling of composite primary keys,

Note about renaming

When you rename table or column remember to generate appropriate migration manually otherwise this extension will not generate updating migration (in case of the table) or will generate migration with command to drop original column and add renamed one (in case of the column). This is happening because yii2-migration can only compare two states of the table without the knowledge of how one state turned into another. And while the very result of migration renaming the column and the one dropping it and adding another is the same in terms of structure, the latter makes you lose data.

Once you add renaming migration to the history it’s being tracked by the extension.

[size="4"]Migration 2.3.0 has been released[/size]

Package has been rewritten for more object-oriented approach.

  • Minimum Yii version is raised up to 2.0.11.

  • Maximum Yii version is set to lower than 2.1.0.

  • Extractor class is gone.

  • Multiple table structure classes have been added.

  • PHPUnit tests (with MySQL specific tests) have been added.

  • Default value of generalSchema property is now 1.

New features:

  • TINYINT and JSON support added (works only for Yii 2.0.14 and newer).

  • Non-unique indexes tracking added (works only for Yii 2.0.13 and newer).

  • ON DELETE and ON UPDATE options tracking for foreign keys added (works only for Yii 2.0.13 and newer).

  • Migration history table is automatically skipped when running create-all and update-all actions.

Migration 3.1.0 and 2.4.0 has been released.

  • Tests structure has been updated for easier DBMS switching
  • Added tests for PostgreSQL and SQLite
  • Added warning for unsupported SQLite migration commands
  • Fixed bug with schema type map missing when loading PostgreSQL schema
  • Added fallback for SQLite primary key detection
  • Schema type is now passed to TableColumn and TableChange
  • Changed the way column length is compared
  • Column length is now present only for DBMS supporting it
  • Updated Travis config for MySQL explicit_defaults_for_timestamp setting

I haven’t updated this topic for some time so here is quick summary what happened with the package since 2.3.0:

  • Extension has been split to 3.x and 2.x branches
  • 3.x requires PHP >=7.1.0 and Yii >=
  • 2.x requires PHP <7.1.0
  • Several bugs have been fixed
  • Travis service has been added for automatic tests
  • Controller returns error codes now
1 Like

Migration version 3.6.0 and 2.9.0 has been released.

What happened since last entry in this topic?

  • Option excludeTables has been added to exclude selected tables from scanning while running create-all and update-all actions. Migration history table is added to excluded tables by default.
  • upsert() method has been added in dummy Migration file to properly silence it while scanning migrations.
  • Some code style has been updated.
  • Deprecated method removeMigrationTable() has been removed.
  • Extracting column from migration with column data provided in form different than ColumnSchemaBuilder instance throws exception from now on.
  • Default column value accepts empty strings now.
  • Default column value accepts arrays now.
  • Unique indexes are not triggering unnecessary updates from now on.
  • Creating migrations for more than one table now forces the order in which they are created based on the foreign key dependencies. When tables are cross-referenced additional special foreign key migration is added at the end of the whole process.
  • New config option templateFileForeignKey - template file for generating new foreign keys migrations (default @bizley/migration/views/create_fk_migration.php ).
    migrationPath and migrationNamespace properties now can also be arrays.
  • Column size different than DBMS’ default is now respected and rendered in case of generalSchema set to 1 .
  • after() and first() calls are now rendered.
1 Like

Migration version 4.0.0 RC1 has been released.

  • Code has been refactored.
  • Support for v2 and v3 is dropped (unless serious bug is reported).
  • Updater can now arrange tables in proper order and generate postponed foreign keys (like Generator).
  • Updating migrations are now properly generated with contents of down() method.
  • Code coverage 100%.
  • PHPStan level 8 tested.
  • See Migrating to version 4.0 for migrating guide.

Stable version is scheduled for release May 1, 2020 (unless some bugs still will be there).

Please test it and let me know if anything is wrong :wink:

v4.2.0 is released - what is new since 4.0.0 rc1?

  • Added comparing foreign keys triggers ON UPDATE, ON DELETE.
  • Added experimental mode (-ex=1) that allows to use raw SQL column definitions for updater.
  • Ensured MySQL 8 compatibility.
  • Yii’s autoloader is not required to be pre-wired to an app anymore.
  • Added fileMode option to set the file permissions for generated migrations.
  • Added fileOwnership option to set the file ownership for generated migrations.
  • Fixed some bugs, added some tests.

v4.3.1 is released - what is new since 4.2.0?

  • When multiple migrations are generated they are not saved with additional _n_ stamp (when n is the number of the next migration) anymore. Instead they are saved with just the timestamp that is not repeated for other migrations in the batch. Thanks to that it is safe to run migrate/mark, migrate/to, and similar Yii commands with such migrations. In case there are possible timestamp collisions with existing migrations user will get a warning first.
  • Added leeway (lw) option to add seconds to the starting timestamp for migrations generation.
  • Fixed issue with foreign key autoindex generated for MySQL update migrations comparison.
  • Fixed order in which updating statements are rendered in the migration.
  • Used safeUp() instead of up() and safeDown() instead of down() in the migration template to match changes in default Yii behavior.

v4.4.0 released

Added new action sql allowing to extract SQL statements from the given migration file. Usage examples:

  • yii migration/sql migration_name
  • yii migration/sql migration_name up
  • yii migration/sql migration_name down
1 Like