データベースマイグレーション

マイグレーションは構造化かつ整理された方法でデータベース編集を行う便利な手段です。SQL 文を手作業で編集することもできますが、それでは他の開発者に実行の必要を知らせる責任を持たなければなりません。また、本番マシンへの次のデプロイ時に変更する必要があることを追跡しなければなりません。

データベーステーブルの マイグレーション はどのマイグレーションがすでに実行済みか、アプリケーションファイルをアップデートしたときに実行しなければならないかを追跡します。$migration->current() の呼び出しで実行すべきマイグレーションを実施します。 現在のバージョンは application/Config/Migrations.php で見つけられます。

マイグレーションファイル名

それぞれのマイグレーションは番号の昇順または降順で実行されます。これはメソッドの引数に依存します。連番の付け方は2通りあります:

  • Sequential: それぞれのマイグレーションは 001 で始まる一連番号がつけられます。 それぞれの番号は3桁の番号でなければならず、番号を飛び越してはいけません。(これは CodeIgniter 3.0 より前の形式です)。
  • Timestamp: それぞれのマイグレーションは作成時のタイムスタンプを使用してナンバリングされます。YYYYMMDDHHIISS の形式です(例: 20121031100537)。これはチーム開発の環境下でナンバリングの衝突を防ぐ手助けとなります。CodeIgniter 3.0 以降で推奨される形式です。

選択した形式は application/Config/Migrations.php ファイルの $type で設定します。デフォルト設定はタイムスタンプです。

どちらのナンバリング形式を使用するにせよ、マイグレーションファイルのプレフィックスとしてその番号を使用し、続けてアンダースコアと、マイグレーション内容の説明となる名前をつけます。例:

  • 001_add_blog.php (一連番号のナンバリング)
  • 20121031100537_add_blog.php (タイムスタンプのナンバリング)

マイグレーションの作成

マイグレーションの手始めとしてブログを持つ新しいサイトをやってみましょう。すべてのマイグレーションは application/Database/Migrations/ ディレクトリに置き、20121031100537_Add_blog.php のような名前にします。

<?php

class Migration_Add_blog extends \CodeIgniter\Database\Migration {

        public function up()
        {
                $this->forge->addField(array(
                        'blog_id' => array(
                                'type' => 'INT',
                                'constraint' => 5,
                                'unsigned' => TRUE,
                                'auto_increment' => TRUE
                        ),
                        'blog_title' => array(
                                'type' => 'VARCHAR',
                                'constraint' => '100',
                        ),
                        'blog_description' => array(
                                'type' => 'TEXT',
                                'null' => TRUE,
                        ),
                ));
                $this->forge->addKey('blog_id', TRUE);
                $this->forge->createTable('blog');
        }

        public function down()
        {
                $this->forge->dropTable('blog');
        }
}

そして、application/Config/Migrations.php$currentVersion = 20121031100537; を設定します。

データベース接続とデータベースフォージクラスはそれぞれ $this->db$this->forge で使用できます。

また別の方法として、マイグレーションファイルのスケルトン生成としてコマンドライン呼び出しを使用できます。詳しくは後述をご覧ください。

$currentVersion の使用

$currentVersion 設定ではアプリケーションがどの地点にあるべきかを設定できます。 これは本番環境設定で特に便利です。アプリケーションでは、本番環境とステージングサーバが正しいスキーマで実行されることを確実にするため、現在適用するバージョンであり最新ではないバージョンに常にマイグレーションをし続けることができます。開発サーバでは、まだ本番適用の準備ができていないコードのための追加のマイグレーションを実行できます。latest() メソッドを使えば、開発マシンを常にアルファ版スキーマにすることができます。

データベースのグループ

マイグレーションはひとつのデータベースグループに対してのみ動作します。もし application/Config/Database.php に複数のグループを定義しても、それに書かれている $defaultGroup に対して動作します。異なるデータベースグループに異なるスキーマが必要になることが、きっとあるでしょう。おそらく片方はサイトの一般的な情報に使用し、他方はミッションクリティカルなデータに使われているでしょう。マイグレーションは $DBGroup プロパティで指定した適切なグループに対してのみ動作させるようにできます。この名前はデータベースグループに完全に一致させなければいけません:

class Migration_Add_blog extends \CodeIgniter\Database\Migration
{
  protected $DBGroup = 'alternate_db_group';

  public function up() { . . . }

  public function down() { . . . }
}

名前空間

The migration library will automatically scan all namespaces you have defined within application/Config/Autoload.php and its $psr4 property for matching directory names. It will include all migrations it finds.

For example, assume that we have the the following namespaces defined in our Autoload configuration file:

$psr4 = [
        'App' => APPPATH,
        'MyCompany' => ROOTPATH.'MyCompany'
];

This will look for any migrations located at both APPPATH/Database/Migrations and ROOTPATH/Database/Migrations. This makes it simple to include migrations in your re-usable, modular code suites.

Usage Example

In this example some simple code is placed in application/controllers/Migrate.php to update the schema:

<?php

class Migrate extends CI_Controller
{

        public function index()
        {
                $migrate = \Config\Services::migrations();

                try
                {
                  $migrate->current();
                }
                catch (\Exception $e)
                {
                  // Do something with the error here...
                }
        }

}

Commnand-Line Tools

CodeIgniter ships with several commands that are available from the command line to help you work with migrations. These tools are not required to use migrations but might make things easier for those of you that wish to use them. The tools primarily provide access to the same methods that are available within the MigrationRunner class.

latest

Migrates all database groups to the latest available migrations:

> php ci.php migrate

current

Migrates all database groups to match the version set in $currentVersion. This will migrate both up and down as needed to match the specified version:

> php ci.php migrate:current

version

Migrates all database groups to the specified version. If no version is provided, you will be prompted for the version.

// Asks you for the version...
> php ci.php migrate:version
> Version:

// Sequential
> php ci.php migrate:version 007

// Timestamp
> php ci.php migrate:version 20161426211300

rollback

Rolls back all migrations, taking all database groups to a blank slate, effectively migration 0:

> php ci.php migrate:rollback

refresh

Refreshes the database state by first rolling back all migrations, and then migrating to the latest version:

> php ci.php migrate:refresh

status

Displays a list of all migrations and the date and time they were ran, or '--' if they have not be ran:

> php ci.php migrate:status
Filename                              Migrated On
20150101101500_First_migration.php    2016-04-25 04:44:22

create

Creates a skeleton migration file in application/Database/Migrations using the timestamp format:

> php ci.php migrate:create [filename]

Migration Preferences

The following is a table of all the config options for migrations, available in application/Config/Migrations.php.

Preference Default Options Description
enabled FALSE TRUE / FALSE Enable or disable migrations.
path 'Database/Migrations/' None The path to your migrations folder.
currentVersion 0 None The current version your database should use.
table migrations None The table name for storing the schema version number.
type 'timestamp' 'timestamp' / 'sequential' The type of numeric identifier used to name migration files.

クラスリファレンス

class CodeIgniterDatabaseMigrationRunner
current()
戻り値:TRUE if no migrations are found, current version string on success, FALSE on failure
戻り値の型:mixed

Migrates up to the current version (whatever is set for $currentVersion in application/Config/Migrations.php).

findMigrations()
戻り値:An array of migration files
戻り値の型:array

An array of migration filenames are returned that are found in the path property.

latest()
戻り値:Current version string on success, FALSE on failure
戻り値の型:mixed

This works much the same way as current() but instead of looking for the $currentVersion the Migration class will use the very newest migration found in the filesystem.

version($target_version)
パラメータ:
  • $target_version (mixed) -- Migration version to process
戻り値:

TRUE if no migrations are found, current version string on success, FALSE on failure

戻り値の型:

mixed

Version can be used to roll back changes or step forwards programmatically to specific versions. It works just like current() but ignores $currentVersion.

$migration->version(5);
setPath($path)
パラメータ:
  • $path (string) -- The directory where migration files can be found.
戻り値:

The current MigrationRunner instance

戻り値の型:

CodeIgniterDatabaseMigrationRunner

Sets the path the library should look for migration files:

$migration->setPath($path)
          ->latest();