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

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

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

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

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

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

The desired style may be selected using the $type setting in your app/Config/Migrations.php file. デフォルト設定はタイムスタンプです。

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

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

マイグレーションの作成

マイグレーションの手始めとしてブログを持つ新しいサイトをやってみましょう。All migrations go in the app/Database/Migrations/ directory and have names such as 20121031100537_Add_blog.php.

<?php namespace App\Database\Migrations;

class Migration_Add_blog extends \CodeIgniter\Database\Migration {

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

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

Then in app/Config/Migrations.php set $currentVersion = 20121031100537;.

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

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

$currentVersion の使用

The $currentVersion setting allows you to mark a location that your main application namespace should be set at. これは本番環境設定で特に便利です。アプリケーションでは、本番環境とステージングサーバが正しいスキーマで実行されることを確実にするため、現在適用するバージョンであり最新ではないバージョンに常にマイグレーションをし続けることができます。開発サーバでは、まだ本番適用の準備ができていないコードのための追加のマイグレーションを実行できます。latest() メソッドを使えば、開発マシンを常にアルファ版スキーマにすることができます。

データベースのグループ

A migration will only be run against a single database group. If you have multiple groups defined in app/Config/Database.php, then it will run against the $defaultGroup as specified in that same configuration file. 異なるデータベースグループに異なるスキーマが必要になることが、きっとあるでしょう。おそらく片方はサイトの一般的な情報に使用し、他方はミッションクリティカルなデータに使われているでしょう。マイグレーションは $DBGroup プロパティで指定した適切なグループに対してのみ動作させるようにできます。この名前はデータベースグループに完全に一致させなければいけません:

<?php namespace App\Database\Migrations;

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

    public function up() { . . . }

    public function down() { . . . }
}

名前空間

The migration library can automatically scan all namespaces you have defined within app/Config/Autoload.php or loaded from an external source like Composer, using the $psr4 property for matching directory names. It will include all migrations it finds in Database/Migrations.

Each namespace has it's own version sequence, this will help you upgrade and downgrade each module (namespace) without affecting other namespaces.

For example, assume that we have 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 app/Controllers/Migrate.php to update the schema:

<?php namespace App\Controllers;

class Migrate extends \CodeIgniter\Controller
{

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

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

}

Command-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 spark migrate:latest

You can use (latest) with the following options:

  • (-g) to chose database group, otherwise default database group will be used.
  • (-n) to choose namespace, otherwise (App) namespace will be used.
  • (-all) to migrate all namespaces to the latest migration

This example will migrate Blog namespace to latest:

> php spark migrate:latest -g test -n Blog

current

Migrates the (App) namespace to match the version set in $currentVersion. This will migrate both up and down as needed to match the specified version:

> php spark migrate:current

You can use (current) with the following options:

  • (-g) to chose database group, otherwise default database group will be used.

version

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

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

// Sequential
> php spark migrate:version 007

// Timestamp
> php spark migrate:version 20161426211300

You can use (version) with the following options:

  • (-g) to chose database group, otherwise default database group will be used.
  • (-n) to choose namespace, otherwise (App) namespace will be used.

rollback

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

> php spark migrate:rollback

You can use (rollback) with the following options:

  • (-g) to chose database group, otherwise default database group will be used.
  • (-n) to choose namespace, otherwise (App) namespace will be used.
  • (-all) to migrate all namespaces to the latest migration

refresh

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

> php spark migrate:refresh

You can use (refresh) with the following options:

  • (-g) to chose database group, otherwise default database group will be used.
  • (-n) to choose namespace, otherwise (App) namespace will be used.
  • (-all) to migrate all namespaces to the latest migration

status

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

> php spark migrate:status
Filename               Migrated On
First_migration.php    2016-04-25 04:44:22

You can use (refresh) with the following options:

  • (-g) to chose database group, otherwise default database group will be used.

create

Creates a skeleton migration file in app/Database/Migrations.

  • When migration type is timestamp, using the YYYYMMDDHHIISS format:

    > php spark migrate:create [filename]
    
  • When migration type is sequential, using the numbered in sequence, default with 001:

    > php spark migrate:create [filename] 001
    

You can use (create) with the following options:

  • (-n) to choose namespace, otherwise (App) namespace will be used.

Migration Preferences

The following is a table of all the config options for migrations, available in app/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($group)
パラメータ:
  • $group (mixed) -- database group name, if null (App) namespace will be used.
戻り値:

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 app/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($namespace, $group)
パラメータ:
  • $namespace (mixed) -- application namespace, if null (App) namespace will be used.
  • $group (mixed) -- database group name, if null default database group will be used.
戻り値:

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.

latestAll($group)
パラメータ:
  • $group (mixed) -- database group name, if null default database group will be used.
戻り値:

成功時は TRUE、失敗時は FALSE

戻り値の型:

mixed

This works much the same way as latest() but instead of looking for one namespace, the Migration class will use the very newest migration found for all namespaces.

version($target_version, $namespace, $group)
パラメータ:
  • $namespace (mixed) -- application namespace, if null (App) namespace will be used.
  • $group (mixed) -- database group name, if null default database group will be used.
  • $target_version (mixed) -- Migration version to process
戻り値:

Current version string on success, FALSE on failure or no migrations are found

戻り値の型:

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);
setNamespace($namespace)
パラメータ:
  • $namespace (string) -- application namespace.
戻り値:

The current MigrationRunner instance

戻り値の型:

CodeIgniterDatabaseMigrationRunner

Sets the path the library should look for migration files:

$migration->setNamespace($path)
          ->latest();
setGroup($group)
パラメータ:
  • $group (string) -- database group name.
戻り値:

The current MigrationRunner instance

戻り値の型:

CodeIgniterDatabaseMigrationRunner

Sets the path the library should look for migration files:

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