Dump current database state to Yii migration

There’s a wonderful extension to Yii 1.x, called database-command, written by the one and only schmunk, which allows you to quickly and easily generate any set of CDbMigrationCommands (actually, entire single migration code) based on current database schema.

This isn’t, of course, the only one out there. There are some others. But I like this one the most, mainly for flexibility (may parameters to suit generated migration file to your needs). However, if this is your first approach to using custom yiic commands, you may get a little bit confused. This article should help you.

Note, that this command covers only up migrations. You must write down migrations yourself.

To use it schmunk‘s command:

  1. Get the newest version from GitHub and put it’s contents into /protected/commands folder (create one, if it does not exist). Note, that you need to put contents as is (without subfolder for this particular command), which is contrary to what we do for example for extensions.
  2. Rename EDatabaseCommand.php file (and class inside) to DatabaseCommand.php, if you want to use yiic database command (as suggested in docs). Without this fix, you’ll have to use yiic edatabase command, as there’s slight inconsistency between docs and the code (at least in the newest version, as of writing this; maybe schmunk is going to fix this).
  3. Having this, navigate back to protected folder in your console and execute yiic database dump migration_name --prefix=table_name.

This will create a migration protected/runtime/migration_name.php file with proper timestamp in the beginning of file name, filled with series of CDbMigration commands to recreate your database schema. Visit “Usage” section in the docs to read more about customizing this command.

More about yiic custom commands can be found in Yii 1.x docs.

Leave a Reply