Creating And Running Migrations

Creating And Running Migrations

Creating A Migration

A migration uses an installer file. The one illustrated here is app/installers/refmt_installer.php. It is used to illustrate ActiveRecord's ability to maintain several languages in a database table.

<?php
class RefmtInstaller extends AkInstaller
{
    function up_1()
    {
        $this->createTable('mono_langs', "
            id,
            lang,
            name
        ");
 
        $this->createTable('multi_langs', "
            id,
            en_name,
            fi_name,
            sv_name
        ");
    }
 
    function down_1()
    {
        $this->dropTable('mono_langs','multi_langs');
    }
}
?>

Running a migration

In a terminal window, change the directory to the top of your project. Then enter

./script/migrate Refmt install

“Refmt” is the part of the class name before “Installer”. If the tables don't exist, they will be created; if they do exist, they won't be overwritten.

The significant thing here that makes the use of this file a migration is that you may add additional up and down functions to add tables, indices, columns, etc. A down function should always undo what the corresponding up function does. ActiveRecord keeps track of where you are in your migration. The first time you do an install, up_1() will be executed. If you then do an uninstall, down_1() will be executed. Each successive install will cause the succeeding up_x() to be run (where x increments the previous up function by 1).

Let's say that you have functions up_1(), down_1(), up_2(), and down_2(). The first time you execute

./script/migrate Refmt install

function up_1() will be executed. The second time you run it, function up_2() will be executed. If you execute

./script/migrate Refmt uninstall

at this point, function down_2() will be executed. The condition of your tables should be as defined in function up_1(). You may add as many up_x() and down_x() functions as you need to, incrementing x by 1 each time.

 
creating-and-running-migrations.txt · Last modified: 2008/07/14 00:47 by 82.103.221.224