牛骨文教育服务平台(让学习变的简单)
博文笔记

YII Framework学习教程-YII的Model-数据库操作5-数据迁移官方翻译

创建时间:2011-12-01 投稿人: 浏览次数:3664

          原文:http://www.yiiframework.com/doc/guide/1.1/en/database.migration

          译文如下,仅供参考:

 

 

Note: The database migration feature has been available since version 1.1.6.数据库迁移功能自从版本1.1.6已经可用。

Like source code, the structure of a database is evolving as we develop and maintain a database-driven application. For example, during development, we may want to add a new table; or after the application is put into production, we may realize the need of adding an index on a column. It is important to keep track of these structural database changes (called migration) like we do with our source code. If the source code and the database are out of sync, it is very likely the whole system may break. For this reason, Yii provides a database migration tool that can keep track of database migration history, apply new migrations, or revert existing ones.

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

  1. Tim creates a new migration (e.g. create a new table)
  2. Tim commits the new migration into source control system (e.g. SVN, GIT)
  3. Doug updates from source control system and receives the new migration
  4. Doug applies the migration to his local development database

Yii supports database migration via the yiic migrate command line tool. This tool supports creating new migrations, applying/reverting/redoing migrations, and showing migration history and new migrations.

In the following, we will describe how to use this tool.

在我们开发程序的过程中,数据库的结构也是不断调整的。我们的开发中要保证代码和数据库库的同步。因为我们的应用离不开数据库。例如: 在开发过程中,我们经常需要增加一个新的表,或者我们后期投入运营的产品,可能需要为某一列添加索引。我们必须保持数据结构和代码的一致性。如果代码和数据库不同步,可能整个系统将无法正常运行。出于这个原因。yii提供了一个数据库迁移工具,可以保持代码和数据库是同步。方便数据库的回滚和更新。

下面的步骤说明了我们如何能够在开发过程中使用的数据库迁移:

  1. Tim 创建一个新的迁任务(例如,创建一个新表)
  2. 提交迁移后的新的源代码到控制系统(如SVN,GIT)
  3. Doug从源代码控制系统的更新了源代码并接收新的迁移
  4. Doug应用迁移到他的本地开发数据库

Note: It"s better to use application-specific yiic (e.g. cd path/to/protected) when working withmigrate command instead of one from framework directory. 

使用yiic迁移命令,最好切换到指定的应用程序目录(e.g. cd path/to/protected)而不是在框架根目录。

1. Creating Migrations 创建迁移

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

要创建一个新的迁移(例如,创建一个新闻表),我们运行下面的命令:

yiic migrate create <name>

The required name parameter specifies a very brief description of the migration (e.g. create_news_table). As we will show in the following, the name  parameter is used as part of a PHP class name. Therefore, it should only contain letters, digits and/or underscore characters.

 name参数是必须的跟指定的迁移做非常简短的描述(例如create_news_table)。正如我们的例子,由于name参数是用来作为一个PHP类名称的一部分。因此,它应该只包含字母,数字和/或下划线字符。

yiic migrate create create_news_table

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

上面的命令将在目录protected/migrations下创建一个新的文件namedm101129_185401_create_news_table.php其中包含以下的初始代码:

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.
";
        return false;
    }
 
    /*
    // implement safeUp/safeDown instead if transaction is needed
    public function safeUp()
    {
    }
 
    public function safeDown()
    {
    }
    */
}

Notice that the class name is the same as the file name which is of the pattern m<timestamp>_<name>, where<timestamp> refers to the UTC timestamp (in the format of yymmdd_hhmmss) when the migration is created, and <name> is taken from the command"s name parameter.

注意,创建迁移时类名作为文件名的格式是m<timestamp>_<name>,其中的<timestamp>是指UTC时间戳(yymmdd_hhmmss格式)和<name>通过命令参数指定。

The up() method should contain the code implementing the actual database migration, while the down()method may contain the code reverting what is done in up().

 up()方法应该包含实际的数据库迁移的实现代码,而down()方法是up()回滚代码

Sometimes, it is impossible to implement down(). For example, if we delete table rows in up(), we will not be able to recover them in down(). In this case, the migration is called irreversible, meaning we cannot roll back to a previous state of the database. In the above generated code, the down() method returns false to indicate that the migration cannot be reverted.

有时, down()不指定具体代码。例如,如果我们在up()中删除表的行,我们将不能回滚up的操作。在这种情况下,迁移被称为不可逆的,这意味着我们不能回滚到以前的状态的数据库。在上述生成的代码,up()方法返回false表明,迁移无法恢复。

Info: Starting from version 1.1.7, if the up() or down() method returns false, all the following migrations will be canceled. Previously in version 1.1.6, one has to throw exceptions to cancel the following migrations.从版本1.1.7开始,如果 up() or down() 方法返回false,表示迁移被取消。此前1.1.6版本中,抛出异常取消迁移

As an example, let"s show the migration about creating a news table.

例子中介绍了一个创建新闻表的迁移。

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");
    }
}

The base class CDbMigration provides a set of methods for manipulating data and schema of a database. For example, CDbMigration::createTable will create a database table, while CDbMigration::insert will insert a row of data. These methods all use the database connection returned by CDbMigration::getDbConnection(), which by default returns Yii::app()->db.

基类CDbMigration提供了一套用于操纵数据和数据库的结构的方法。例如, CDbMigration::createTable将创建一个数据库表,而CDbMigration::insert将插入一行数据。这些方法都使用CDbMigration::getDbConnection()获取数据库连接,默认返回Yii::app()->db

Info: You may notice that the database methods provided by CDbMigration are very similar to those in CDbCommand. Indeed they are nearly the same except that CDbMigration methods will measure the time used by their methods and print some messages about the method parameters.您可能会注意到由CDbMigration数据库提供的方法和CDbCommand非常相似。事实上,他们几乎是相同的,除了CDbMigration方法将打印方法所用的时间和打印有关该方法的参数的一些消息

2. Transactional Migrations 事务迁移

Info: The feature of transactional migrations has been supported since version 1.1.7.版本1.1.7后支持事务迁移功能。

While performing complex DB migrations, we usually want to make sure that each migration succeed or fail as a whole so that the database maintains the consistency and integrity. In order to achieve this goal, we can exploit DB transactions.

执行复杂的数据库迁移的同时,我们通常要确保整个迁移成功或失败,从而使数据库保持一致性和完整性。为了实现这个目标,我们可以利用数据库的事务。

We could explicitly start a DB transaction and enclose the rest of the DB-related code within the transaction, like the following:

我们应该明确地指定启动DB 事务和事务相关的数据的代码的操作,例如:

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()."
";
            $transaction->rollBack();
            return false;
        }
    }
 
    // ...similar code for down()
}

However, an easier way to get transaction support is to implement the safeUp() method instead of up(), andsafeDown() instead of down(). For example,

获得事务支持一个更简单的方式是使用safeUp() 方法代替up(),safeDown() 代替down()。例如,

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");
    }
}

When Yii performs the migration, it will start a DB transaction and then call safeUp() or safeDown(). If any DB error occurs in safeUp() or safeDown(), the transaction will be rolled back, thus ensuring the database remain in a good shape.

Yii的执行迁移时,它会启动一个数据库事务,然后调用safeUp()或safeDown()。如果任何DB错误safeUp()或safeDown()时,将回滚事务,从而确保数据库完整性

Note: Not all DBMS support transactions. And some DB queries cannot be put into a transaction. In this case, you will have to implement up() and down(), instead. And for MySQL, some SQL statements may cause implicit commit.不是所有的DBMS都支持事务。一些数据库查询不能放入事务。在这种情况下,您不得不使用up() 和down()。MySQL中,一些SQL语句可能会造成隐式提交。

3. Applying Migrations 应用迁移

To apply all available new migrations (i.e., make the local database up-to-date), run the following command:

应用所有可用的新的迁移(例如, 本地数据库最新),运行以下命令:

yiic migrate

The command will show the list of all new migrations. If you confirm to apply the migrations, it will run the up()method in every new migration class, one after another, in the order of the timestamp value in the class name.

该命令将显示所有新迁移的名单。如果确认应用迁移,它将运行那些up()方法执行迁移,执行顺序是按照类名的时间戳值的顺序。

After applying a migration, the migration tool will keep a record in a database table named tbl_migration. This allows the tool to identify which migrations have been applied and which are not. If the tbl_migrationtable does not exist, the tool will automatically create it in the database specified by the db application component.

在应用迁移是,迁移工具将保存记录到名

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。