데이터베이스 유틸리티 클래스 Database Utility Class

데이터베이스 유틸리티 클래스는 데이터베이스 관리에 도움을 주는 함수들을 제공합니다.

유틸리티 클래스 초기화 Initializing the Utility Class

Important

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

아래와 같이 유틸리티 클래스를 로드합니다:

$this->load->dbutil()

또한 관리할 데이터베이스가 하나가 아닌 경우, DB 유틸리티 로더에 다른 데이터베이스 객체를 전달할 수 있습니다 :

$this->myutil = $this->load->dbutil($this->other_db, TRUE);

위 예제에서, 커스텀 데이터베이스 객체를 첫 번째 파라미터에 전달하고, 직접직으로 $this->dbutil 객체에 할당하는 대신 dbutil 객체를 리턴 받습니다.

Note

두 개의 파라미터는 개별적으로 사용될 수 있습니다. 만약 스킵하고 싶으면, 첫 번째 파라미터에 빈 값을 넘겨주세요.

초기화 되고 나면 함수들을 사용할 때 $this->dbutil 객체를 이용합니다:

$this->dbutil->some_method()

유틸리티 사용하기 Using the Database Utilities

데이터베이스 목록 검색 Retrieve list of database names

데이터베이스 이름을 담은 배열을 리턴합니다:

$dbs = $this->dbutil->list_databases();

foreach ($dbs as $db)
{
        echo $db;
}

데이터베이스가 존재하는지 확인 Determine If a Database Exists

데이터베이스 존재 여부를 확인. 리턴값 TRUE/FALSE. 예제:

if ($this->dbutil->database_exists('database_name'))
{
        // some code...
}

Note

database_name 부분을 찾고자 하는 테이블 명으로 바꿉니다. 대소문자에 주의하세요.

테이블 최적화 Optimize a Table

첫 번째 파라미터로 테이블 이름을 넘겨주며, 그 테이블을 최적화 합니다. 작업 결과에 따라서 TRUE/FALSE을 리턴합니다:

if ($this->dbutil->optimize_table('table_name'))
{
        echo 'Success!';
}

Note

모든 데이터베이스 플렛폼이 지원하지는 않습니다. 이 함수는 MySQL 데이터베이스에서만 사용할 수 있습니다.

테이블 수리 Repair a Table

첫 번째 파라미터로 테이블 이름을 넘겨주며, 그 테이블을 수리합니다. 작업 결과에 따라서 TRUE/FALSE을 리턴합니다:

if ($this->dbutil->repair_table('table_name'))
{
        echo 'Success!';
}

Note

모든 데이터베이스 플렛폼이 테이블 최적화를 지원하지는 않습니다.

데이터베이스 최적화 Optimize a Database

현재 사용 중인 데이터베이스를 최적화합니다. 작업 결과에 따라 데이터베이스 상태가 담긴 배열을 리턴하거나 FALSE를 리턴합니다.

$result = $this->dbutil->optimize_database();

if ($result !== FALSE)
{
        print_r($result);
}

Note

모든 데이터베이스 플렛폼이 테이블 최적화를 지원하지는 않습니다.

쿼리 결과를 CSV 파일로 내보내기 Export a Query Result as a CSV File

쿼리 결과로부터 CSV를 생성할 수 있게 합니다. 첫 번째 파라미터는 반드시 쿼리 실행의 결과객체라야 합니다. 예제:

$this->load->dbutil();

$query = $this->db->query("SELECT * FROM mytable");

echo $this->dbutil->csv_from_result($query);

두 번째와 세 번째 파라미터는 각각 칼럼구분자(delimiter)와 줄바꿈문자로 설정합니다. 기본적으로 탭이 칼럼구분자로,“n” 이 줄바꿈문자입니다. 예제:

$delimiter = ",";
$newline = "\r\n";
$enclosure = '"';

echo $this->dbutil->csv_from_result($query, $delimiter, $newline, $enclosure);

Important

이 함수는 CSV 파일을 생성하는 것이 아니라 단순히 CSV레이아웃을 생성합니다. 이 파일을 저장하러면 파일(File Helper) 섹션을 보세요.

쿼리 결과를 XML 문서로 내보내기 Export a Query Result as an XML Document

쿼리 결과로부터 XML 을 생성해줍니다. 첫 번째 파라미터는 쿼리 결과 객체이며 두 번째 파라미터는 옵션으로 환경설정을 담은 배열을 넘겨줄 수 있습니다. 예제:

$this->load->dbutil();

$query = $this->db->query("SELECT * FROM mytable");

$config = array (
        'root'          => 'root',
        'element'       => 'element',
        'newline'       => "\n",
        'tab'           => "\t"
);

echo $this->dbutil->xml_from_result($query, $config);

Important

이 함수는 XML 파일을 생성하는 것이 아니라 단순히 XML레이아웃을 생성합니다. 이 파일을 저장하러면 파일(File Helper) 섹션을 보세요.

데이터베이스 백업 Backup Your Database

백업시 주의사항 Database Backup Notes

데이터베이스 전체나 각각의 테이블을 백업할 수 있도록 합니다.백업데이터는 Zip 이나 Gzip 포멧으로 압축할 수 있습니다.

Note

이 함수는 MySQL, Interbase/Firebird 데이터베이스에서만 사용할 수 있습니다.

Note

Interbase/Firebird 데이터베이스는, 백업 파일명이 파라미터가 됩니다.

Eg. $this->dbutil->backup(‘db_backup_filename’);

Note

PHP에서 사용 가능한 메모리가 제한되어있고 실행시간의 제한도 있기 때문에 너무 큰 데이터베이스의 백업은 불가능할 수 있습니다. 큰 데이터베이스는 직접 백업하세요 .

사용 예제 Usag Example

// Load the DB utility class
$this->load->dbutil();

// Backup your entire database and assign it to a variable
$backup =& $this->dbutil->backup();

// Load the file helper and write the file to your server
$this->load->helper('file');
write_file('/path/to/mybackup.gz', $backup);

// Load the download helper and send the file to your desktop
$this->load->helper('download');
force_download('mybackup.gz', $backup);

백업 환경설정 Setting Backup Preferences

백업 환경설정은 배열로 구성되며 backup() 함수의 첫 번째 파라미터로 넘기시면 됩니다. 예제:

$prefs = array(
        'tables'        => array('table1', 'table2'),   // Array of tables to backup.
        'ignore'        => array(),                     // List of tables to omit from the backup
        'format'        => 'txt',                       // gzip, zip, txt
        'filename'      => 'mybackup.sql',              // File name - NEEDED ONLY WITH ZIP FILES
        'add_drop'      => TRUE,                        // Whether to add DROP TABLE statements to backup file
        'add_insert'    => TRUE,                        // Whether to add INSERT data to backup file
        'newline'       => "\n"                         // Newline character used in backup file
);

$this->dbutil->backup($prefs);

백업 환경설정 설명 Description of Backup Preferences

설정 기본값 옵션 설명
tables empty array None 백업하고자 하는 테이블명 배열. 공백이면 모든 테이블을 백업.
ignore empty array None 백업루틴에서 제외하고자 하는 테이블명.(백업 안 할 테이블)
format gzip gzip, zip, txt 백업 파일의 포멧.
filename the current date/time None 백업 파일의 파일명.ZIP 압축시에만 필요함
add_drop TRUE TRUE/FALSE DROP TABLE 문을 백업 파일에 추가할지 여부
add_insert TRUE TRUE/FALSE INSERT문을 SQL 백업 파일에 추가할지 여부.
newline “\n” “\n”, “\r”, “\r\n” SQL 백업 파일의 줄바꿈 문자.
foreign_key_checks TRUE TRUE/FALSE 외래 키 검사를 활성화 해야하는지 여부.

클래스 레퍼런스 Class Reference

class CI_DB_utility
backup([$params = array()])
인수:
  • $params (array) – An associative array of options
반환값:

raw/(g)zipped SQL query string

반환형:

문자열

사용자 환경 설정당, 데이터베이스 백업을 수행합니다.

database_exists($database_name)
인수:
  • $database_name (string) – Database name
반환값:

TRUE if the database exists, FALSE otherwise

반환형:

bool

데이터베이스의 존재 여부를 확인합니다.

list_databases()
반환값:Array of database names found
반환형:배열(array)

모든 데이터베이스 이름 목록을 검색.

optimize_database()
반환값:Array of optimization messages or FALSE on failure
반환형:배열(array)

데이터베이스 최적화.

optimize_table($table_name)
인수:
  • $table_name (string) – Name of the table to optimize
반환값:

Array of optimization messages or FALSE on failure

반환형:

array

테이블 최적화.

repair_table($table_name)
인수:
  • $table_name (string) – Name of the table to repair
반환값:

Array of repair messages or FALSE on failure

반환형:

array

테이블 수리.

csv_from_result($query[, $delim = ', '[, $newline = "n"[, $enclosure = '"']]])
인수:
  • $query (object) – A database result object
  • $delim (string) – The CSV field delimiter to use
  • $newline (string) – The newline character to use
  • $enclosure (string) – The enclosure delimiter to use
반환값:

The generated CSV file as a string

반환형:

문자열

CSV 문서에 데이터베이스 결과 객체를 변환합니다.

xml_from_result($query[, $params = array()])
인수:
  • $query (object) – A database result object
  • $params (array) – An associative array of preferences
반환값:

The generated XML document as a string

반환형:

문자열

XML 문서로 데이터베이스 결과 객체를 변환합니다.