CodeIgniterでデータベースのマイグレーションしたいじゃないですかー?
そうすると、migrationライブラリを読み込んでいろいろしたいけれど、ブラウザからコントローラーにアクセスしてやるのはナンセンスじゃないですかー?
そうなると、CLIになるじゃないですかー?
CodeIgniterのコントローラーでは、CLIからのアクセスのみに限定する方法があるので、マイグレーションはCLIからのみにします。$this->input->is_cli_request()で条件分岐すればよいです。
あと、マイグレーションファイルは既に書いているものとします。
これは、マイグレーションを実際に実行するコントローラーです。
<?php
class Migrate extends CI_Controller{
public function __construct() {
parent::__construct();
$this->config->load('migration');
$this->load->library('migration');
}
function migration() {
if ($this->input->is_cli_request()) {
$migrationVersion = $this->config->item('migration_version');
if (!$this->migration->current()) {
echo $this->migration->error_string();
return;
}
echo "Migrate: #{$migrationVersion}\n";
}
}
function rollback() {
if ($this->input->is_cli_request()) {
$migrationVersion = $this->config->item('migration_version');
$rollbackVersion = $migrationVersion - 1;
echo "Current Version: #{$migrationVersion}";
if (!$this->migration->version($rollbackVersion)) {
echo $this->migration->error_string();
return;
}
echo "Rollback: #{$migrationVersion} -> #{$rollbackVersion}\n";
}
}
}
さぁこれで準備はできたかなーと思って、いざマイグレーション。
cd /path/to/codeigniter # CodeIgniterで作ったアプリのディレクトリ php index.php migrate migration
エラーになりました。
Unable to connect to your database server using the provided settings.
ブラウザ経由だとエラーにならないだけに、謎だなーと思っていたのですが、config/database.phpのhostnameがlocalhostだと、エラーになるようです。127.0.0.1にしたら、通りました。
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = '127.0.0.1'; // localhost => 127.0.0.1に変更した
$db['default']['username'] = 'user';
$db['default']['password'] = 'password';
$db['default']['database'] = 'database';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;
$db['default']['port'] = 8889;
/* End of file database.php */
/* Location: ./application/config/database.php */
CLIもコントローラーでなんとかするという感じが微妙な感じがするCodeIgniterですが、マイグレーションくらいはCLIでやりたいから、これでいきましょうかねぇ。
