데이터베이스 관리 클래스 Database Forge Class

데이터베이스 관리 클래스는 아래와 같이 데이터베이스를 관리하는데 도움이 되는 함수들을 포함하고 있습니다.

관리 클래스 초기화 Initializing the Forge Class

Important

관리 클래스를 초기화 하기 위해서는 데이터베이스 드라이버가 실행된 상태라야 합니다. 관리 클래스는 데이터베이스 드라이버에 의존합니다.

관리 클래스를 아래와 같이 로드합니다:

$this->load->dbforge()

사용하고 싶은 데이터베이스가 기본값이 아닐 경우, 다른 데이터베이스 객체를 DB Forge 로더에 전달할 수 있습니다:

$this->myforge = $this->load->dbforge($this->other_db, TRUE);

위 예제에서, 첫 번째 파라미터로 데이터베이스 객체를 전달합니다. 그리고 $this->dbforge를 직접 할당하는 대신에 dbforge 객체를 돌려줍니다.

Note

두 개의 파라미터는 각각 사용될 수 있습니다. 스킵하고 싶으면 첫 번째 파라미터를 빈 값을 전달하면 됩니다.

한 번 로드 되면, $this->dbforge 객체를 이용합니다 object:

$this->dbforge->some_method();

데이터베이스 생성 및 삭제 Creating and Dropping Databases

$this->dbforge->create_database(‘db_name’)

첫 번째 파라미터에 정의한대로 데이터베이스를 생성합니다. 그리고 그 결과에 따라서 TRUE/FALSE를 리턴합니다:

if ($this->dbforge->create_database('my_db'))
{
        echo 'Database created!';
}

$this->dbforge->drop_database(‘db_name’)

첫 번째 파라미터에 주어진 데이터베이스를 삭제합니다. 그리고 그 결과에 따라서 TRUE/FALSE를 리턴합니다:

if ($this->dbforge->drop_database('my_db'))
{
        echo 'Database deleted!';
}

Creating and Dropping Tables

테이블을 생성할 때 하고자 하는 일들이 몇 가지 있을 것입니다. 필드 추가, 키 추가, 칼럼 변경 등이 그것이죠. CodeIgniter는 이러한 작업에 대한 메커니즘을 제공합니다.

Adding fields

필드는 연관배열을 통해 정의됩니다. 배열에는 반드시 필드의 데이터타입에 대한 ‘type’키가 존재해야 합니다. 예를 들어, INT, VARCHAR, TEXT, 등 많은 데이터타입(for example VARCHAR) 과 제약(‘constraint’) 키도 필요합니다.

$fields = array(
        'users' => array(
                'type' => 'VARCHAR',
                'constraint' => '100',
        ),
);
// will translate to "users VARCHAR(100)" when the field is added.

부가적으로, 다음의 키/값 쌍이 사용됩니다:

  • unsigned/true :필드정의에서 “UNSIGNED” 를 생성합니다.
  • default/value : 필드정의에서 기본값을 설정합니다.
  • null/true : 필드정의에서 “NULL” 을 생성합니다. 설정하지 않으면 기본으로 “NOT NULL” 이 설정됩니다.
  • auto_increment/true : 필드정의에서 auto_increment 플래그를 설정합니다. 필드의 타입은 예를 들어 integer 처럼 자동증가를 지원해야 합니다
  • unique/true : 유니크 키를 생성할 때 사용됩니다
$fields = array(
        'blog_id' => array(
                'type' => 'INT',
                'constraint' => 5,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
        ),
        'blog_title' => array(
                'type' => 'VARCHAR',
                'constraint' => '100',
                'unique' => TRUE,
        ),
        'blog_author' => array(
                'type' =>'VARCHAR',
                'constraint' => '100',
                'default' => 'King of Town',
        ),
        'blog_description' => array(
                'type' => 'TEXT',
                'null' => TRUE,
        ),
);

필드정의가 완료된 후 $this->dbforge->add_field($fields); 를 호출하고 최종적으로 create_table() 을 호출하여 적용시킵니다.

$this->dbforge->add_field()

이 함수가 위의 배열을 수용합니다.

Passing strings as fields

필드가 어떤 형태로 생성되어야 하는지 정확히 알고 있다면, add_field() 를 사용할 때 문자열로 넘겨주어도 됩니다.

$this->dbforge->add_field("label varchar(100) NOT NULL DEFAULT 'default label'");

Note

Passing raw strings as fields cannot be followed by add_key() calls on those fields.

Note

add_field() 함수를 여러 번 호출하면 그 결과는 누적됩니다.

아이디 필드 생성 Creating an id field

아이디 필드를 만들 때 특별한 예외가 있습니다. 아이디(id)타입의 필드는 자동으로 INT(9) 로 설정되며 자동증가되는 기본키(Primary Key)로 설정됩니다.

$this->dbforge->add_field('id');
// gives id INT(9) NOT NULL AUTO_INCREMENT

키 추가 Adding Keys

일반적으로, 여러분은 테이블이 키를 가지고 있도록 만들 것입니다. $this->dbforge->add_key(‘field’) 함수를 호출하시면 됩니다. 옵션으로 설정하는 두 번째 파라미터를 TRUE로 하시면 기본키(primary key)가 될것입니다. 주의하실 것은 add_key() 함수는 create_table() 함수 전에 실행되어야 한다는 것입니다.

기본키가 아닌 여러 칼럼들은 반드시 배열로 설정해야 합니다. 아래는 MySql 에 대한 예제입니다.

$this->dbforge->add_key('blog_id', TRUE);
// gives PRIMARY KEY `blog_id` (`blog_id`)

$this->dbforge->add_key('blog_id', TRUE);
$this->dbforge->add_key('site_id', TRUE);
// gives PRIMARY KEY `blog_id_site_id` (`blog_id`, `site_id`)

$this->dbforge->add_key('blog_name');
// gives KEY `blog_name` (`blog_name`)

$this->dbforge->add_key(array('blog_name', 'blog_label'));
// gives KEY `blog_name_blog_label` (`blog_name`, `blog_label`)

테이블 생성 Creating a table

필드와 키들이 정의된 후에 아래와 같이 새로운 테이블을 생성합니다.

$this->dbforge->create_table('table_name');
// gives CREATE TABLE table_name

옵션으로 제공되는 두 번째 파라미터를 TRUE로 설정하면 “IF NOT EXISTS” 절을 추가하게 됩니다.

$this->dbforge->create_table('table_name', TRUE);
// gives CREATE TABLE IF NOT EXISTS table_name

또한 MySQL 의 ENGINE과 같은 옵션을 전달할 수 있습니다:

$attributes = array('ENGINE' => 'InnoDB');
$this->dbforge->create_table('table_name', FALSE, $attributes);
// produces: CREATE TABLE `table_name` (...) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci

Note

Unless you specify the CHARACTER SET and/or COLLATE attributes, create_table() will always add them with your configured char_set and dbcollat values, as long as they are not empty (MySQL only).

테이블 삭제 Dropping a table

테이블삭제( DROP TABLE )쿼리를 실행합니다.

// Produces: DROP TABLE table_name
$this->dbforge->drop_table('table_name');

// Produces: DROP TABLE IF EXISTS table_name
$this->dbforge->drop_table('table_name');

테이블 이름 변경 Renaming a table

테이블 이름 변경(TABLE rename) 쿼리를 실행합니다.

$this->dbforge->rename_table('old_table_name', 'new_table_name');
// gives ALTER TABLE old_table_name RENAME TO new_table_name

테이블 수정 Modifying Tables

테이블에 컬럼 추가 Adding a Column to a Table

$this->dbforge->add_column()

add_column() 함수는 이미 존재하는 테이블을 수정하기 위해 사용합니다. 이 함수는 위에서 설명한 것과 같은 배열을 사용할 수 있으며, 필드의 개수의 제한 없이 사용할 수 있습니다.

$fields = array(
        'preferences' => array('type' => 'TEXT')
);
$this->dbforge->add_column('table_name', $fields);
// Executes: ALTER TABLE table_name ADD preferences TEXT

MySQL 이나 CUBIRD 를 사용한다면, 새로운 칼럼을 위치할 때에 AFTER 절과 FIRST 절을 이용할 수 있습니다.

예제:

// Will place the new column after the `another_field` column:
$fields = array(
        'preferences' => array('type' => 'TEXT', 'after' => 'another_field')
);

// Will place the new column at the start of the table definition:
$fields = array(
        'preferences' => array('type' => 'TEXT', 'first' => TRUE)
);

테이블에서 컬럼 삭제 Dropping a Column From a Table

$this->dbforge->drop_column()

테이블에서 칼럼을 제거하기 위해 사용합니다.

$this->dbforge->drop_column('table_name', 'column_to_drop');

테이블에서 컬럼 수정 Modifying a Column in a Table

$this->dbforge->modify_column()

이 함수의 사용법은 add_column() 함수와 동일합니다만, 새로운 칼럼을 추가하는 것이아니라 기존의 칼럼을 수정하는데 사용합니다. 칼럼 명을 수정하기 위해서는 배열에 “name” 키가 있어야 합니다.

$fields = array(
        'old_name' => array(
                'name' => 'new_name',
                'type' => 'TEXT',
        ),
);
$this->dbforge->modify_column('table_name', $fields);
// gives ALTER TABLE table_name CHANGE old_name new_name TEXT

클래스 레퍼런스

class CI_DB_forge
add_column($table[, $field = array()[, $_after = NULL]])
인수:
  • $table (string) – Table name to add the column to
  • $field (array) – Column definition(s)
  • $_after (string) – Column for AFTER clause (deprecated)
반환값:

TRUE on success, FALSE on failure

반환형:

bool

컬럼을 테이블에 추가. 사용 : Adding a Column to a Table 참조.

add_field($field)
인수:
  • $field (array) – Field definition to add
반환값:

CI_DB_forge instance (method chaining)

반환형:

CI_DB_forge

테이블을 생성하는 데 사용되는 필드들을 추가. 사용: Adding fields 참조.

add_key($key[, $primary = FALSE])
인수:
  • $key (array) – Name of a key field
  • $primary (bool) – Set to TRUE if it should be a primary key or a regular one
반환값:

CI_DB_forge instance (method chaining)

반환형:

CI_DB_forge

테이블을 생성하는 데 사용되는 세트에 키를 추가. 사용: Adding Keys 참조.

create_database($db_name)
인수:
  • $db_name (string) – Name of the database to create
반환값:

TRUE on success, FALSE on failure

반환형:

bool

새로운 데이터베이스 생성. 사용: Creating and Dropping Databases 참조.

create_table($table[, $if_not_exists = FALSE[, array $attributes = array()]])
인수:
  • $table (string) – Name of the table to create
  • $if_not_exists (string) – Set to TRUE to add an ‘IF NOT EXISTS’ clause
  • $attributes (string) – An associative array of table attributes
반환값:

TRUE on success, FALSE on failure

반환형:

bool

새로운 테이블 생성. 사용: Creating a table 참조.

drop_column($table, $column_name)
인수:
  • $table (string) – Table name
  • $column_name (array) – The column name to drop
반환값:

TRUE on success, FALSE on failure

반환형:

bool

테이블에서 컬럼 삭제. 사용 : Dropping a Column From a Table 참조.

drop_database($db_name)
인수:
  • $db_name (string) – Name of the database to drop
반환값:

TRUE on success, FALSE on failure

반환형:

bool

데이터베이스 삭제. 사용: Creating and Dropping Databases 참조.

drop_table($table_name[, $if_exists = FALSE])
인수:
  • $table (string) – Name of the table to drop
  • $if_exists (string) – Set to TRUE to add an ‘IF EXISTS’ clause
반환값:

TRUE on success, FALSE on failure

반환형:

bool

테이블 삭제. 사용: Dropping a table 참조.

modify_column($table, $field)
인수:
  • $table (string) – Table name
  • $field (array) – Column definition(s)
반환값:

TRUE on success, FALSE on failure

반환형:

bool

테이블 컬럼 수정. 사용: Modifying a Column in a Table 참조.

rename_table($table_name, $new_table_name)
인수:
  • $table (string) – Current of the table
  • $new_table_name (string) – New name of the table
반환값:

TRUE on success, FALSE on failure

반환형:

bool

테이블 이름 변경. 사용: Renaming a table 참조.