yii database migration

In the process of our development program, the structure of the database is constantly adjusted. Our developers want to ensure synchronization code and database repository. Because we can not do without the application database. For example: During the development process, we often need to add a new table, or we put into operation late in the product, you may need to add an index to a column. We have to maintain the consistency of data structures and code. If the code and the database is not synchronized, the system may not function properly. Due to this reason. yii provides a database migration tool that can keep the code and databases are synchronized. Easy rollback and update the database.

The following steps illustrate how we can use database migration during the development process:

 

  1. Tim moved to create a new task (for example, create a new table)
  2. After submission of a new migration source to the control system (e.g., SVN, GIT)
  3. Doug updated source code from source code control system and to receive a new migration
  4. Doug application migration to his local development database

Note:  Use yiic migration command, preferably switch to the specified application directory (eg cd path / to / protected ) instead of the frame in the root directory.

1. Creating Migrations create a migration

To create a new migration (eg create a news table), we run the following command:

yiic migrate create <name>

 The name parameter is required to make a very brief description (eg create_news_table) with the specified migration. As our example, since the name parameter is used as part of a PHP class name. Therefore, it should only contain letters, numbers and / or the underscore character.

yiic migrate create create_news_table

The above command will create a new file in the directory namedm101129_185401_create_news_table.php protected / migrations which contains the following initial code:

class m101129_185401_create_news_table extends CDbMigration
{
    public function up()
    {
    }
 
    public function down()
    {
        echo "m101129_185401_create_news_table does not support migration down.\n";
        return false;
    }
 
    /*
    // implement safeUp/safeDown instead if transaction is needed
    public function safeUp()
    {
    }
 
    public function safeDown()
    {
    }
    */
}

Note that, when the class name as create a migration file name format is m <timestamp> _ <name>, wherein <timestamp> refers UTC timestamp (yymmdd_hhmmss format) and <name> parameter is specified by the command.

 up () method should contain the actual database migration implementation code, and down () method is up () rollback code.

Sometimes, down () do not specify a specific code. For example, if we delete rows in the table up (), we will not be rolled back up the operation. In this case, the migration is called irreversible, meaning we can not roll back to a previous state of the database. In the generated code, up () method returns false indicates that the migration can not be restored.

Info:  Starting with version 1.1.7, if the up () or down () method returns false, indicating that the migration was canceled. Prior to version 1.1.6, an exception is thrown cancel the migration.

Examples are described in a table to create news migration.

class m101129_185401_create_news_table extends CDbMigration
{
    public function up()
    {
        $this->createTable('tbl_news', array(
            'id' => 'pk',
            'title' => 'string NOT NULL',
            'content' => 'text',
        ));
    }
 
    public function down()
    {
        $this->dropTable('tbl_news');
    }
}

CDbMigration base class provides a method for manipulating data structures and database. For example, CDbMigration :: createTable will create a database table, and CDbMigration :: insert will insert a row. These methods use CDbMigration :: getDbConnection () Gets the database connection, default returns Yii :: app () -> db

Info:  The method you may notice provided by CDbMigration database and CDbCommand very similar. In fact, they are almost identical, except CDbMigration method will print the time and method used to print some information about the parameters of the method.

2. Transactional Migrations Migration Affairs

Info:  version 1.1.7 support transaction migration.

While performing complex database migration, we usually want to make sure the entire migration success or failure, so that the database consistency and integrity. To achieve this goal, we can use transactional database.

We should clearly specify the startup operation code-related data DB affairs and affairs, such as:

class m101129_185401_create_news_table extends CDbMigration
{
    public function up()
    {
        $transaction=$this->getDbConnection()->beginTransaction();
        try
        {
            $this->createTable('tbl_news', array(
                'id' => 'pk',
                'title' => 'string NOT NULL',
                'content' => 'text',
            ));
            $transaction->commit();
        }
        catch(Exception $e)
        {
            echo "Exception: ".$e->getMessage()."\n";
            $transaction->rollback();
            return false;
        }
    }
 
    // ...similar code for down()
}

Get transaction support is an easier way is to use safeUp () method instead of up (), safeDown () instead of down (). E.g,

class m101129_185401_create_news_table extends CDbMigration
{
    public function safeUp()
    {
        $this->createTable('tbl_news', array(
            'id' => 'pk',
            'title' => 'string NOT NULL',
            'content' => 'text',
        ));
    }
 
    public function safeDown()
    {
        $this->dropTable('tbl_news');
    }
}

Yii time of the migration, it starts a database transaction and then call safeUp () or safeDown (). If any DB error safeUp () or safeDown (), will roll back the transaction to ensure database integrity.

Note:  Not all DBMS support transactions. Some database query can not be placed in the transaction. In this case, you have to use up () and down (). MySQL, some SQL statements may cause implicit commit.

3. Applying Migrations application migration

Apply all new migration available (for example, the latest local database), run the following command:

yiic migrate

This command will display all new migration list. If confirmed application migration, that it will run up () method to perform the migration, the order is executed in accordance with the class name of the timestamp value of the order.

In the application migration, the migration tool will keep records to a database table called tbl_migration. This makes the tool, you can ensure that migration is applied. If tbl_migration does not exist, the tool will automatically create it in the DB application specifies the database

Sometimes, we may need to apply only one or a few new migrations. We can use the following command:

yiic migrate up 3

This command will apply the 3 new migrations. By modifying the value of 3, it will allow us to change the number of migrated applications.

We can also use the following command to migrate to a specific version of the database:

yiic migrate to 101129_185401

In other words, we can use the migration name + time stamp section to specify the version of the database we want to migrate. If there are multiple migration such as migration and the last application specified migration. All these migrations will be applied. A first application of the last migration, and then to roll back the designated transition (to be described in a).

4. Reverting Migrations reducing migration

To restore migrate past one or more applications, we can use the following command:

yiic migrate down [step]

Optional step parameter specifies how many migrate recovery. The default value is 1, which means that the last time rollback migration.

As we mentioned earlier, not all migrations can be rolled back. Trying to roll back such a migration will throw an exception and stop the whole recovery process.

5. Redoing Migrations 

Redo the migration means first recover and then apply the specified migration. You can use the following command:

yiic migrate redo [step]

Optional step parameter specifies the number of redo migration. The default value is 1, which means redoing the last migration.

6. Showing Migration Information displays the migration information

In addition to recovery and migration applications, it can also display the new migration history and migration of applications.

yiic migrate history [limit]
yiic migrate new [limit]

Among them, the optional parameter specifies the limit migration to be displayed. If there is no specified limit, it will display all the available migration.

The first command displays the migration has been applied, and the second command displays the migration has not been applied.

7. Modifying Migration History 

Sometimes, we may have to revise immigration records, which usually occurs when there is no practical application or restore about migrating to a specific version or migrate in the development of a new migration task. We can use the following command.

yiic migrate mark 101129_185401

This command and yiic migration command is very similar, except that it can only change history table, no application migration or migration to restore the specified version.

8. Customizing Migration Command customize migration commands

There are several ways to customize the migration command.

Use Command Line Options command-line options

Migration command in the command line can use the following four options:

  • interactive: Boolean, specify whether to perform interactive mode of migration. The default is true, which means that users will be prompted when performing a specific migration. You can set to false should do a background process migration

  • migrationPath: String, specifies the directory storing all migration class files. You must specify the alias and the corresponding path must exist. If not specified, it will themigrations subdirectory under the root path using the application

  • migrationTable: String ,, specify the name of the database table to store the migration history information. Default tbl_migration. Version of the structure of the table is VARCHAR (255) primary key, apply_time integer.

  • connectionID: ID string, specified database application components. The default is 'DB'.

  • templateFile: String, specify the path to the file, served as a template to generate code for class migration. You must specify a path alias (eg application.migrations.template). If not set, an internal template will be used. In the template, marker {ClassName} will be replaced with the actual name of the migration class.

Examples are as follows

yiic migrate up --option1=value1 --option2=value2 ...

For example, if we want to migrate a forum module, the migration file is located within the module migrations directory, we can use the following command:

yiic migrate up --migrationPath=ext.forum.migrations

Configure Command Globally global configuration command

Although the command-line option allows us to configure the migration command, sometimes we may need time to configure all commands. For example, we may want to use a different table to store the migration history, or we may want to use a customized migration template. We can modify the configuration file similar to the following console application,

return array(
    ......
    'commandMap'=>array(
        'migrate'=>array(
            'class'=>'system.cli.commands.MigrateCommand',
            'migrationPath'=>'application.migrations',
            'migrationTable'=>'tbl_migration',
            'connectionID'=>'db',
            'templateFile'=>'application.migrations.template',
        ),
        ......
    ),
    ......
);

Now, if we run the migrate command, the above configuration will remain in effect without the need for each configuration.

 

 

 

 

 

Database migration using the command line .. do is console / Application

 So to change the configuration of the console config / ...

'components.db'=>[
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=test',
'username' => 'root',
'password' => '******',
]

 

  • php yii migrate --migrationPath=@vendor/amnah/yii2-user/amnah/yii2/user/migrations

Reproduced in: https: //my.oschina.net/zhepama/blog/265037

Guess you like

Origin blog.csdn.net/weixin_33940102/article/details/91927345