git-svn-id: http://xe-core.googlecode.com/svn/trunk@1110 201d5d3c-b55e-5fd7-737f-ddc643e51545

This commit is contained in:
zero 2007-04-12 04:48:39 +00:00
parent 2e59a1accd
commit cea271683f
2 changed files with 181 additions and 157 deletions

View file

@ -1,17 +1,18 @@
<?php
/**
* @class DBMysqli
* @class DBMysqlInndoDB
* @author zero (zero@nzeo.com)
* @brief MySQLi DBMS를 이용하기 위한 class
* @brief MySQL DBMS를 이용하기 위한 class
* @version 0.1
* @todo mysqli 미구현 (mysql과 같은 처리..)
*
* mysqli의 prepare, bind param등을 사용하려고 만들었으나....
* 문제는 bind_param 시에 mixed var를 eval이 아닌 방법으로 구현할 방법을 찾지 못했음.
* mysql handling class
**/
class DBMysqli extends DB {
class DBMysqlInndoDB extends DB {
/**
* @brief Mysql DB에 접속하기 위한 정보
**/
var $hostname = '127.0.0.1'; ///< hostname
var $userid = NULL; ///< user id
var $password = NULL; ///< password
@ -37,7 +38,7 @@
/**
* @brief constructor
**/
function DBMysqli() {
function DBMysqlInndoDB() {
$this->_setDBInfo();
$this->_connect();
}
@ -46,7 +47,7 @@
* @brief 설치 가능 여부를 return
**/
function isSupported() {
if(!function_exists('mysqli_connect') || mysqli_get_client_info() < "4.1.00") return false;
if(!function_exists('mysql_connect') || mysql_get_client_info() < "4.1.00") return false;
return true;
}
@ -71,16 +72,24 @@
if(!$this->hostname || !$this->userid || !$this->password || !$this->database) return;
// 접속시도
$this->fd = @mysqli_connect($this->hostname, $this->userid, $this->password, $this->database);
// 접속체크
if(mysqli_connect_error()) {
$this->setError(-1, mysqli_connect_error());
return $this->is_connected = false;
$this->fd = @mysql_connect($this->hostname, $this->userid, $this->password);
if(mysql_error()) {
$this->setError(mysql_errno(), mysql_error());
return;
}
// db 선택
@mysql_select_db($this->database, $this->fd);
if(mysql_error()) {
$this->setError(mysql_errno(), mysql_error());
return;
}
// 접속체크
$this->is_connected = true;
$this->_query("SET NAMES 'utf8'");
// mysql의 경우 utf8임을 지정
$this->_query("set names 'utf8'");
}
/**
@ -88,19 +97,36 @@
**/
function close() {
if(!$this->isConnected()) return;
@mysqli_close();
@mysql_close($this->fd);
}
/**
* @brief 쿼리에서 입력되는 문자열 변수들의 quotation 조절
**/
function addQuotes($string) {
if(!$this->fd) return $string;
if(get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$string));
if(!is_numeric($string)) $string = mysqli_escape_string($this->fd, $string);
if(!is_numeric($string)) $string = @mysql_escape_string($string);
return $string;
}
/**
* @brief 트랜잭션 시작
**/
function begin() {
}
/**
* @brief 롤백
**/
function rollback() {
}
/**
* @brief 커밋
**/
function commit() {
}
/**
* @brief : 쿼리문의 실행 결과의 fetch 처리
*
@ -113,72 +139,28 @@
function _query($query) {
if(!$this->isConnected()) return;
$this->query = $query;
// 쿼리 시작을 알림
$this->actStart($query);
if(__DEBUG__) $query_start = getMicroTime();
// 쿼리 문 실행
$result = @mysql_query($query, $this->fd);
$this->setError(0,'success');
// 오류 체크
if(mysql_error($this->fd)) $this->setError(mysql_errno($this->fd), mysql_error($this->fd));
$result = mysqli_query($this->fd,$query);
if(__DEBUG__) {
$query_end = getMicroTime();
$elapsed_time = $query_end - $query_start;
$GLOBALS['__db_elapsed_time__'] += $elapsed_time;
}
if(mysqli_errno($this->fd)) {
$this->setError(mysqli_errno($this->fd), mysqli_error($this->fd));
if(__DEBUG__) {
$GLOBALS['__db_queries__'] .= sprintf("\t%02d. %s (%0.6f sec)\n\t Fail : %d\n\t\t %s\n", ++$GLOBALS['__dbcnt'], $this->query, $elapsed_time, $this->errno, $this->errstr);
}
return;
}
if(__DEBUG__) {
$GLOBALS['__db_queries__'] .= sprintf("\t%02d. %s (%0.6f sec)\n", ++$GLOBALS['__dbcnt'], $this->query, $elapsed_time);
}
// 쿼리 실행 종료를 알림
$this->actFinish();
// 결과 리턴
return $result;
}
/**
* @brief 트랜잭션 시작
**/
function begin() {
if(!$this->is_connected || $this->transaction_started) return;
$this->_query('begin');
$this->transaction_started = true;
}
/**
* @brief 롤백
**/
function rollback() {
if(!$this->is_connected || !$this->transaction_started) return;
$this->_query('rollback');
$this->transaction_started = false;
}
/**
* @brief 커밋
**/
function commit() {
if(!$this->is_connected || !$this->transaction_started) return;
$this->_query('commit');
$this->transaction_started = false;
}
/**
* @brief 결과를 fetch
**/
function _fetch($result) {
if($this->isError() || !$result) return;
while($tmp = mysqli_fetch_object($result)) {
if(!$this->isConnected() || $this->isError() || !$result) return;
while($tmp = mysql_fetch_object($result)) {
$output[] = $tmp;
}
if(count($output)==1) return $output[0];
@ -191,7 +173,7 @@
function getNextSequence() {
$query = sprintf("insert into `%ssequence` (seq) values ('')", $this->prefix);
$this->_query($query);
return mysqli_insert_id($this->fd);
return mysql_insert_id();
}
/**
@ -283,78 +265,94 @@
}
}
$schema = sprintf('create table `%s` (%s%s) %s;', $this->addQuotes($table_name), "\n", implode($column_schema,",\n"), "type=innodb CHARACTER SET utf8 COLLATE utf8_general_ci");
$schema = sprintf('create table `%s` (%s%s) %s;', $this->addQuotes($table_name), "\n", implode($column_schema,",\n"), "ENGINE = INNODB CHARACTER SET utf8 COLLATE utf8_general_ci");
$output = $this->_query($schema);
if(!$output) return false;
}
/**
* @brief 테이블 삭제
* @brief 조건문 작성하여 return
**/
function dropTable($target_name) {
$query = sprintf('drop table `%s%s`;', $this->prefix, $this->addQuotes($target_name));
$this->_query($query);
}
function getCondition($output) {
if(!$output->conditions) return;
/**
* @brief 테이블의 이름 변경
**/
function renameTable($source_name, $targe_name) {
$query = sprintf("alter table `%s%s` rename `%s%s`;", $this->prefix, $this->addQuotes($source_name), $this->prefix, $this->addQuotes($targe_name));
$this->_query($query);
}
foreach($output->conditions as $key => $val) {
$sub_condition = '';
foreach($val['condition'] as $k =>$v) {
if(!$v['value']) continue;
/**
* @brief 테이블을 비움
**/
function truncateTable($target_name) {
$query = sprintf("truncate table `%s%s`;", $this->prefix, $this->addQuotes($target_name));
$this->_query($query);
}
$name = $v['column'];
$operation = $v['operation'];
$value = $v['value'];
$type = $output->column_type[$name];
$pipe = $v['pipe'];
/**
* @brief 테이블 데이터 Dump
*
* @todo 아직 미구현
**/
function dumpTable($target_name) {
$value = $this->getConditionValue($name, $value, $operation, $type);
$str = $this->getConditionPart($name, $value, $operation);
if($sub_condition) $sub_condition .= ' '.$pipe.' ';
$sub_condition .= $str;
}
if($sub_condition) {
if($condition && $val['pipe']) $condition .= ' '.$val['pipe'].' ';
$condition .= '('.$sub_condition.')';
}
}
if($condition) $condition = ' where '.$condition;
return $condition;
}
/**
* @brief insertAct 처리
**/
function _executeInsertAct($tables, $column, $pass_quotes) {
$table = array_pop($tables);
foreach($column as $key => $val) {
$key_list[] = $key;
if(in_array($key, $pass_quotes)) $val_list[] = $this->addQuotes($val);
else $val_list[] = '\''.$this->addQuotes($val).'\'';
function _executeInsertAct($output) {
// 테이블 정리
foreach($output->tables as $key => $val) {
$table_list[] = '`'.$this->prefix.$key.'`';
}
$query = sprintf("insert into `%s%s` (%s) values (%s);", $this->prefix, $table, '`'.implode('`,`',$key_list).'`', implode(',', $val_list));
// 컬럼 정리
foreach($output->columns as $key => $val) {
$name = $val['name'];
$value = $val['value'];
if($output->column_type[$name]!='number') {
$value = "'".$this->addQuotes($value)."'";
if(!$value) $value = 'null';
} else {
if(!$value) $value = 0;
}
$column_list[] = '`'.$name.'`';
$value_list[] = $value;
}
$query = sprintf("insert into %s (%s) values (%s);", implode(',',$table_list), implode(',',$column_list), implode(',', $value_list));
return $this->_query($query);
}
/**
* @brief updateAct 처리
**/
function _executeUpdateAct($tables, $column, $args, $condition, $pass_quotes) {
$table = array_pop($tables);
foreach($column as $key => $val) {
// args에 아예 해당 key가 없으면 패스
if(!isset($args->{$key})) continue;
if(in_array($key, $pass_quotes)) $update_list[] = sprintf('`%s` = %s', $key, $this->addQuotes($val));
else $update_list[] = sprintf('`%s` = \'%s\'', $key, $this->addQuotes($val));
function _executeUpdateAct($output) {
// 테이블 정리
foreach($output->tables as $key => $val) {
$table_list[] = '`'.$this->prefix.$key.'`';
}
if(!count($update_list)) return;
$update_query = implode(',',$update_list);
if($condition) $condition = ' where '.$condition;
// 컬럼 정리
foreach($output->columns as $key => $val) {
$name = $val['name'];
$value = $val['value'];
if($output->column_type[$name]!='number') $value = "'".$this->addQuotes($value)."'";
$query = sprintf("update `%s%s` set %s %s;", $this->prefix, $table, $update_query, $condition);
$column_list[] = sprintf("`%s` = %s", $name, $value);
}
// 조건절 정리
$condition = $this->getCondition($output);
$query = sprintf("update %s set %s %s", implode(',',$table_list), implode(',',$column_list), $condition);
return $this->_query($query);
}
@ -362,12 +360,17 @@
/**
* @brief deleteAct 처리
**/
function _executeDeleteAct($tables, $condition, $pass_quotes) {
$table = array_pop($tables);
function _executeDeleteAct($output) {
// 테이블 정리
foreach($output->tables as $key => $val) {
$table_list[] = '`'.$this->prefix.$key.'`';
}
if($condition) $condition = ' where '.$condition;
// 조건절 정리
$condition = $this->getCondition($output);
$query = sprintf("delete from %s %s", implode(',',$table_list), $condition);
$query = sprintf("delete from `%s%s` %s;", $this->prefix, $table, $condition);
return $this->_query($query);
}
@ -377,32 +380,42 @@
* select의 경우 특정 페이지의 목록을 가져오는 것을 편하게 하기 위해\n
* navigation이라는 method를 제공
**/
function _executeSelectAct($tables, $column, $invert_columns, $condition, $navigation, $group_script, $pass_quotes) {
if(!count($tables)) $table = $this->prefix.array_pop($tables);
else {
foreach($tables as $key => $val) $table_list[] = sprintf('%s%s as %s', $this->prefix, $key, $val);
function _executeSelectAct($output) {
// 테이블 정리
$table_list = array();
foreach($output->tables as $key => $val) {
$table_list[] = '`'.$this->prefix.$key.'` as '.$val;
}
$table = implode(',',$table_list);
if(!$column) $columns = '*';
else {
foreach($invert_columns as $key => $val) {
$column_list[] = sprintf('%s as %s',$val, $key);
if(!$output->columns) {
$columns = '*';
} else {
$column_list = array();
foreach($output->columns as $key => $val) {
$name = $val['name'];
$alias = $val['alias'];
if($name == '*') {
$column_list[] = '*';
} elseif(strpos($name,'.')===false && strpos($name,'(')===false) {
if($alias) $column_list[] = sprintf('`%s` as `%s`', $name, $alias);
else $column_list[] = sprintf('`%s`',$name);
} else {
if($alias) $column_list[] = sprintf('%s as `%s`', $name, $alias);
else $column_list[] = sprintf('%s',$name);
}
}
$columns = implode(',', $column_list);
$columns = implode(',',$column_list);
}
if($condition) $condition = ' where '.$condition;
$condition = $this->getCondition($output);
if($navigation->list_count) return $this->_getNavigationData($table, $columns, $condition, $navigation);
if($output->list_count) return $this->_getNavigationData($table_list, $columns, $condition, $output);
$query = sprintf("select %s from %s %s", $columns, $table, $condition);
$query = sprintf("select %s from %s %s", $columns, implode(',',$table_list), $condition);
$query .= ' '.$group_script;
if($navigation->index) {
foreach($navigation->index as $index_obj) {
$index_list[] = sprintf('%s %s', $index_obj[0], $index_obj[1]);
if($output->order) {
foreach($output->order as $key => $val) {
$index_list[] = sprintf('%s %s', $val[0], $val[1]);
}
if(count($index_list)) $query .= ' order by '.implode(',',$index_list);
}
@ -421,29 +434,40 @@
*
* 그닥 좋지는 않은 구조이지만 편리하다.. -_-;
**/
function _getNavigationData($table, $columns, $condition, $navigation) {
function _getNavigationData($table_list, $columns, $condition, $output) {
require_once('./classes/page/PageHandler.class.php');
// 전체 개수를 구함
$count_query = sprintf("select count(*) as count from %s %s", $table, $condition);
$count_query = sprintf("select count(*) as count from %s %s", implode(',',$table_list), $condition);
$result = $this->_query($count_query);
$count_output = $this->_fetch($result);
$total_count = (int)$count_output->count;
$list_count = $output->list_count['value'];
if(!$list_count) $list_count = 20;
$page_count = $output->page_count['value'];
if(!$page_count) $page_count = 10;
$page = $output->page->value;
if(!$page) $page = 1;
// 전체 페이지를 구함
$total_page = (int)(($total_count-1)/$navigation->list_count) +1;
$total_page = (int)(($total_count-1)/$list_count) +1;
// 페이지 변수를 체크
if($navigation->page > $total_page) $page = $navigation->page;
else $page = $navigation->page;
$start_count = ($page-1)*$navigation->list_count;
if($page > $total_page) $page = $total_page;
$start_count = ($page-1)*$list_count;
foreach($navigation->index as $index_obj) {
$index_list[] = sprintf('%s %s', $index_obj[0], $index_obj[1]);
$query = sprintf("select %s from %s %s", $columns, implode(',',$table_list), $condition);
if($output->order) {
foreach($output->order as $key => $val) {
$index_list[] = sprintf('%s %s', $val[0], $val[1]);
}
if(count($index_list)) $query .= ' order by '.implode(',',$index_list);
}
$index = implode(',',$index_list);
$query = sprintf('select %s from %s %s order by %s limit %d, %d', $columns, $table, $condition, $index, $start_count, $navigation->list_count);
$query = sprintf('%s limit %d, %d', $query, $start_count, $list_count);
$result = $this->_query($query);
if($this->isError()) {
$buff = new Object();
@ -452,12 +476,12 @@
$buff->page = 1;
$buff->data = array();
$buff->page_navigation = new PageHandler($total_count, $total_page, $page, $navigation->page_count);
$buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count);
return $buff;
}
$virtual_no = $total_count - ($page-1)*$navigation->list_count;
while($tmp = $result->fetch_object()) {
$virtual_no = $total_count - ($page-1)*$list_count;
while($tmp = mysql_fetch_object($result)) {
$data[$virtual_no--] = $tmp;
}
@ -467,7 +491,7 @@
$buff->page = $page;
$buff->data = $data;
$buff->page_navigation = new PageHandler($total_count, $total_page, $page, $navigation->page_count);
$buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count);
return $buff;
}
}

View file

@ -42,7 +42,7 @@
$lang->db_desc = array(
'mysql' => 'mysql DB를 php의 mysql*()함수를 이용하여 사용합니다.<br />DB 파일은 myisam으로 생성되기에 트랜잭션이 이루어지지 않습니다.',
'mysqli' => 'mysql DB를 php의 mysqli*()함수를 이용하여 사용합니다.<br />DB 파일을 INNODB로 생성하여 트랜잭션 기능을 수행할 수 있습니다.<br />(안정화 테스트가 되지 않았습니다)',
'mysqlinnodb' => 'mysql DB를 innodb를 이용하여 사용합니다.<br />innodb는 트랜잭션을 사용할 수 있습니다',
'sqlite2' => '파일로 데이터를 저장하는 sqlite2를 지원합니다.<br />설치시 DB파일은 웹에서 접근할 수 없는 곳에 생성하여 주셔야 합니다.<br />(안정화 테스트가 되지 않았습니다)',
'sqlite3_pdo' => 'PHP의 PDO로 sqlite3를 지원합니다.<br />설치시 DB파일은 웹에서 접근할 수 없는 곳에 생성하여 주셔야 합니다.',
'cubrid' => 'CUBRID DB를 이용합니다.<br />(안정화 테스트 및 튜닝이 되지 않았습니다)',