CodeIgniter User Guide Version 2.1.0


마이그레이션(Migration) 클래스

마이그레이션을 통해서 쉽고 안정적으로 데이터베이스를 변경(alter) 할 수 있습니다. 수작업으로 sql을 만들 수도 있지만, 그럴경우 어떤것이 변경되었는지 ,다음 배포때는 어떤것이 수행되어야하는지, 기억하고 있어야 합니다.

데이터베이스 테이블 마이그레이션은 어떤 마이그레이션이 수행되었는지 지속적으로 추적해 주기 때문에, 개발자는 단지 프로그램 파일을 업데이트 하고 $this->migrate->current() 만 호출하면,배포에 필요한 마이그레이션이 수행됩니다.현재버전은 config/migration.php에 있습니다.

마이그레이션 생성

블로그를 포함하고 있는 새 사이트의 첫번째 마이그레이션 일 경우입니다. 모든 마이그레이션은 application/migrations/ 으로 들어가며, 이름은 001_add_blog.php 와 같은 형태가 됩니다.

defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_blog extends CI_Migration {

	public function up()
	{
		$this->dbforge->add_field(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->dbforge->create_table('blog');
	}

	public function down()
	{
		$this->dbforge->drop_table('blog');
	}

그리고 application/config/migration.php 에서 $config['migration_version'] = 1;으로 설정합니다.

사용예

예제에서 사용되는 코드는 application/controllers/migrate.php 에 있으며 스키마를 업데이트 합니다.

$this->load->library('migration');

if ( ! $this->migration->current())
{
	show_error($this->migration->error_string());
}

함수 레퍼런스

$this->migration->current()

application/config/migration.php에 있는 $config['migration_version'] 에 설정된 현재버전

$this->migration->latest()

current() 와 거의 유사하게 동작하나, $config['migration_version']를 참조하는 대신, 파일 시스템에 있는 가장 최근의 마이그레이션을 사용합니다.

$this->migration->version()

특정버전으로 롤백하거나, 이후 버전으로 바꿀 때 사용합니다. current와 유사하게 동작하나$config['migration_version']를 사용하지 않습니다.

$this->load->library('migration');

$this->migration->version(5);

마이그레이션 참조

마이그레이션 설정 옵션

설정 기본값 옵션 설명
migration_enabledFALSETRUE / FALSE 마이그레이션 사용/비사용 설정
migration_version0None 데이터베이스가 사용하고 있는 현재버전
migration_pathAPPPATH.'migrations/'None 마이그레이션 폴더의 경로