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

This commit is contained in:
zero 2007-02-14 04:55:29 +00:00
parent a314c21ba7
commit 3d61ed75c1
10 changed files with 1686 additions and 1450 deletions

View file

@ -1,237 +1,249 @@
<?php
/**
* @file : classes/db/DB.class.php
* @author : zero <zero@nzeo.com>
* @desc : DB* 상위 클래스
**/
class DB {
// connector resource or file description
var $fd = NULL;
// result
var $result = NULL;
// errno, errstr
var $errno = 0;
var $errstr = '';
var $query = '';
// isconnected
var $is_connected = false;
// 지원하는 DB의 종류
var $supported_list = array();
// public Object &getInstance($db_type)/*{{{*/
// DB를 상속받는 특정 db type의 instance를 생성 후 return
function &getInstance($db_type = NULL) {
if(!$db_type) $db_type = Context::getDBType();
if(!$db_type) return new Output(-1, 'msg_db_not_setted');
if(!$GLOBALS['__DB__']) {
$class_name = sprintf("DB%s%s", strtoupper(substr($db_type,0,1)), strtolower(substr($db_type,1)));
$class_file = sprintf("./classes/db/%s.class.php", $class_name);
if(!file_exists($class_file)) new Output(-1, 'msg_db_not_setted');
require_once($class_file);
$eval_str = sprintf('$GLOBALS[\'__DB__\'] = new %s();', $class_name);
eval($eval_str);
}
return $GLOBALS['__DB__'];
}/*}}}*/
/**
* 지원 가능한 DB 목록을 return
**/
// public array getSupportedList()/*{{{*/
// 지원하는 DB의 종류 return
function getSupportedList() {
$oDB = new DB();
return $oDB->_getSupportedList();
}/*}}}*/
* @class DB
* @author zero (zero@nzeo.com)
* @brief DB* 상위 클래스
*
* 제로보드5의 DB 사용은 xml을 이용하여 이루어짐을 원칙으로 한다.\n
* xml의 종류에는 query xml, schema xml이 있다.\n
* query xml의 경우 DB::executeQuery() method를 이용하여 xml파일을\n
* php code로 compile한 후에 실행이 된다.\n
* query xml은 고유한 query id를 가지며 생성은 module에서 이루어진다.\n
* \n
* queryid = 모듈.쿼리명\n
* \n
* 으로 된다.\n
**/
// private array _getSupportedList()/*{{{*/
function _getSupportedList() {
if(!count($this->supported_list)) {
$db_classes_path = "./classes/db/";
$filter = "/^DB([^\.]+)\.class\.php/i";
$this->supported_list = FileHandler::readDir($db_classes_path, $filter, true);
}
return $this->supported_list;
}/*}}}*/
class DB {
// public boolean isSupported($db_type) /*{{{*/
// 지원하는 DB인지에 대한 check
function isSupported($db_type) {
$supported_list = DB::getSupportedList();
return in_array($db_type, $supported_list);
}/*}}}*/
var $fd = NULL; ///< connector resource or file description
/**
* 에러 남기기
**/
// public void setError($errno, $errstr) /*{{{*/
function setError($errno, $errstr) {
$this->errno = $errno;
$this->errstr = $errstr;
var $result = NULL; ///< result
if(__DEBUG__ && $this->errno!=0) debugPrint(sprintf("Query Fail\t#%05d : %s - %s\n\t\t%s", $GLOBALS['__dbcnt'], $errno, $errstr, $this->query));
}/*}}}*/
var $errno = 0; ///< 에러 발생시 에러 코드 (0이면 에러가 없다고 정의)
var $errstr = ''; ///< 에러 발생시 에러 메세지
var $query = ''; ///< 가장 최근에 수행된 query string
/**
* 각종 bool return
**/
// public boolean isConnected()/*{{{*/
// 접속되었는지 return
function isConnected() {
return $this->is_connected;
}/*}}}*/
var $is_connected = false; ///< DB에 접속이 되었는지에 대한 flag
// public boolean isError()/*{{{*/
// 오류가 발생하였는지 return
function isError() {
return $error===0?true:false;
}/*}}}*/
var $supported_list = array(); ///< 지원하는 DB의 종류, classes/DB/DB***.class.php 를 이용하여 동적으로 작성됨
// public object getError()/*{{{*/
function getError() {
return new Output($this->errno, $this->errstr);
}/*}}}*/
/**
* @brief DB를 상속받는 특정 db type의 instance를 생성 return
**/
function &getInstance($db_type = NULL) {
if(!$db_type) $db_type = Context::getDBType();
if(!$db_type) return new Output(-1, 'msg_db_not_setted');
/**
* query execute
**/
// public object executeQuery($query_id, $args = NULL)/*{{{*/
// query_id = module.queryname
// query_id에 해당하는 xml문(or 캐싱파일)을 찾아서 실행
function executeQuery($query_id, $args = NULL) {
if(!$query_id) return new Output(-1, 'msg_invalid_queryid');
if(!$GLOBALS['__DB__']) {
$class_name = sprintf("DB%s%s", strtoupper(substr($db_type,0,1)), strtolower(substr($db_type,1)));
$class_file = sprintf("./classes/db/%s.class.php", $class_name);
if(!file_exists($class_file)) new Output(-1, 'msg_db_not_setted');
list($module, $id) = explode('.',$query_id);
if(!$module||!$id) return new Output(-1, 'msg_invalid_queryid');
require_once($class_file);
$eval_str = sprintf('$GLOBALS[\'__DB__\'] = new %s();', $class_name);
eval($eval_str);
}
$xml_file = sprintf('./modules/%s/queries/%s.xml', $module, $id);
if(!file_exists($xml_file)) {
$xml_file = sprintf('./files/modules/%s/queries/%s.xml', $module, $id);
if(!file_exists($xml_file)) return new Output(-1, 'msg_invalid_queryid');
}
// 일단 cache 파일을 찾아본다
$cache_file = sprintf('./files/queries/%s.cache.php', $query_id);
// 없으면 원본 쿼리 xml파일을 찾아서 파싱을 한다
if(!file_exists($cache_file)||filectime($cache_file)<filectime($xml_file)) {
require_once('./classes/xml/XmlQueryParser.class.php');
$oParser = new XmlQueryParser();
$oParser->parse($query_id, $xml_file, $cache_file);
}
// 쿼리를 실행한다
return $this->_executeQuery($cache_file, $args, $query_id);
}/*}}}*/
// private object _executeQuery($cache_file, $args)/*{{{*/
// 쿼리문을 실행하고 결과를 return한다
function _executeQuery($cache_file, $source_args, $query_id) {
global $lang;
if(!file_exists($cache_file)) return new Output(-1, 'msg_invalid_queryid');
if(__DEBUG__) $query_start = getMicroTime();
if($source_args) $args = clone($source_args);
$output = include($cache_file);
if( (is_a($output, 'Output')||is_subclass_of($output,'Output'))&&!$output->toBool()) return $output;
// action값에 따라서 쿼리 생성으로 돌입
switch($action) {
case 'insert' :
$output = $this->_executeInsertAct($tables, $column, $pass_quotes);
break;
case 'update' :
$output = $this->_executeUpdateAct($tables, $column, $condition, $pass_quotes);
break;
case 'delete' :
$output = $this->_executeDeleteAct($tables, $condition, $pass_quotes);
break;
case 'select' :
$output = $this->_executeSelectAct($tables, $column, $invert_columns, $condition, $navigation, $group_script, $pass_quotes);
break;
}
if(__DEBUG__) {
$query_end = getMicroTime();
$elapsed_time = $query_end - $query_start;
$GLOBALS['__db_elapsed_time__'] += $elapsed_time;
$GLOBALS['__db_queries__'] .= sprintf("\t%02d. %s (%0.4f sec)\n\t %s\n", ++$GLOBALS['__dbcnt'], $query_id, $elapsed_time, $this->query);
}
if($this->errno!=0) return new Output($this->errno, $this->errstr);
if(is_a($output, 'Output') || is_subclass_of($output, 'Output')) return $output;
return new Output();
}/*}}}*/
// private object _checkFilter($key, $val, $filter_type, $minlength, $maxlength) /*{{{*/
// $val을 $filter_type으로 검사
function _checkFilter($key, $val, $filter_type, $minlength, $maxlength) {
global $lang;
$length = strlen($val);
if($minlength && $length < $minlength) return new Output(-1, sprintf($lang->filter->outofrange, $lang->{$key}?$lang->{$key}:$key));
if($maxlength && $length > $maxlength) return new Output(-1, sprintf($lang->filter->outofrange, $lang->{$key}?$lang->{$key}:$key));
switch($filter_type) {
case 'email' :
case 'email_adderss' :
if(!eregi('^[_0-9a-z-]+(\.[_0-9a-z-]+)*@[0-9a-z-]+(\.[0-9a-z-]+)*$', $val)) return new Output(-1, sprintf($lang->filter->invalid_email, $lang->{$key}?$lang->{$key}:$key));
break;
case 'homepage' :
if(!eregi('^(http|https)+(:\/\/)+[0-9a-z_-]+\.[^ ]+$', $val)) return new Output(-1, sprintf($lang->filter->invalid_homepage, $lang->{$key}?$lang->{$key}:$key));
break;
case 'userid' :
case 'user_id' :
if(!eregi('^[a-zA-Z]+([_0-9a-zA-Z]+)*$', $val)) return new Output(-1, sprintf($lang->filter->invalid_userid, $lang->{$key}?$lang->{$key}:$key));
break;
case 'number' :
if(!eregi('^[0-9]+$', $val)) return new Output(-1, sprintf($lang->filter->invalid_number, $lang->{$key}?$lang->{$key}:$key));
break;
case 'alpha' :
if(!eregi('^[a-z]+$', $val)) return new Output(-1, sprintf($lang->filter->invalid_alpha, $lang->{$key}?$lang->{$key}:$key));
break;
case 'alpha_number' :
if(!eregi('^[0-9a-z]+$', $val)) return new Output(-1, sprintf($lang->filter->invalid_alpha_number, $lang->{$key}?$lang->{$key}:$key));
break;
}
return new Output();
}/*}}}*/
// private string _combineCondition($cond_group, $group_pipe) /*{{{*/
function _combineCondition($cond_group, $group_pipe) {
if(!is_array($cond_group)) return;
$cond_query = '';
foreach($cond_group as $group_idx => $group) {
if(!is_array($group)) continue;
$buff = '';
foreach($group as $key => $val) {
$pipe = key($val);
$cond = array_pop($val);
if($buff) $buff .= $pipe.' '.$cond;
else $buff = $cond;
return $GLOBALS['__DB__'];
}
$g_pipe = $group_pipe[$group_idx];
if(!$g_pipe) $g_pipe = 'and';
if($cond_query) $cond_query .= sprintf(' %s ( %s )', $g_pipe, $buff);
else $cond_query = '('.$buff.')';
}
return $cond_query;
}/*}}}*/
/**
* @brief 지원 가능한 DB 목록을 return
**/
function getSupportedList() {
$oDB = new DB();
return $oDB->_getSupportedList();
}
}
/**
* @brief 지원 가능한 DB 목록을 return
**/
function _getSupportedList() {
if(!count($this->supported_list)) {
$db_classes_path = "./classes/db/";
$filter = "/^DB([^\.]+)\.class\.php/i";
$this->supported_list = FileHandler::readDir($db_classes_path, $filter, true);
}
return $this->supported_list;
}
/**
* @brief 지원하는 DB인지에 대한 check
**/
function isSupported($db_type) {
$supported_list = DB::getSupportedList();
return in_array($db_type, $supported_list);
}
/**
* @brief 에러발생시 에러 메세지를 남기고 debug 모드일때는 GLOBALS 변수에 에러 로깅
**/
function setError($errno, $errstr) {
$this->errno = $errno;
$this->errstr = $errstr;
if(__DEBUG__ && $this->errno!=0) debugPrint(sprintf("Query Fail\t#%05d : %s - %s\n\t\t%s", $GLOBALS['__dbcnt'], $errno, $errstr, $this->query));
}
/**
* @brief 접속되었는지 return
**/
function isConnected() {
return $this->is_connected;
}
/**
* @brief 오류가 발생하였는지 return
**/
function isError() {
return $error===0?true:false;
}
/**
* @brief 에러결과를 Output 객체로 return
**/
function getError() {
return new Output($this->errno, $this->errstr);
}
/**
* @brief query xml 파일을 실행하여 결과를 return
*
* query_id = module.queryname
* query_id에 해당하는 xml문(or 캐싱파일) 찾아서 컴파일 실행
**/
function executeQuery($query_id, $args = NULL) {
if(!$query_id) return new Output(-1, 'msg_invalid_queryid');
list($module, $id) = explode('.',$query_id);
if(!$module||!$id) return new Output(-1, 'msg_invalid_queryid');
$xml_file = sprintf('./modules/%s/queries/%s.xml', $module, $id);
if(!file_exists($xml_file)) {
$xml_file = sprintf('./files/modules/%s/queries/%s.xml', $module, $id);
if(!file_exists($xml_file)) return new Output(-1, 'msg_invalid_queryid');
}
// 일단 cache 파일을 찾아본다
$cache_file = sprintf('./files/queries/%s.cache.php', $query_id);
// 없으면 원본 쿼리 xml파일을 찾아서 파싱을 한다
if(!file_exists($cache_file)||filectime($cache_file)<filectime($xml_file)) {
require_once('./classes/xml/XmlQueryParser.class.php');
$oParser = new XmlQueryParser();
$oParser->parse($query_id, $xml_file, $cache_file);
}
// 쿼리를 실행한다
return $this->_executeQuery($cache_file, $args, $query_id);
}
/**
* @brief 쿼리문을 실행하고 결과를 return한다
**/
function _executeQuery($cache_file, $source_args, $query_id) {
global $lang;
if(!file_exists($cache_file)) return new Output(-1, 'msg_invalid_queryid');
if(__DEBUG__) $query_start = getMicroTime();
if($source_args) $args = clone($source_args);
$output = include($cache_file);
if( (is_a($output, 'Output')||is_subclass_of($output,'Output'))&&!$output->toBool()) return $output;
// action값에 따라서 쿼리 생성으로 돌입
switch($action) {
case 'insert' :
$output = $this->_executeInsertAct($tables, $column, $pass_quotes);
break;
case 'update' :
$output = $this->_executeUpdateAct($tables, $column, $condition, $pass_quotes);
break;
case 'delete' :
$output = $this->_executeDeleteAct($tables, $condition, $pass_quotes);
break;
case 'select' :
$output = $this->_executeSelectAct($tables, $column, $invert_columns, $condition, $navigation, $group_script, $pass_quotes);
break;
}
if(__DEBUG__) {
$query_end = getMicroTime();
$elapsed_time = $query_end - $query_start;
$GLOBALS['__db_elapsed_time__'] += $elapsed_time;
$GLOBALS['__db_queries__'] .= sprintf("\t%02d. %s (%0.4f sec)\n\t %s\n", ++$GLOBALS['__dbcnt'], $query_id, $elapsed_time, $this->query);
}
if($this->errno!=0) return new Output($this->errno, $this->errstr);
if(is_a($output, 'Output') || is_subclass_of($output, 'Output')) return $output;
return new Output();
}
/**
* @brief $val을 $filter_type으로 검사
**/
function _checkFilter($key, $val, $filter_type, $minlength, $maxlength) {
global $lang;
$length = strlen($val);
if($minlength && $length < $minlength) return new Output(-1, sprintf($lang->filter->outofrange, $lang->{$key}?$lang->{$key}:$key));
if($maxlength && $length > $maxlength) return new Output(-1, sprintf($lang->filter->outofrange, $lang->{$key}?$lang->{$key}:$key));
switch($filter_type) {
case 'email' :
case 'email_adderss' :
if(!eregi('^[_0-9a-z-]+(\.[_0-9a-z-]+)*@[0-9a-z-]+(\.[0-9a-z-]+)*$', $val)) return new Output(-1, sprintf($lang->filter->invalid_email, $lang->{$key}?$lang->{$key}:$key));
break;
case 'homepage' :
if(!eregi('^(http|https)+(:\/\/)+[0-9a-z_-]+\.[^ ]+$', $val)) return new Output(-1, sprintf($lang->filter->invalid_homepage, $lang->{$key}?$lang->{$key}:$key));
break;
case 'userid' :
case 'user_id' :
if(!eregi('^[a-zA-Z]+([_0-9a-zA-Z]+)*$', $val)) return new Output(-1, sprintf($lang->filter->invalid_userid, $lang->{$key}?$lang->{$key}:$key));
break;
case 'number' :
if(!eregi('^[0-9]+$', $val)) return new Output(-1, sprintf($lang->filter->invalid_number, $lang->{$key}?$lang->{$key}:$key));
break;
case 'alpha' :
if(!eregi('^[a-z]+$', $val)) return new Output(-1, sprintf($lang->filter->invalid_alpha, $lang->{$key}?$lang->{$key}:$key));
break;
case 'alpha_number' :
if(!eregi('^[0-9a-z]+$', $val)) return new Output(-1, sprintf($lang->filter->invalid_alpha_number, $lang->{$key}?$lang->{$key}:$key));
break;
}
return new Output();
}
/**
* @brief 조건문들 정리
**/
function _combineCondition($cond_group, $group_pipe) {
if(!is_array($cond_group)) return;
$cond_query = '';
foreach($cond_group as $group_idx => $group) {
if(!is_array($group)) continue;
$buff = '';
foreach($group as $key => $val) {
$pipe = key($val);
$cond = array_pop($val);
if($buff) $buff .= $pipe.' '.$cond;
else $buff = $cond;
}
$g_pipe = $group_pipe[$group_idx];
if(!$g_pipe) $g_pipe = 'and';
if($cond_query) $cond_query .= sprintf(' %s ( %s )', $g_pipe, $buff);
else $cond_query = '('.$buff.')';
}
return $cond_query;
}
}
?>

View file

@ -1,375 +1,405 @@
<?php
/**
* @file : classes/db/DB.class.php
* @author : zero <zero@nzeo.com>
* @desc : db(mysql, cubrid, sqlite..) 이용하기 위한 db class의 abstract class
**/
/**
* @class DBMysql
* @author zero (zero@nzeo.com)
* @brief mysql handling class
**/
class DBMysql extends DB {
class DBMysql extends DB {
// db info
var $hostname = '127.0.0.1';
var $userid = NULL;
var $password = NULL;
var $database = NULL;
var $prefix = 'zb';
var $hostname = '127.0.0.1'; ///< hostname
var $userid = NULL; ///< user id
var $password = NULL; ///< password
var $database = NULL; ///< database
var $prefix = 'zb'; ///< 제로보드에서 사용할 테이블들의 prefix (한 DB에서 여러개의 제로보드 설치 가능)
// mysql에서 사용될 column type
var $column_type = array(
'number' => 'int',
'varchar' => 'varchar',
'char' => 'char',
'text' => 'text',
'date' => 'varchar(14)',
/**
* @brief mysql에서 사용될 column type
*
* column_type은 schema/query xml에서 공통 선언된 type을 이용하기 때문에
* DBMS에 맞게 replace 해주어야 한다
**/
var $column_type = array(
'number' => 'int',
'varchar' => 'varchar',
'char' => 'char',
'text' => 'text',
'date' => 'varchar(14)',
);
// public void DBMysql()/*{{{*/
function DBMysql() {
$this->_setDBInfo();
$this->_connect();
}/*}}}*/
/**
* DB정보 설정 connect/ close
**/
// public boolean _setDBInfo()/*{{{*/
function _setDBInfo() {
$db_info = Context::getDBInfo();
$this->hostname = $db_info->db_hostname;
$this->userid = $db_info->db_userid;
$this->password = $db_info->db_password;
$this->database = $db_info->db_database;
$this->prefix = $db_info->db_table_prefix;
if(!substr($this->prefix,-1)!='_') $this->prefix .= '_';
}/*}}}*/
// public boolean _connect()/*{{{*/
function _connect() {
// db 정보가 없으면 무시
if(!$this->hostname || !$this->userid || !$this->password || !$this->database) return;
// 접속시도
$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;
// mysql의 경우 utf8임을 지정
$this->_query("SET NAMES 'utf8'");
}/*}}}*/
// public boolean close()/*{{{*/
function close() {
if(!$this->isConnected()) return;
@mysql_close($this->fd);
}/*}}}*/
/**
* add quotation
**/
// public string addQuotes(string $string)/*{{{*/
function addQuotes($string) {
if(get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$string));
if(!is_numeric($string)) $string = @mysql_escape_string($string);
return $string;
}/*}}}*/
/**
* query : query문 실행하고 result return
* fetch : reutrn 값이 없으면 NULL
* rows이면 array object
* row이면 object
* return
* getNextSequence : 1 증가되는 sequence값을 return (mysql의 auto_increment는 sequence테이블에서만 사용)
*/
// private object _query(string $query) /*{{{*/
function _query($query) {
if(!$this->isConnected()) return;
$this->query = $query;
$this->setError(0,'success');
$result = @mysql_query($query, $this->fd);
if(mysql_error()) {
$this->setError(mysql_errno(), mysql_error());
return;
}
return $result;
}/*}}}*/
// private object _fetch($result) /*{{{*/
function _fetch($result) {
if($this->errno!=0 || !$result) return;
while($tmp = mysql_fetch_object($result)) {
$output[] = $tmp;
}
if(count($output)==1) return $output[0];
return $output;
}/*}}}*/
// public int getNextSequence() /*{{{*/
// sequence값을 받음
function getNextSequence() {
$query = sprintf("insert into `%ssequence` (seq) values ('')", $this->prefix);
$this->_query($query);
return mysql_insert_id();
}/*}}}*/
/**
* Table의 Create/Drop/Alter/Rename/Truncate/Dump...
**/
// public boolean isTableExists(string $table_name)/*{{{*/
function isTableExists($target_name) {
$query = sprintf("show tables like '%s%s'", $this->prefix, $this->addQuotes($target_name));
$result = $this->_query($query);
$tmp = $this->_fetch($result);
if(!$tmp) return false;
return true;
}/*}}}*/
// public boolean createTableByXml($xml) /*{{{*/
// xml 을 받아서 테이블을 생성
function createTableByXml($xml_doc) {
return $this->_createTable($xml_doc);
}/*}}}*/
// public boolean createTableByXmlFile($file_name) /*{{{*/
// xml 을 받아서 테이블을 생성
function createTableByXmlFile($file_name) {
if(!file_exists($file_name)) return;
// xml 파일을 읽음
$buff = FileHandler::readFile($file_name);
return $this->_createTable($buff);
}/*}}}*/
// private boolean _createTable($xml)/*{{{*/
// type : number, varchar, text, char, date,
// opt : notnull, default, size
// index : primary key, index, unique
function _createTable($xml_doc) {
// xml parsing
$oXml = new XmlParser();
$xml_obj = $oXml->parse($xml_doc);
// 테이블 생성 schema 작성
$table_name = $xml_obj->table->attrs->name;
if($this->isTableExists($table_name)) return;
$table_name = $this->prefix.$table_name;
if(!is_array($xml_obj->table->column)) $columns[] = $xml_obj->table->column;
else $columns = $xml_obj->table->column;
foreach($columns as $column) {
$name = $column->attrs->name;
$type = $column->attrs->type;
$size = $column->attrs->size;
$notnull = $column->attrs->notnull;
$primary_key = $column->attrs->primary_key;
$index = $column->attrs->index;
$unique = $column->attrs->unique;
$default = $column->attrs->default;
$auto_increment = $column->attrs->auto_increment;
$column_schema[] = sprintf('`%s` %s%s %s %s %s',
$name,
$this->column_type[$type],
$size?'('.$size.')':'',
$default?"default '".$default."'":'',
$notnull?'not null':'',
$auto_increment?'auto_increment':''
);
if($primary_key) $primary_list[] = $name;
else if($unique) $unique_list[$unique][] = $name;
else if($index) $index_list[$index][] = $name;
}
if(count($primary_list)) {
$column_schema[] = sprintf("primary key (%s)", '`'.implode($primary_list,'`,`').'`');
}
if(count($unique_list)) {
foreach($unique_list as $key => $val) {
$column_schema[] = sprintf("unique %s (%s)", $key, '`'.implode($val,'`,`').'`');
/**
* @brief constructor
**/
function DBMysql() {
$this->_setDBInfo();
$this->_connect();
}
}
if(count($index_list)) {
foreach($index_list as $key => $val) {
$column_schema[] = sprintf("index %s (%s)", $key, '`'.implode($val,'`,`').'`');
/**
* @brief DB정보 설정 connect/ close
**/
function _setDBInfo() {
$db_info = Context::getDBInfo();
$this->hostname = $db_info->db_hostname;
$this->userid = $db_info->db_userid;
$this->password = $db_info->db_password;
$this->database = $db_info->db_database;
$this->prefix = $db_info->db_table_prefix;
if(!substr($this->prefix,-1)!='_') $this->prefix .= '_';
}
}
$schema = sprintf('create table `%s` (%s%s);', $this->addQuotes($table_name), "\n", implode($column_schema,",\n"));
$output = $this->_query($schema);
if(!$output) return false;
}/*}}}*/
/**
* @brief DB 접속
**/
function _connect() {
// db 정보가 없으면 무시
if(!$this->hostname || !$this->userid || !$this->password || !$this->database) return;
// public boolean dropTable($target_name) /*{{{*/
// 테이블 삭제
function dropTable($target_name) {
$query = sprintf('drop table `%s%s`;', $this->prefix, $this->addQuotes($target_name));
$this->_query($query);
}/*}}}*/
// 접속시도
$this->fd = @mysql_connect($this->hostname, $this->userid, $this->password);
if(mysql_error()) {
$this->setError(mysql_errno(), mysql_error());
return;
}
// public boolean renameTable($source_name, $targe_name) /*{{{*/
// 테이블의 이름 변경
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);
}/*}}}*/
// db 선택
@mysql_select_db($this->database, $this->fd);
if(mysql_error()) {
$this->setError(mysql_errno(), mysql_error());
return;
}
// public boolean truncateTable($target_name) /*{{{*/
// 테이블을 비움
function truncateTable($target_name) {
$query = sprintf("truncate table `%s%s`;", $this->prefix, $this->addQuotes($target_name));
$this->_query($query);
}/*}}}*/
// 접속체크
$this->is_connected = true;
// public boolean dumpTable($target_name) 미완성 /*{{{*/
// 테이블 데이터 Dump
function dumpTable($target_name) {
}/*}}}*/
/**
* insert/update/delete/select 구현
**/
// private string _executeInsertAct($tables, $column, $pass_quotes)/*{{{*/
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).'\'';
}
$query = sprintf("insert into `%s%s` (%s) values (%s);", $this->prefix, $table, '`'.implode('`,`',$key_list).'`', implode(',', $val_list));
return $this->_query($query);
}/*}}}*/
// private string _executeUpdateAct($tables, $column, $condition, $pass_quotes)/*{{{*/
function _executeUpdateAct($tables, $column, $condition, $pass_quotes) {
$table = array_pop($tables);
foreach($column as $key => $val) {
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));
}
if(!count($update_list)) return;
$update_query = implode(',',$update_list);
if($condition) $condition = ' where '.$condition;
$query = sprintf("update `%s%s` set %s %s;", $this->prefix, $table, $update_query, $condition);
return $this->_query($query);
}/*}}}*/
// private string _executeDeleteAct($tables, $condition, $pass_quotes)/*{{{*/
function _executeDeleteAct($tables, $condition, $pass_quotes) {
$table = array_pop($tables);
if($condition) $condition = ' where '.$condition;
$query = sprintf("delete from `%s%s` %s;", $this->prefix, $table, $condition);
return $this->_query($query);
}/*}}}*/
// private string _executeSelectAct($tables, $column, $invert_columns, $condition, $navigation, $pass_quotes)/*{{{*/
// 네비게이션 변수 정리를 해야함
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);
}
$table = implode(',',$table_list);
if(!$column) $columns = '*';
else {
foreach($invert_columns as $key => $val) {
$column_list[] = sprintf('%s as %s',$val, $key);
// mysql의 경우 utf8임을 지정
$this->_query("SET NAMES 'utf8'");
}
$columns = implode(',', $column_list);
}
if($condition) $condition = ' where '.$condition;
if($navigation->list_count) return $this->_getNavigationData($table, $columns, $condition, $navigation);
$query = sprintf("select %s from %s %s", $columns, $table, $condition);
$query .= ' '.$group_script;
if($navigation->index) {
foreach($navigation->index as $index_obj) {
$index_list[] = sprintf('%s %s', $index_obj[0], $index_obj[1]);
/**
* @brief DB접속 해제
**/
function close() {
if(!$this->isConnected()) return;
@mysql_close($this->fd);
}
if(count($index_list)) $query .= ' order by '.implode(',',$index_list);
}
/**
* @brief 쿼리에서 입력되는 문자열 변수들의 quotation 조절
**/
function addQuotes($string) {
if(get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$string));
if(!is_numeric($string)) $string = @mysql_escape_string($string);
return $string;
}
$result = $this->_query($query);
if($this->errno!=0) return;
$data = $this->_fetch($result);
/**
* @brief : 쿼리문의 실행 결과의 fetch 처리
*
* query : query문 실행하고 result return\n
* fetch : reutrn 값이 없으면 NULL\n
* rows이면 array object\n
* row이면 object\n
* return\n
**/
function _query($query) {
if(!$this->isConnected()) return;
$this->query = $query;
$buff = new Output();
$buff->data = $data;
return $buff;
}/*}}}*/
$this->setError(0,'success');
// private function _getNavigationData($query)/*{{{*/
// query xml에 navigation 정보가 있을 경우 페이징 관련 작업을 처리한다
// 그닥 좋지는 않은 구조이지만 편리하다.. -_-;
function _getNavigationData($table, $columns, $condition, $navigation) {
// 전체 개수를 구함
$count_query = sprintf("select count(*) as count from %s %s", $table, $condition);
$result = $this->_query($count_query);
$count_output = $this->_fetch($result);
$total_count = (int)$count_output->count;
$result = @mysql_query($query, $this->fd);
// 전체 페이지를 구함
$total_page = (int)(($total_count-1)/$navigation->list_count) +1;
if(mysql_error()) {
$this->setError(mysql_errno(), mysql_error());
return;
}
// 페이지 변수를 체크
if($navigation->page > $total_page) $page = $navigation->page;
else $page = $navigation->page;
$start_count = ($page-1)*$navigation->list_count;
return $result;
}
foreach($navigation->index as $index_obj) {
$index_list[] = sprintf('%s %s', $index_obj[0], $index_obj[1]);
}
/**
* @brief 결과를 fetch
**/
function _fetch($result) {
if($this->errno!=0 || !$result) return;
while($tmp = mysql_fetch_object($result)) {
$output[] = $tmp;
}
if(count($output)==1) return $output[0];
return $output;
}
$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);
$result = $this->_query($query);
if($this->errno!=0) return;
/**
* @brief 1 증가되는 sequence값을 return (mysql의 auto_increment는 sequence테이블에서만 사용)
**/
function getNextSequence() {
$query = sprintf("insert into `%ssequence` (seq) values ('')", $this->prefix);
$this->_query($query);
return mysql_insert_id();
}
$virtual_no = $total_count - ($page-1)*$navigation->list_count;
while($tmp = mysql_fetch_object($result)) {
$data[$virtual_no--] = $tmp;
}
/**
* @brief 테이블 기생성 여부 return
**/
function isTableExists($target_name) {
$query = sprintf("show tables like '%s%s'", $this->prefix, $this->addQuotes($target_name));
$result = $this->_query($query);
$tmp = $this->_fetch($result);
if(!$tmp) return false;
return true;
}
$buff = new Output();
$buff->total_count = $total_count;
$buff->total_page = $total_page;
$buff->page = $page;
$buff->data = $data;
/**
* @brief xml 받아서 테이블을 생성
**/
function createTableByXml($xml_doc) {
return $this->_createTable($xml_doc);
}
require_once('./classes/page/PageHandler.class.php');
$buff->page_navigation = new PageHandler($total_count, $total_page, $page, $navigation->page_count);
return $buff;
}/*}}}*/
}
/**
* @brief xml 받아서 테이블을 생성
**/
function createTableByXmlFile($file_name) {
if(!file_exists($file_name)) return;
// xml 파일을 읽음
$buff = FileHandler::readFile($file_name);
return $this->_createTable($buff);
}
/**
* @brief schema xml을 이용하여 create table query생성
*
* type : number, varchar, text, char, date, \n
* opt : notnull, default, size\n
* index : primary key, index, unique\n
**/
function _createTable($xml_doc) {
// xml parsing
$oXml = new XmlParser();
$xml_obj = $oXml->parse($xml_doc);
// 테이블 생성 schema 작성
$table_name = $xml_obj->table->attrs->name;
if($this->isTableExists($table_name)) return;
$table_name = $this->prefix.$table_name;
if(!is_array($xml_obj->table->column)) $columns[] = $xml_obj->table->column;
else $columns = $xml_obj->table->column;
foreach($columns as $column) {
$name = $column->attrs->name;
$type = $column->attrs->type;
$size = $column->attrs->size;
$notnull = $column->attrs->notnull;
$primary_key = $column->attrs->primary_key;
$index = $column->attrs->index;
$unique = $column->attrs->unique;
$default = $column->attrs->default;
$auto_increment = $column->attrs->auto_increment;
$column_schema[] = sprintf('`%s` %s%s %s %s %s',
$name,
$this->column_type[$type],
$size?'('.$size.')':'',
$default?"default '".$default."'":'',
$notnull?'not null':'',
$auto_increment?'auto_increment':''
);
if($primary_key) $primary_list[] = $name;
else if($unique) $unique_list[$unique][] = $name;
else if($index) $index_list[$index][] = $name;
}
if(count($primary_list)) {
$column_schema[] = sprintf("primary key (%s)", '`'.implode($primary_list,'`,`').'`');
}
if(count($unique_list)) {
foreach($unique_list as $key => $val) {
$column_schema[] = sprintf("unique %s (%s)", $key, '`'.implode($val,'`,`').'`');
}
}
if(count($index_list)) {
foreach($index_list as $key => $val) {
$column_schema[] = sprintf("index %s (%s)", $key, '`'.implode($val,'`,`').'`');
}
}
$schema = sprintf('create table `%s` (%s%s);', $this->addQuotes($table_name), "\n", implode($column_schema,",\n"));
$output = $this->_query($schema);
if(!$output) return false;
}
/**
* @brief 테이블 삭제
**/
function dropTable($target_name) {
$query = sprintf('drop table `%s%s`;', $this->prefix, $this->addQuotes($target_name));
$this->_query($query);
}
/**
* @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);
}
/**
* @brief 테이블을 비움
**/
function truncateTable($target_name) {
$query = sprintf("truncate table `%s%s`;", $this->prefix, $this->addQuotes($target_name));
$this->_query($query);
}
/**
* @brief 테이블 데이터 Dump
*
* @todo 아직 미구현
**/
function dumpTable($target_name) {
}
/**
* @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).'\'';
}
$query = sprintf("insert into `%s%s` (%s) values (%s);", $this->prefix, $table, '`'.implode('`,`',$key_list).'`', implode(',', $val_list));
return $this->_query($query);
}
/**
* @brief updateAct 처리
**/
function _executeUpdateAct($tables, $column, $condition, $pass_quotes) {
$table = array_pop($tables);
foreach($column as $key => $val) {
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));
}
if(!count($update_list)) return;
$update_query = implode(',',$update_list);
if($condition) $condition = ' where '.$condition;
$query = sprintf("update `%s%s` set %s %s;", $this->prefix, $table, $update_query, $condition);
return $this->_query($query);
}
/**
* @brief deleteAct 처리
**/
function _executeDeleteAct($tables, $condition, $pass_quotes) {
$table = array_pop($tables);
if($condition) $condition = ' where '.$condition;
$query = sprintf("delete from `%s%s` %s;", $this->prefix, $table, $condition);
return $this->_query($query);
}
/**
* @brief selectAct 처리
*
* 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);
}
$table = implode(',',$table_list);
if(!$column) $columns = '*';
else {
foreach($invert_columns as $key => $val) {
$column_list[] = sprintf('%s as %s',$val, $key);
}
$columns = implode(',', $column_list);
}
if($condition) $condition = ' where '.$condition;
if($navigation->list_count) return $this->_getNavigationData($table, $columns, $condition, $navigation);
$query = sprintf("select %s from %s %s", $columns, $table, $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(count($index_list)) $query .= ' order by '.implode(',',$index_list);
}
$result = $this->_query($query);
if($this->errno!=0) return;
$data = $this->_fetch($result);
$buff = new Output();
$buff->data = $data;
return $buff;
}
/**
* @brief query xml에 navigation 정보가 있을 경우 페이징 관련 작업을 처리한다
*
* 그닥 좋지는 않은 구조이지만 편리하다.. -_-;
**/
function _getNavigationData($table, $columns, $condition, $navigation) {
// 전체 개수를 구함
$count_query = sprintf("select count(*) as count from %s %s", $table, $condition);
$result = $this->_query($count_query);
$count_output = $this->_fetch($result);
$total_count = (int)$count_output->count;
// 전체 페이지를 구함
$total_page = (int)(($total_count-1)/$navigation->list_count) +1;
// 페이지 변수를 체크
if($navigation->page > $total_page) $page = $navigation->page;
else $page = $navigation->page;
$start_count = ($page-1)*$navigation->list_count;
foreach($navigation->index as $index_obj) {
$index_list[] = sprintf('%s %s', $index_obj[0], $index_obj[1]);
}
$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);
$result = $this->_query($query);
if($this->errno!=0) return;
$virtual_no = $total_count - ($page-1)*$navigation->list_count;
while($tmp = mysql_fetch_object($result)) {
$data[$virtual_no--] = $tmp;
}
$buff = new Output();
$buff->total_count = $total_count;
$buff->total_page = $total_page;
$buff->page = $page;
$buff->data = $data;
require_once('./classes/page/PageHandler.class.php');
$buff->page_navigation = new PageHandler($total_count, $total_page, $page, $navigation->page_count);
return $buff;
}
}
?>