ITの隊長のブログ

ITの隊長のブログです。Rubyを使って仕事しています。最近も色々やっているお(^ω^ = ^ω^)

CakePHPで継続的インテグレーションその3

スポンサードリンク

photo by jc-pics

第3回

前回はフィーチャーテスト(導入のみ)でした。

aipacommander.hatenablog.jp

今日はDBマイグレーションです。

ついに来ました。一番学びたかった項目(゚∀゚)キタコレ!!

これまで、Gitで効率よくソース管理・共有してきたけど、DBだけが面倒だった。

色々調べた結果、マイグレーションって管理方法があるので挑戦したけど、中々根付かない。

本から学んで勉強します。では!

「CakeDC Migrations Plugin」の導入

CakePHPのディレクトリに移動し、Composerでインストールします。

$ composer require "cakedc/migrations:~2.3"

./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)           
  - Installing cakedc/migrations (2.4.0)
    Downloading: 100%         

Writing lock file
Generating autoload files

(Composerって処理遅いよね。ここでは5分程。ネット回線のせいかな)

インストールできました。

プラグインを読み込みます。

  • ~/Config/bootstrap.php
<?php
// 56行目あたり
/**
 * Plugins need to be loaded manually, you can either load them one by one or all of them in a single call
 * Uncomment one of the lines below, as you need. Make sure you read the documentation on CakePlugin to use more
 * advanced ways of loading plugins
 *
 * CakePlugin::loadAll(); // Loads all plugins at once
 * CakePlugin::load('DebugKit'); //Loads a single plugin named DebugKit
 *
 */
CakePlugin::load('Migrations'); // この行を追加

これでおk。

マイグレーションファイルの作成

早速Pluginを使って、DBにテーブルを作成してみましょう。

$ ./Console/cake migrations:migration generate create_posts id:primary_key title:string body:text created modified
Error: Shell class Migrations:migrationShell could not be found.

(°ω°;

何故だ。

あ、ごめんなさい。誤字でした。migrations:migrationのところは「:」ではなく「.」でした。ごめんなさい。

修正して実行

$ ./Console/cake migrations.migration generate create_posts id:primary_key title:string body:text created modified

Cake Migration Shell
---------------------------------------------------------------
---------------------------------------------------------------
Generating migration from commandline arguments...
Do you want to preview the file before generation? (y/n) 
[y] > n
Generating Migration...

Done.

ヒアドキュメントで聞かれます。質問の内容は「プレビューしますか?」って内容らしいのでいいえ(n)でいきましょう。

マイグレーションファイルが作成されました。確認してみます。

  • ~/Config/Migartion/xxxxxxxxxx_create_posts.php
<?php
class CreatePosts extends CakeMigration {

/**
 * Migration description
 *
 * @var string
 */
    public $description = 'create_posts';

/**
 * Actions to be performed
 *
 * @var array $migration
 */
    public $migration = array(
        'up' => array(
            'create_table' => array(
                'posts' => array(
                    'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'),
                    'title' => array('type' => 'string', 'null' => false, 'default' => null),
                    'body' => array('type' => 'text', 'null' => false, 'default' => null),
                    'created' => array('type' => 'datetime', 'null' => false, 'default' => null),
                    'modified' => array('type' => 'datetime', 'null' => false, 'default' => null),
                    'indexes' => array(
                        'PRIMARY' => array('column' => 'id', 'unique' => true),
                    ),
                ),
            ),
        ),
        'down' => array(
            'drop_table' => array(
                'posts'
            ),
        ),
    );

/**
 * Before migration callback
 *
 * @param string $direction Direction of migration process (up or down)
 * @return bool Should process continue
 */
    public function before($direction) {
        return true;
    }

/**
 * After migration callback
 *
 * @param string $direction Direction of migration process (up or down)
 * @return bool Should process continue
 */
    public function after($direction) {
        return true;
    }
}

凄すぎてワロタ

いいね。これ。

マイグレーションの適用

作ったマイグレーションファイルを実行します。

$ ./Console/cake migrations.migration run all -d
Cake Migration Shell
---------------------------------------------------------------
Running migrations:

Migration will run dry, no database changes will be made

---------------------------------------------------------------
SQL for migration 1442625841_create_posts:
---------------------------------------------------------------
CREATE TABLE `test_test_test`.`posts` (`id` int(11) NOT NULL AUTO_INCREMENT,`title` varchar(255) NOT NULL,`body` text NOT NULL,`created` datetime NOT NULL,`modified` datetime NOT NULL,PRIMARY KEY  (`id`)) ;
---------------------------------------------------------------
All migrations have completed.

-dを付けて、実行すると実行すSQL文を確認すことができます。問題なければはずして実行しましょう。

$ ./Console/cake migrations.migration run all 
Cake Migration Shell
---------------------------------------------------------------
Running migrations:
  [1442625841] 1442625841_create_posts
An error occurred when processing the migration:
  Migration: 1442625841_create_posts
  Error: Table "posts" already exists in database.
---------------------------------------------------------------
Do you want to mark the migration as successful?. [y]es or [a]bort. (y/a) 
> a

おろ?

自分の環境では、どうやらすでにpostsテーブルが存在するっぽいです。

削除して再実行

$ ./Console/cake migrations.migration run all 
Cake Migration Shell
---------------------------------------------------------------
Running migrations:
  [1442625841] 1442625841_create_posts
      > Creating table "posts".

---------------------------------------------------------------
All migrations have completed.

おk

ちなみに、allではなく、downにすると前のバージョンに戻ります。便利!

$ ./Console/cake migrations.migration run down
Cake Migration Shell
---------------------------------------------------------------
Running migrations:
  [1442625841] 1442625841_create_posts
      > Dropping table "posts".

---------------------------------------------------------------
All migrations have completed.

チートシート

テーブル操作

テーブル操作 機能
create_table テーブルを生成する
drop_table テーブルを削除する
rename_table テーブルの名前を変更する

列操作

列操作 機能
create_filed 列を追加する
drop_field 列を削除する
alter_field 列定義(名前以外)を変更する
rename_field 列名を変更する

列名

列名 デフォルト値
id integer
created datetime
modified datetime
updated datetime
上記以外 string

CakePHPスキーマ記述

CakePHPスキーマ記述 MySQLの型 最大の長さ
string varchar 255
text text
biginteger bingint 20
integer int 11
float float
datetime datetime
timestamp timestamp
time time
date date
binary blog
boolean tinyint 1

雑メモ

凄い便利じゃないこれ。

ネットの情報だけでやると大変だったわ。容量の悪い俺にとって、本はすばらしい。

これはすごい武器になりそうです。引き続きがんばろう。

これまでの記事

aipacommander.hatenablog.jp

aipacommander.hatenablog.jp

参考書籍

CakePHPで学ぶ継続的インテグレーション

CakePHPで学ぶ継続的インテグレーション

CakePHPで学ぶ継続的インテグレーション (impress top gear)

CakePHPで学ぶ継続的インテグレーション (impress top gear)