diff --git a/classes/db/DBMssql.class.php b/classes/db/DBMssql.class.php index 1d1668f7c..27c541db9 100644 --- a/classes/db/DBMssql.class.php +++ b/classes/db/DBMssql.class.php @@ -1,737 +1,795 @@ 'bigint', + 'number' => 'int', + 'varchar' => 'varchar', + 'char' => 'char', + 'text' => 'text', + 'bigtext' => 'text', + 'date' => 'varchar(14)', + 'float' => 'float', + ); - /** - * prefix of XE tables(One more XE can be installed on a single DB) - * @var string - */ - var $prefix = 'xe'; - var $param = array(); - var $comment_syntax = '/* %s */'; + /** + * Constructor + * @return void + */ + function DBMssql() + { + $this->_setDBInfo(); + $this->_connect(); + } - /** - * column type used in mssql - * - * column_type should be replaced for each DBMS's type - * becasue it uses commonly defined type in the schema/query xml - * @var array - */ - var $column_type = array( - 'bignumber' => 'bigint', - 'number' => 'int', - 'varchar' => 'varchar', - 'char' => 'char', - 'text' => 'text', - 'bigtext' => 'text', - 'date' => 'varchar(14)', - 'float' => 'float', - ); + /** + * Create an instance of this class + * @return DBMssql return DBMssql object instance + */ + function create() + { + return new DBMssql; + } - /** - * Constructor - * @return void - */ - function DBMssql() { - $this->_setDBInfo(); - $this->_connect(); - } + /** + * Return if supportable + * Check 'sqlsrv' extension loaded. + * @return boolean + */ + function isSupported() + { + if (!extension_loaded("sqlsrv")) return false; + return true; + } - /** - * Create an instance of this class - * @return DBMssql return DBMssql object instance - */ - function create() + /** + * DB Connect + * this method is private + * @param array $connection connection's value is db_hostname, db_database, db_userid, db_password + * @return resource + */ + function __connect($connection) + { + //sqlsrv_configure( 'WarningsReturnAsErrors', 0 ); + //sqlsrv_configure( 'LogSeverity', SQLSRV_LOG_SEVERITY_ALL ); + //sqlsrv_configure( 'LogSubsystems', SQLSRV_LOG_SYSTEM_ALL ); + $result = @sqlsrv_connect($connection["db_hostname"], array('Database' => $connection["db_database"], 'UID' => $connection["db_userid"], 'PWD' => $connection["db_password"])); + + if(!$result) { - return new DBMssql; + $errors = print_r(sqlsrv_errors(), true); + $this->setError (-1, 'database connect fail' . PHP_EOL . $errors); + return; + } + return $result; + } + + /** + * DB disconnection + * this method is private + * @param resource $connection + * @return void + */ + function _close($connection) + { + $this->commit(); + sqlsrv_close($connection); + } + + /** + * Handles quatation of the string variables from the query + * @todo See what to do about this + * @param string $string + * @return string + */ + function addQuotes($string) + { + if(version_compare(PHP_VERSION, "5.9.0", "<") && get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$string)); + //if(!is_numeric($string)) $string = str_replace("'","''",$string); + + return $string; + } + + /** + * DB transaction start + * this method is private + * @return boolean + */ + function _begin() + { + $connection = $this->_getConnection('master'); + if(sqlsrv_begin_transaction($connection) === false) return; + return true; + } + + /** + * DB transaction rollback + * this method is private + * @return boolean + */ + function _rollback() + { + $connection = $this->_getConnection('master'); + sqlsrv_rollback($connection); + return true; + } + + /** + * DB transaction commit + * this method is private + * @return boolean + */ + function _commit() + { + $connection = $this->_getConnection('master'); + sqlsrv_commit($connection); + return true; + } + + /** + * Execute the query + * this method is private + * @param string $query + * @param resource $connection + * @return resource|boolean Returns a statement resource on success and FALSE if an error occurred. + */ + function __query($query, $connection) + { + $_param = array(); + + if(count($this->param)) + { + foreach($this->param as $k => $o) + { + if($o->isColumnName()) continue; + if($o->getType() == 'number') + { + $value = $o->getUnescapedValue(); + if(is_array($value)) $_param = array_merge($_param, $value); + else $_param[] = $o->getUnescapedValue(); + } + else + { + $value = $o->getUnescapedValue(); + if(is_array($value)) + { + foreach($value as $v) + $_param[] = array($v, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STRING('utf-8')); + } + else $_param[] = array($value, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STRING('utf-8')); + } + } } - /** - * Return if supportable - * Check 'sqlsrv' extension loaded. - * @return boolean - */ - function isSupported() { - if (!extension_loaded("sqlsrv")) return false; - return true; - } + // Run the query statement + $result = false; + if(count($_param)) + { + $args = $this->_getParametersByReference($_param); + $stmt = sqlsrv_prepare($connection, $query, $args); + } + else + { + $stmt = sqlsrv_prepare($connection, $query); + } - /** - * DB Connect - * this method is private - * @param array $connection connection's value is db_hostname, db_database, db_userid, db_password - * @return resource - */ - function __connect($connection) { - //sqlsrv_configure( 'WarningsReturnAsErrors', 0 ); - //sqlsrv_configure( 'LogSeverity', SQLSRV_LOG_SEVERITY_ALL ); - //sqlsrv_configure( 'LogSubsystems', SQLSRV_LOG_SYSTEM_ALL ); - $result = @sqlsrv_connect($connection["db_hostname"], array('Database' => $connection["db_database"], 'UID' => $connection["db_userid"], 'PWD' => $connection["db_password"])); - - if(!$result) - { - $errors = print_r(sqlsrv_errors(), true); - $this->setError (-1, 'database connect fail' . PHP_EOL . $errors); - return; - } - return $result; - } - - /** - * DB disconnection - * this method is private - * @param resource $connection - * @return void - */ - function _close($connection) { - $this->commit(); - sqlsrv_close($connection); - } - - /** - * Handles quatation of the string variables from the query - * @todo See what to do about this - * @param string $string - * @return string - */ - function addQuotes($string) { - if(version_compare(PHP_VERSION, "5.9.0", "<") && get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$string)); - //if(!is_numeric($string)) $string = str_replace("'","''",$string); - - return $string; - } - - /** - * DB transaction start - * this method is private - * @return boolean - */ - function _begin() { - $connection = $this->_getConnection('master'); - if(sqlsrv_begin_transaction($connection) === false) return; - return true; - } - - /** - * DB transaction rollback - * this method is private - * @return boolean - */ - function _rollback() { - $connection = $this->_getConnection('master'); - sqlsrv_rollback($connection); - return true; - } - - /** - * DB transaction commit - * this method is private - * @return boolean - */ - function _commit() { - $connection = $this->_getConnection('master'); - sqlsrv_commit($connection); - return true; - } - - /** - * Execute the query - * this method is private - * @param string $query - * @param resource $connection - * @return resource|boolean Returns a statement resource on success and FALSE if an error occurred. - */ - function __query($query, $connection) { - $_param = array(); - - if(count($this->param)){ - foreach($this->param as $k => $o){ - if($o->isColumnName()) continue; - if($o->getType() == 'number'){ - $value = $o->getUnescapedValue(); - if(is_array($value)) $_param = array_merge($_param, $value); - else $_param[] = $o->getUnescapedValue(); - }else{ - $value = $o->getUnescapedValue(); - if(is_array($value)) { - foreach($value as $v) - $_param[] = array($v, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STRING('utf-8')); - } - else $_param[] = array($value, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STRING('utf-8')); - } - } - } - - // Run the query statement + if(!$stmt) + { $result = false; - if(count($_param)){ - $args = $this->_getParametersByReference($_param); - $stmt = sqlsrv_prepare($connection, $query, $args); - }else{ - $stmt = sqlsrv_prepare($connection, $query); - } - - if(!$stmt) + } + else + { + $result = sqlsrv_execute($stmt); + } + + // Error Check + if(!$result) + $this->setError(print_r(sqlsrv_errors(),true)); + + $this->param = array(); + + return $stmt; + } + + /** + * Parameters to sqlsrv_prepare need to be references, and not literals + * Parameters are sent as an array, where each parameter can be: + * - a PHP variable (by reference) + * - a PHP array (containng param value, type and direction) -> also needs to be sent by reference + * @param array $_param + * @return array + */ + function _getParametersByReference($_param) + { + $copy = array(); $args = array(); $i = 0; + foreach($_param as $key => $value) + { + if(is_array($value)) { - $result = false; + $value_copy = $value; + $value_arg = array(); + $value_arg[] = &$value_copy[0]; + $value_arg[] = $value_copy[1]; + $value_arg[] = $value_copy[2]; } else { - $result = sqlsrv_execute($stmt); + $value_arg = $value; } - - // Error Check - if(!$result) - $this->setError(print_r(sqlsrv_errors(),true)); + $copy[$key] = $value_arg; + $args[$i++] = &$copy[$key]; + } + return $args; + } - $this->param = array(); + /** + * Fetch results + * @param resource $result + * @param int|NULL $arrayIndexEndValue + * @return array + */ + function _fetch($result, $arrayIndexEndValue = NULL) + { + $output = array(); + if(!$this->isConnected() || $this->isError() || !$result) return $output; - return $stmt; - } - - /** - * Parameters to sqlsrv_prepare need to be references, and not literals - * Parameters are sent as an array, where each parameter can be: - * - a PHP variable (by reference) - * - a PHP array (containng param value, type and direction) -> also needs to be sent by reference - * @param array $_param - * @return array - */ - function _getParametersByReference($_param) + $c = sqlsrv_num_fields($result); + $m = null; + + while(sqlsrv_fetch($result)) { - $copy = array(); $args = array(); $i = 0; - foreach($_param as $key => $value) { - if(is_array($value)) - { - $value_copy = $value; - $value_arg = array(); - $value_arg[] = &$value_copy[0]; - $value_arg[] = $value_copy[1]; - $value_arg[] = $value_copy[2]; - } - else - { - $value_arg = $value; - } - $copy[$key] = $value_arg; - $args[$i++] = &$copy[$key]; + if(!$m) $m = sqlsrv_field_metadata($result); + unset($row); + for($i=0;$i<$c;$i++) + { + $row->{$m[$i]['Name']} = sqlsrv_get_field( $result, $i, SQLSRV_PHPTYPE_STRING( 'utf-8' )); } - return $args; + if($arrayIndexEndValue) $output[$arrayIndexEndValue--] = $row; + else $output[] = $row; } - /** - * Fetch results - * @param resource $result - * @param int|NULL $arrayIndexEndValue - * @return array - */ - function _fetch($result, $arrayIndexEndValue = NULL) { - $output = array(); - if(!$this->isConnected() || $this->isError() || !$result) return $output; + if(count($output)==1) + { + if(isset($arrayIndexEndValue)) return $output; + else return $output[0]; + } + return $output; - $c = sqlsrv_num_fields($result); - $m = null; + } - while(sqlsrv_fetch($result)){ - if(!$m) $m = sqlsrv_field_metadata($result); - unset($row); - for($i=0;$i<$c;$i++){ - $row->{$m[$i]['Name']} = sqlsrv_get_field( $result, $i, SQLSRV_PHPTYPE_STRING( 'utf-8' )); - } - if($arrayIndexEndValue) $output[$arrayIndexEndValue--] = $row; - else $output[] = $row; + /** + * Return the sequence value incremented by 1 + * Auto_increment column only used in the sequence table + * @return int + */ + function getNextSequence() + { + $query = sprintf("insert into %ssequence (seq) values (ident_incr('%ssequence'))", $this->prefix, $this->prefix); + $this->_query($query); + + $query = sprintf("select ident_current('%ssequence')+1 as sequence", $this->prefix); + $result = $this->_query($query); + $tmp = $this->_fetch($result); + + + return $tmp->sequence; + } + + /** + * Check a table exists status + * @param string $target_name + * @return boolean + */ + function isTableExists($target_name) + { + $query = sprintf("select name from sysobjects where name = '%s%s' and xtype='U'", $this->prefix, $this->addQuotes($target_name)); + $result = $this->_query($query); + $tmp = $this->_fetch($result); + + if(!$tmp) return false; + return true; + } + + /** + * Add a column to the table + * @param string $table_name table name + * @param string $column_name column name + * @param string $type column type, default value is 'number' + * @param int $size column size + * @param string|int $default default value + * @param boolean $notnull not null status, default value is false + * @return void + */ + function addColumn($table_name, $column_name, $type='number', $size='', $default = '', $notnull=false) + { + if($this->isColumnExists($table_name, $column_name)) return; + $type = $this->column_type[$type]; + if(strtoupper($type)=='INTEGER') $size = ''; + + $query = sprintf("alter table %s%s add %s ", $this->prefix, $table_name, $column_name); + if($size) $query .= sprintf(" %s(%s) ", $type, $size); + else $query .= sprintf(" %s ", $type); + if($default) $query .= sprintf(" default '%s' ", $default); + if($notnull) $query .= " not null "; + + return $this->_query($query); + } + + /** + * Drop a column from the table + * @param string $table_name table name + * @param string $column_name column name + * @return void + */ + function dropColumn($table_name, $column_name) + { + if(!$this->isColumnExists($table_name, $column_name)) return; + $query = sprintf("alter table %s%s drop %s ", $this->prefix, $table_name, $column_name); + $this->_query($query); + } + + /** + * Check column exist status of the table + * @param string $table_name table name + * @param string $column_name column name + * @return boolean + */ + function isColumnExists($table_name, $column_name) + { + $query = sprintf("select syscolumns.name as name from syscolumns, sysobjects where sysobjects.name = '%s%s' and sysobjects.id = syscolumns.id and syscolumns.name = '%s'", $this->prefix, $table_name, $column_name); + $result = $this->_query($query); + if($this->isError()) return; + $tmp = $this->_fetch($result); + if(!$tmp->name) return false; + return true; + } + + /** + * Add an index to the table + * $target_columns = array(col1, col2) + * $is_unique? unique : none + * @param string $table_name table name + * @param string $index_name index name + * @param string|array $target_columns target column or columns + * @param boolean $is_unique + * @return void + */ + function addIndex($table_name, $index_name, $target_columns, $is_unique = false) + { + if($this->isIndexExists($table_name, $index_name)) return; + if(!is_array($target_columns)) $target_columns = array($target_columns); + + $query = sprintf("create %s index %s on %s%s (%s)", $is_unique?'unique':'', $index_name, $this->prefix, $table_name, implode(',',$target_columns)); + $this->_query($query); + } + + /** + * Drop an index from the table + * @param string $table_name table name + * @param string $index_name index name + * @param boolean $is_unique + * @return void + */ + function dropIndex($table_name, $index_name, $is_unique = false) + { + if(!$this->isIndexExists($table_name, $index_name)) return; + $query = sprintf("drop index %s%s.%s", $this->prefix, $table_name, $index_name); + $this->_query($query); + } + + /** + * Check index status of the table + * @param string $table_name table name + * @param string $index_name index name + * @return boolean + */ + function isIndexExists($table_name, $index_name) + { + $query = sprintf("select sysindexes.name as name from sysindexes, sysobjects where sysobjects.name = '%s%s' and sysobjects.id = sysindexes.id and sysindexes.name = '%s'", $this->prefix, $table_name, $index_name); + + $result = $this->_query($query); + if($this->isError()) return; + $tmp = $this->_fetch($result); + + if(!$tmp->name) return false; + return true; + } + + /** + * Creates a table by using xml contents + * @param string $xml_doc xml schema contents + * @return void|object + */ + function createTableByXml($xml_doc) + { + return $this->_createTable($xml_doc); + } + + /** + * Creates a table by using xml file path + * @param string $file_name xml schema file path + * @return void|object + */ + function createTableByXmlFile($file_name) + { + if(!file_exists($file_name)) return; + // read xml file + $buff = FileHandler::readFile($file_name); + return $this->_createTable($buff); + } + + /** + * Create table by using the schema xml + * + * type : number, varchar, tinytext, text, bigtext, char, date, \n + * opt : notnull, default, size\n + * index : primary key, index, unique\n + * @param string $xml_doc xml schema contents + * @return void|object + */ + function _createTable($xml_doc) + { + // xml parsing + $oXml = new XmlParser(); + $xml_obj = $oXml->parse($xml_doc); + // Create a table schema + $table_name = $xml_obj->table->attrs->name; + if($this->isTableExists($table_name)) return; + + if($table_name == 'sequence') + { + $table_name = $this->prefix.$table_name; + $query = sprintf('create table %s ( sequence int identity(1,1), seq int )', $table_name); + return $this->_query($query); + } + else + { + $table_name = $this->prefix.$table_name; + + if(!is_array($xml_obj->table->column)) $columns[] = $xml_obj->table->column; + else $columns = $xml_obj->table->column; + + $primary_list = array(); + $unique_list = array(); + $index_list = array(); + + $typeList = array('number'=>1, 'text'=>1); + 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], + !isset($typeList[$type])&&$size?'('.$size.')':'', + isset($default)?"default '".$default."'":'', + $notnull?'not null':'null', + $auto_increment?'identity(1,1)':'' + ); + + if($primary_key) $primary_list[] = $name; + else if($unique) $unique_list[$unique][] = $name; + else if($index) $index_list[$index][] = $name; } - if(count($output)==1) { - if(isset($arrayIndexEndValue)) return $output; - else return $output[0]; - } - return $output; + if(count($primary_list)) + { + $column_schema[] = sprintf("primary key (%s)", '"'.implode($primary_list,'","').'"'); + } - } + $schema = sprintf('create table [%s] (%s%s)', $this->addQuotes($table_name), "\n", implode($column_schema,",\n")); + $output = $this->_query($schema); + if(!$output) return false; - /** - * Return the sequence value incremented by 1 - * Auto_increment column only used in the sequence table - * @return int - */ - function getNextSequence() { - $query = sprintf("insert into %ssequence (seq) values (ident_incr('%ssequence'))", $this->prefix, $this->prefix); - $this->_query($query); - - $query = sprintf("select ident_current('%ssequence')+1 as sequence", $this->prefix); - $result = $this->_query($query); - $tmp = $this->_fetch($result); - - - return $tmp->sequence; - } - - /** - * Check a table exists status - * @param string $target_name - * @return boolean - */ - function isTableExists($target_name) { - $query = sprintf("select name from sysobjects where name = '%s%s' and xtype='U'", $this->prefix, $this->addQuotes($target_name)); - $result = $this->_query($query); - $tmp = $this->_fetch($result); - - if(!$tmp) return false; - return true; - } - - /** - * Add a column to the table - * @param string $table_name table name - * @param string $column_name column name - * @param string $type column type, default value is 'number' - * @param int $size column size - * @param string|int $default default value - * @param boolean $notnull not null status, default value is false - * @return void - */ - function addColumn($table_name, $column_name, $type='number', $size='', $default = '', $notnull=false) { - if($this->isColumnExists($table_name, $column_name)) return; - $type = $this->column_type[$type]; - if(strtoupper($type)=='INTEGER') $size = ''; - - $query = sprintf("alter table %s%s add %s ", $this->prefix, $table_name, $column_name); - if($size) $query .= sprintf(" %s(%s) ", $type, $size); - else $query .= sprintf(" %s ", $type); - if($default) $query .= sprintf(" default '%s' ", $default); - if($notnull) $query .= " not null "; - - return $this->_query($query); - } - - /** - * Drop a column from the table - * @param string $table_name table name - * @param string $column_name column name - * @return void - */ - function dropColumn($table_name, $column_name) { - if(!$this->isColumnExists($table_name, $column_name)) return; - $query = sprintf("alter table %s%s drop %s ", $this->prefix, $table_name, $column_name); - $this->_query($query); - } - - /** - * Check column exist status of the table - * @param string $table_name table name - * @param string $column_name column name - * @return boolean - */ - function isColumnExists($table_name, $column_name) { - $query = sprintf("select syscolumns.name as name from syscolumns, sysobjects where sysobjects.name = '%s%s' and sysobjects.id = syscolumns.id and syscolumns.name = '%s'", $this->prefix, $table_name, $column_name); - $result = $this->_query($query); - if($this->isError()) return; - $tmp = $this->_fetch($result); - if(!$tmp->name) return false; - return true; - } - - /** - * Add an index to the table - * $target_columns = array(col1, col2) - * $is_unique? unique : none - * @param string $table_name table name - * @param string $index_name index name - * @param string|array $target_columns target column or columns - * @param boolean $is_unique - * @return void - */ - function addIndex($table_name, $index_name, $target_columns, $is_unique = false) { - if($this->isIndexExists($table_name, $index_name)) return; - if(!is_array($target_columns)) $target_columns = array($target_columns); - - $query = sprintf("create %s index %s on %s%s (%s)", $is_unique?'unique':'', $index_name, $this->prefix, $table_name, implode(',',$target_columns)); - $this->_query($query); - } - - /** - * Drop an index from the table - * @param string $table_name table name - * @param string $index_name index name - * @param boolean $is_unique - * @return void - */ - function dropIndex($table_name, $index_name, $is_unique = false) { - if(!$this->isIndexExists($table_name, $index_name)) return; - $query = sprintf("drop index %s%s.%s", $this->prefix, $table_name, $index_name); - $this->_query($query); - } - - /** - * Check index status of the table - * @param string $table_name table name - * @param string $index_name index name - * @return boolean - */ - function isIndexExists($table_name, $index_name) { - $query = sprintf("select sysindexes.name as name from sysindexes, sysobjects where sysobjects.name = '%s%s' and sysobjects.id = sysindexes.id and sysindexes.name = '%s'", $this->prefix, $table_name, $index_name); - - $result = $this->_query($query); - if($this->isError()) return; - $tmp = $this->_fetch($result); - - if(!$tmp->name) return false; - return true; - } - - /** - * Creates a table by using xml contents - * @param string $xml_doc xml schema contents - * @return void|object - */ - function createTableByXml($xml_doc) { - return $this->_createTable($xml_doc); - } - - /** - * Creates a table by using xml file path - * @param string $file_name xml schema file path - * @return void|object - */ - function createTableByXmlFile($file_name) { - if(!file_exists($file_name)) return; - // read xml file - $buff = FileHandler::readFile($file_name); - return $this->_createTable($buff); - } - - /** - * Create table by using the schema xml - * - * type : number, varchar, tinytext, text, bigtext, char, date, \n - * opt : notnull, default, size\n - * index : primary key, index, unique\n - * @param string $xml_doc xml schema contents - * @return void|object - */ - function _createTable($xml_doc) { - // xml parsing - $oXml = new XmlParser(); - $xml_obj = $oXml->parse($xml_doc); - // Create a table schema - $table_name = $xml_obj->table->attrs->name; - if($this->isTableExists($table_name)) return; - - if($table_name == 'sequence') { - $table_name = $this->prefix.$table_name; - $query = sprintf('create table %s ( sequence int identity(1,1), seq int )', $table_name); - return $this->_query($query); - } else { - $table_name = $this->prefix.$table_name; - - if(!is_array($xml_obj->table->column)) $columns[] = $xml_obj->table->column; - else $columns = $xml_obj->table->column; - - $primary_list = array(); - $unique_list = array(); - $index_list = array(); - - $typeList = array('number'=>1, 'text'=>1); - 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], - !isset($typeList[$type])&&$size?'('.$size.')':'', - isset($default)?"default '".$default."'":'', - $notnull?'not null':'null', - $auto_increment?'identity(1,1)':'' - ); - - if($primary_key) $primary_list[] = $name; - else if($unique) $unique_list[$unique][] = $name; - else if($index) $index_list[$index][] = $name; - } - - if(count($primary_list)) + if(count($unique_list)) + { + foreach($unique_list as $key => $val) { - $column_schema[] = sprintf("primary key (%s)", '"'.implode($primary_list,'","').'"'); - } - - $schema = sprintf('create table [%s] (%s%s)', $this->addQuotes($table_name), "\n", implode($column_schema,",\n")); - $output = $this->_query($schema); - if(!$output) return false; + $query = sprintf("create unique index %s on %s (%s);", $key, $table_name, '['.implode('],[',$val).']'); + $this->_query($query); + } + } - if(count($unique_list)) { - foreach($unique_list as $key => $val) { - $query = sprintf("create unique index %s on %s (%s);", $key, $table_name, '['.implode('],[',$val).']'); - $this->_query($query); - } - } - - if(count($index_list)) { - foreach($index_list as $key => $val) { - $query = sprintf("create index %s on %s (%s);", $key, $table_name, '['.implode('],[',$val).']'); - $this->_query($query); - } - } - return true; - } - } - - - - /** - * Handles insertAct - * @todo Lookup _filterNumber against sql injection - see if it is still needed and how to integrate - * @param Object $queryObject - * @return resource - */ - function _executeInsertAct($queryObject) { - $query = $this->getInsertSql($queryObject, false); - $this->param = $queryObject->getArguments(); - return $this->_query($query); - } - - /** - * Handles updateAct - * @param Object $queryObject - * @return resource - */ - function _executeUpdateAct($queryObject) { - $query = $this->getUpdateSql($queryObject, false); - $this->param = $queryObject->getArguments(); - return $this->_query($query); - } - - /** - * Return update query string - * @param object $query - * @param boolean $with_values - * @param boolean $with_priority - * @return string - */ - function getUpdateSql($query, $with_values = true, $with_priority = false){ - $columnsList = $query->getUpdateString($with_values); - if($columnsList == '') return new Object(-1, "Invalid query"); - - $from = $query->getFromString($with_values); - if($from == '') return new Object(-1, "Invalid query"); - - $tables = $query->getTables(); - $alias_list = ''; - foreach($tables as $table) - $alias_list .= $table->getAlias(); - implode(',', explode(' ', $alias_list)); - - $where = $query->getWhereString($with_values); - if($where != '') $where = ' WHERE ' . $where; - - $priority = $with_priority?$query->getPriority():''; - - return "UPDATE $priority $alias_list SET $columnsList FROM ".$from.$where; - } - - /** - * Handles deleteAct - * @param Object $queryObject - * @return resource - */ - function _executeDeleteAct($queryObject) { - $query = $this->getDeleteSql($queryObject, false); - $this->param = $queryObject->getArguments(); - return $this->_query($query); - } - - /** - * Return select query string - * @param object $query - * @param boolean $with_values - * @return string - */ - function getSelectSql($query, $with_values = TRUE){ - $with_values = false; - - //$limitOffset = $query->getLimit()->getOffset(); - //if($limitOffset) - // TODO Implement Limit with offset with subquery - $limit = '';$limitCount = ''; - $limitQueryPart = $query->getLimit(); - if($limitQueryPart) - $limitCount = $limitQueryPart->getLimit(); - if($limitCount != '') $limit = 'SELECT TOP ' . $limitCount; - - $select = $query->getSelectString($with_values); - if($select == '') return new Object(-1, "Invalid query"); - if($limit != '') - $select = $limit.' '.$select; - else - $select = 'SELECT ' .$select; - - $from = $query->getFromString($with_values); - if($from == '') return new Object(-1, "Invalid query"); - $from = ' FROM '.$from; - - $where = $query->getWhereString($with_values); - if($where != '') $where = ' WHERE ' . $where; - - $groupBy = $query->getGroupByString(); - if($groupBy != '') $groupBy = ' GROUP BY ' . $groupBy; - - $orderBy = $query->getOrderByString(); - if($orderBy != '') $orderBy = ' ORDER BY ' . $orderBy; + if(count($index_list)) + { + foreach($index_list as $key => $val) + { + $query = sprintf("create index %s on %s (%s);", $key, $table_name, '['.implode('],[',$val).']'); + $this->_query($query); + } + } + return true; + } + } - return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy; - } + /** + * Handles insertAct + * @todo Lookup _filterNumber against sql injection - see if it is still needed and how to integrate + * @param Object $queryObject + * @return resource + */ + function _executeInsertAct($queryObject) + { + $query = $this->getInsertSql($queryObject, false); + $this->param = $queryObject->getArguments(); + return $this->_query($query); + } - /** - * Handle selectAct - * In order to get a list of pages easily when selecting \n - * it supports a method as navigation - * @param Object $queryObject - * @param resource $connection - * @return Object - */ - function _executeSelectAct($queryObject, $connection = null) { - $query = $this->getSelectSql($queryObject); + /** + * Handles updateAct + * @param Object $queryObject + * @return resource + */ + function _executeUpdateAct($queryObject) + { + $query = $this->getUpdateSql($queryObject, false); + $this->param = $queryObject->getArguments(); + return $this->_query($query); + } - if(strpos($query, "substr")) $query = str_replace ("substr", "substring", $query); + /** + * Return update query string + * @param object $query + * @param boolean $with_values + * @param boolean $with_priority + * @return string + */ + function getUpdateSql($query, $with_values = true, $with_priority = false) + { + $columnsList = $query->getUpdateString($with_values); + if($columnsList == '') return new Object(-1, "Invalid query"); - // TODO Decide if we continue to pass parameters like this + $from = $query->getFromString($with_values); + if($from == '') return new Object(-1, "Invalid query"); + + $tables = $query->getTables(); + $alias_list = ''; + foreach($tables as $table) + $alias_list .= $table->getAlias(); + implode(',', explode(' ', $alias_list)); + + $where = $query->getWhereString($with_values); + if($where != '') $where = ' WHERE ' . $where; + + $priority = $with_priority?$query->getPriority():''; + + return "UPDATE $priority $alias_list SET $columnsList FROM ".$from.$where; + } + + /** + * Handles deleteAct + * @param Object $queryObject + * @return resource + */ + function _executeDeleteAct($queryObject) + { + $query = $this->getDeleteSql($queryObject, false); + $this->param = $queryObject->getArguments(); + return $this->_query($query); + } + + /** + * Return select query string + * @param object $query + * @param boolean $with_values + * @return string + */ + function getSelectSql($query, $with_values = TRUE) + { + $with_values = false; + + //$limitOffset = $query->getLimit()->getOffset(); + //if($limitOffset) + // TODO Implement Limit with offset with subquery + $limit = '';$limitCount = ''; + $limitQueryPart = $query->getLimit(); + if($limitQueryPart) + $limitCount = $limitQueryPart->getLimit(); + if($limitCount != '') $limit = 'SELECT TOP ' . $limitCount; + + $select = $query->getSelectString($with_values); + if($select == '') return new Object(-1, "Invalid query"); + if($limit != '') + $select = $limit.' '.$select; + else + $select = 'SELECT ' .$select; + + $from = $query->getFromString($with_values); + if($from == '') return new Object(-1, "Invalid query"); + $from = ' FROM '.$from; + + $where = $query->getWhereString($with_values); + if($where != '') $where = ' WHERE ' . $where; + + $groupBy = $query->getGroupByString(); + if($groupBy != '') $groupBy = ' GROUP BY ' . $groupBy; + + $orderBy = $query->getOrderByString(); + if($orderBy != '') $orderBy = ' ORDER BY ' . $orderBy; + + return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy; + } + + /** + * Handle selectAct + * In order to get a list of pages easily when selecting \n + * it supports a method as navigation + * @param Object $queryObject + * @param resource $connection + * @return Object + */ + function _executeSelectAct($queryObject, $connection = null) + { + $query = $this->getSelectSql($queryObject); + + if(strpos($query, "substr")) $query = str_replace ("substr", "substring", $query); + + // TODO Decide if we continue to pass parameters like this + $this->param = $queryObject->getArguments(); + + $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; + $result = $this->_query($query, $connection); + + if ($this->isError ()) return $this->queryError($queryObject); + else return $this->queryPageLimit($queryObject, $result, $connection); + } + + /** + * Return the DBParser + * @param boolean $force + * @return DBParser + */ + function getParser($force = FALSE) + { + return new DBParser("[", "]", $this->prefix); + } + + /** + * If have a error, return error object + * @param Object $queryObject + * @return Object + */ + function queryError($queryObject) + { + $limit = $queryObject->getLimit(); + if ($limit && $limit->isPageHandler()) + { + $buff = new Object (); + $buff->total_count = 0; + $buff->total_page = 0; + $buff->page = 1; + $buff->data = array (); + $buff->page_navigation = new PageHandler (/*$total_count*/0, /*$total_page*/1, /*$page*/1, /*$page_count*/10);//default page handler values + return $buff; + } + else + return; + } + + /** + * If select query execute, return page info + * @param Object $queryObject + * @param resource $result + * @param resource $connection + * @return Object Object with page info containing + */ + function queryPageLimit($queryObject, $result, $connection) + { + $limit = $queryObject->getLimit(); + if ($limit && $limit->isPageHandler()) + { + // Total count + $temp_where = $queryObject->getWhereString(true, false); + $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString(), ($temp_where === '' ? '' : ' WHERE ' . $temp_where)); + + // Check for distinct query and if found update count query structure + $temp_select = $queryObject->getSelectString(true); + $uses_distinct = strpos(strtolower($temp_select), "distinct") !== false; + $uses_groupby = $queryObject->getGroupByString() != ''; + if($uses_distinct || $uses_groupby) + { + $count_query = sprintf('select %s %s %s %s' + , $temp_select + , 'FROM ' . $queryObject->getFromString(true) + , ($temp_where === '' ? '' : ' WHERE '. $temp_where) + , ($uses_groupby ? ' GROUP BY ' . $queryObject->getGroupByString() : '') + ); + + // If query uses grouping or distinct, count from original select + $count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query); + } + + $count_query .= (__DEBUG_QUERY__ & 1 && $queryObject->queryID) ? sprintf(' ' . $this->comment_syntax, $this->query_id) : ''; $this->param = $queryObject->getArguments(); + $result_count = $this->_query($count_query, $connection); + $count_output = $this->_fetch($result_count); + $total_count = (int) $count_output->count; - $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; - $result = $this->_query($query, $connection); + $list_count = $limit->list_count->getValue(); + if (!$list_count) + $list_count = 20; + $page_count = $limit->page_count->getValue(); + if (!$page_count) + $page_count = 10; + $page = $limit->page->getValue(); + if (!$page) + $page = 1; + // Total pages + if ($total_count) + { + $total_page = (int) (($total_count - 1) / $list_count) + 1; + } + else + $total_page = 1; - if ($this->isError ()) return $this->queryError($queryObject); - else return $this->queryPageLimit($queryObject, $result, $connection); - } - - /** - * Return the DBParser - * @param boolean $force - * @return DBParser - */ - function getParser($force = FALSE){ - return new DBParser("[", "]", $this->prefix); - } - - /** - * If have a error, return error object - * @param Object $queryObject - * @return Object - */ - function queryError($queryObject){ - $limit = $queryObject->getLimit(); - if ($limit && $limit->isPageHandler()){ - $buff = new Object (); - $buff->total_count = 0; - $buff->total_page = 0; - $buff->page = 1; - $buff->data = array (); - $buff->page_navigation = new PageHandler (/*$total_count*/0, /*$total_page*/1, /*$page*/1, /*$page_count*/10);//default page handler values - return $buff; - }else - return; - } - - /** - * If select query execute, return page info - * @param Object $queryObject - * @param resource $result - * @param resource $connection - * @return Object Object with page info containing - */ - function queryPageLimit($queryObject, $result, $connection) { - $limit = $queryObject->getLimit(); - if ($limit && $limit->isPageHandler()) { - // Total count - $temp_where = $queryObject->getWhereString(true, false); - $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString(), ($temp_where === '' ? '' : ' WHERE ' . $temp_where)); - - // Check for distinct query and if found update count query structure - $temp_select = $queryObject->getSelectString(true); - $uses_distinct = strpos(strtolower($temp_select), "distinct") !== false; - $uses_groupby = $queryObject->getGroupByString() != ''; - if($uses_distinct || $uses_groupby) { - $count_query = sprintf('select %s %s %s %s' - , $temp_select - , 'FROM ' . $queryObject->getFromString(true) - , ($temp_where === '' ? '' : ' WHERE '. $temp_where) - , ($uses_groupby ? ' GROUP BY ' . $queryObject->getGroupByString() : '') - ); - - // If query uses grouping or distinct, count from original select - $count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query); - } - - $count_query .= (__DEBUG_QUERY__ & 1 && $queryObject->queryID) ? sprintf(' ' . $this->comment_syntax, $this->query_id) : ''; - $this->param = $queryObject->getArguments(); - $result_count = $this->_query($count_query, $connection); - $count_output = $this->_fetch($result_count); - $total_count = (int) $count_output->count; - - $list_count = $limit->list_count->getValue(); - if (!$list_count) - $list_count = 20; - $page_count = $limit->page_count->getValue(); - if (!$page_count) - $page_count = 10; - $page = $limit->page->getValue(); - if (!$page) - $page = 1; - // Total pages - if ($total_count) { - $total_page = (int) (($total_count - 1) / $list_count) + 1; - } else - $total_page = 1; - - // check the page variables - if ($page > $total_page) { - // If requested page is bigger than total number of pages, return empty list - - $buff = new Object (); - $buff->total_count = $total_count; - $buff->total_page = $total_page; - $buff->page = $page; - $buff->data = array(); - $buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count); - return $buff; - } - - $start_count = ($page - 1) * $list_count; - $this->param = $queryObject->getArguments(); - $virtual_no = $total_count - $start_count; - $data = $this->_fetch($result, $virtual_no); + // check the page variables + if ($page > $total_page) + { + // If requested page is bigger than total number of pages, return empty list $buff = new Object (); $buff->total_count = $total_count; $buff->total_page = $total_page; $buff->page = $page; - $buff->data = $data; + $buff->data = array(); $buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count); - }else { - $data = $this->_fetch($result); - $buff = new Object (); - $buff->data = $data; + return $buff; } - return $buff; - } - } -?> + $start_count = ($page - 1) * $list_count; + $this->param = $queryObject->getArguments(); + $virtual_no = $total_count - $start_count; + $data = $this->_fetch($result, $virtual_no); + + $buff = new Object (); + $buff->total_count = $total_count; + $buff->total_page = $total_page; + $buff->page = $page; + $buff->data = $data; + $buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count); + } + else + { + $data = $this->_fetch($result); + $buff = new Object (); + $buff->data = $data; + } + return $buff; + } + +} +/* End of file DBMssql.class.php */ +/* Location: ./classes/db/DBMssql.class.php */ diff --git a/classes/db/DBMysql.class.php b/classes/db/DBMysql.class.php index 4166db827..3f2ff1504 100644 --- a/classes/db/DBMysql.class.php +++ b/classes/db/DBMysql.class.php @@ -9,59 +9,62 @@ * @package /classes/db * @version 0.1 */ -class DBMysql extends DB { - - /** +class DBMysql extends DB +{ + /** * prefix of a tablename (One or more XEs can be installed in a single DB) * @var string - */ - var $prefix = 'xe_'; // / < - var $comment_syntax = '/* %s */'; + */ + var $prefix = 'xe_'; // / < + var $comment_syntax = '/* %s */'; - /** - * Column type used in MySQL - * - * Becasue a common column type in schema/query xml is used for colum_type, - * it should be replaced properly for each DBMS + /** + * Column type used in MySQL + * + * Becasue a common column type in schema/query xml is used for colum_type, + * it should be replaced properly for each DBMS * @var array - */ - var $column_type = array( - 'bignumber' => 'bigint', - 'number' => 'bigint', - 'varchar' => 'varchar', - 'char' => 'char', - 'text' => 'text', - 'bigtext' => 'longtext', - 'date' => 'varchar(14)', - 'float' => 'float', - ); + */ + var $column_type = array( + 'bignumber' => 'bigint', + 'number' => 'bigint', + 'varchar' => 'varchar', + 'char' => 'char', + 'text' => 'text', + 'bigtext' => 'longtext', + 'date' => 'varchar(14)', + 'float' => 'float', + ); - /** - * Constructor + /** + * Constructor * @return void - */ - function DBMysql() { - $this->_setDBInfo(); - $this->_connect(); - } + */ + function DBMysql() + { + $this->_setDBInfo(); + $this->_connect(); + } /** * Create an instance of this class * @return DBMysql return DBMysql object instance */ - function create() { - return new DBMysql; - } + function create() + { + return new DBMysql; + } /** * Return if supportable * Check 'mysql_connect' function exists. * @return boolean */ - function isSupported() { - if(!function_exists('mysql_connect')) return false; - return true; - } + function isSupported() + { + if(!function_exists('mysql_connect')) return false; + return true; + } /** * DB Connect @@ -69,32 +72,36 @@ class DBMysql extends DB { * @param array $connection connection's value is db_hostname, db_port, db_database, db_userid, db_password * @return resource */ - function __connect($connection) { - // Ignore if no DB information exists - if (strpos($connection["db_hostname"], ':') === false && $connection["db_port"]) - $connection["db_hostname"] .= ':' . $connection["db_port"]; + function __connect($connection) + { + // Ignore if no DB information exists + if (strpos($connection["db_hostname"], ':') === false && $connection["db_port"]) + $connection["db_hostname"] .= ':' . $connection["db_port"]; - // Attempt to connect - $result = @mysql_connect($connection["db_hostname"], $connection["db_userid"], $connection["db_password"]); + // Attempt to connect + $result = @mysql_connect($connection["db_hostname"], $connection["db_userid"], $connection["db_password"]); - if(mysql_error()) { - $this->setError(mysql_errno(), mysql_error()); - return; - } - // Error appears if the version is lower than 4.1 - if(mysql_get_server_info($result)<"4.1") { - $this->setError(-1, "XE cannot be installed under the version of mysql 4.1. Current mysql version is ".mysql_get_server_info()); - return; - } - // select db - @mysql_select_db($connection["db_database"], $result); - if(mysql_error()) { - $this->setError(mysql_errno(), mysql_error()); - return; - } + if(mysql_error()) + { + $this->setError(mysql_errno(), mysql_error()); + return; + } + // Error appears if the version is lower than 4.1 + if(mysql_get_server_info($result)<"4.1") + { + $this->setError(-1, "XE cannot be installed under the version of mysql 4.1. Current mysql version is ".mysql_get_server_info()); + return; + } + // select db + @mysql_select_db($connection["db_database"], $result); + if(mysql_error()) + { + $this->setError(mysql_errno(), mysql_error()); + return; + } - return $result; - } + return $result; + } /** * If have a task after connection, add a taks in this method @@ -102,10 +109,11 @@ class DBMysql extends DB { * @param resource $connection * @return void */ - function _afterConnect($connection){ - // Set utf8 if a database is MySQL - $this->_query("set names 'utf8'", $connection); - } + function _afterConnect($connection) + { + // Set utf8 if a database is MySQL + $this->_query("set names 'utf8'", $connection); + } /** * DB disconnection @@ -113,47 +121,52 @@ class DBMysql extends DB { * @param resource $connection * @return void */ - function _close($connection) { - @mysql_close($connection); - } + function _close($connection) + { + @mysql_close($connection); + } /** * Handles quatation of the string variables from the query * @param string $string * @return string */ - function addQuotes($string) { - if(version_compare(PHP_VERSION, "5.9.0", "<") && get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$string)); - if(!is_numeric($string)) $string = @mysql_real_escape_string($string); - return $string; - } + function addQuotes($string) + { + if(version_compare(PHP_VERSION, "5.9.0", "<") && get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$string)); + if(!is_numeric($string)) $string = @mysql_real_escape_string($string); + return $string; + } /** * DB transaction start * this method is private * @return boolean */ - function _begin() { - return true; - } + function _begin() + { + return true; + } /** * DB transaction rollback * this method is private * @return boolean */ - function _rollback() { - return true; - } + function _rollback() + { + return true; + } /** * DB transaction commit * this method is private * @return boolean */ - function _commit() { - return true; - } + function _commit() + { + return true; + } /** * Execute the query @@ -162,14 +175,15 @@ class DBMysql extends DB { * @param resource $connection * @return resource */ - function __query($query, $connection) { - // Run the query statement - $result = mysql_query($query, $connection); - // Error Check - if(mysql_error($connection)) $this->setError(mysql_errno($connection), mysql_error($connection)); - // Return result - return $result; - } + function __query($query, $connection) + { + // Run the query statement + $result = mysql_query($query, $connection); + // Error Check + if(mysql_error($connection)) $this->setError(mysql_errno($connection), mysql_error($connection)); + // Return result + return $result; + } /** * Fetch the result @@ -177,37 +191,42 @@ class DBMysql extends DB { * @param int|NULL $arrayIndexEndValue * @return array */ - function _fetch($result, $arrayIndexEndValue = NULL) { - $output = array(); - if(!$this->isConnected() || $this->isError() || !$result) return $output; - while($tmp = $this->db_fetch_object($result)) { - if($arrayIndexEndValue) $output[$arrayIndexEndValue--] = $tmp; - else $output[] = $tmp; - } - if(count($output)==1){ - if(isset($arrayIndexEndValue)) return $output; - else return $output[0]; - } - $this->db_free_result($result); - return $output; - } + function _fetch($result, $arrayIndexEndValue = NULL) + { + $output = array(); + if(!$this->isConnected() || $this->isError() || !$result) return $output; + while($tmp = $this->db_fetch_object($result)) + { + if($arrayIndexEndValue) $output[$arrayIndexEndValue--] = $tmp; + else $output[] = $tmp; + } + if(count($output)==1) + { + if(isset($arrayIndexEndValue)) return $output; + else return $output[0]; + } + $this->db_free_result($result); + return $output; + } /** * Return the sequence value incremented by 1 * Auto_increment column only used in the sequence table * @return int */ - function getNextSequence() { - $query = sprintf("insert into `%ssequence` (seq) values ('0')", $this->prefix); - $this->_query($query); - $sequence = $this->db_insert_id(); - if($sequence % 10000 == 0) { - $query = sprintf("delete from `%ssequence` where seq < %d", $this->prefix, $sequence); - $this->_query($query); - } + function getNextSequence() + { + $query = sprintf("insert into `%ssequence` (seq) values ('0')", $this->prefix); + $this->_query($query); + $sequence = $this->db_insert_id(); + if($sequence % 10000 == 0) + { + $query = sprintf("delete from `%ssequence` where seq < %d", $this->prefix, $sequence); + $this->_query($query); + } - return $sequence; - } + return $sequence; + } /** * Function to obtain mysql old password(mysql only) @@ -215,26 +234,28 @@ class DBMysql extends DB { * @param string $saved_password saved password in DBMS * @return boolean */ - function isValidOldPassword($password, $saved_password) { - $query = sprintf("select password('%s') as password, old_password('%s') as old_password", $this->addQuotes($password), $this->addQuotes($password)); - $result = $this->_query($query); - $tmp = $this->_fetch($result); - if($tmp->password == $saved_password || $tmp->old_password == $saved_password) return true; - return false; - } + function isValidOldPassword($password, $saved_password) + { + $query = sprintf("select password('%s') as password, old_password('%s') as old_password", $this->addQuotes($password), $this->addQuotes($password)); + $result = $this->_query($query); + $tmp = $this->_fetch($result); + if($tmp->password == $saved_password || $tmp->old_password == $saved_password) return true; + return false; + } /** * Check a table exists status * @param string $target_name * @return boolean */ - 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; - } + 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; + } /** * Add a column to the table @@ -246,18 +267,19 @@ class DBMysql extends DB { * @param boolean $notnull not null status, default value is false * @return void */ - function addColumn($table_name, $column_name, $type='number', $size='', $default = '', $notnull=false) { - $type = $this->column_type[$type]; - if(strtoupper($type)=='INTEGER') $size = ''; + function addColumn($table_name, $column_name, $type='number', $size='', $default = '', $notnull=false) + { + $type = $this->column_type[$type]; + if(strtoupper($type)=='INTEGER') $size = ''; - $query = sprintf("alter table `%s%s` add `%s` ", $this->prefix, $table_name, $column_name); - if($size) $query .= sprintf(" %s(%s) ", $type, $size); - else $query .= sprintf(" %s ", $type); - if($default) $query .= sprintf(" default '%s' ", $default); - if($notnull) $query .= " not null "; + $query = sprintf("alter table `%s%s` add `%s` ", $this->prefix, $table_name, $column_name); + if($size) $query .= sprintf(" %s(%s) ", $type, $size); + else $query .= sprintf(" %s ", $type); + if($default) $query .= sprintf(" default '%s' ", $default); + if($notnull) $query .= " not null "; - return $this->_query($query); - } + return $this->_query($query); + } /** * Drop a column from the table @@ -265,10 +287,11 @@ class DBMysql extends DB { * @param string $column_name column name * @return void */ - function dropColumn($table_name, $column_name) { - $query = sprintf("alter table `%s%s` drop `%s` ", $this->prefix, $table_name, $column_name); - $this->_query($query); - } + function dropColumn($table_name, $column_name) + { + $query = sprintf("alter table `%s%s` drop `%s` ", $this->prefix, $table_name, $column_name); + $this->_query($query); + } /** * Check column exist status of the table @@ -276,20 +299,23 @@ class DBMysql extends DB { * @param string $column_name column name * @return boolean */ - function isColumnExists($table_name, $column_name) { - $query = sprintf("show fields from `%s%s`", $this->prefix, $table_name); - $result = $this->_query($query); - if($this->isError()) return; - $output = $this->_fetch($result); - if($output) { - $column_name = strtolower($column_name); - foreach($output as $key => $val) { - $name = strtolower($val->Field); - if($column_name == $name) return true; - } - } - return false; - } + function isColumnExists($table_name, $column_name) + { + $query = sprintf("show fields from `%s%s`", $this->prefix, $table_name); + $result = $this->_query($query); + if($this->isError()) return; + $output = $this->_fetch($result); + if($output) + { + $column_name = strtolower($column_name); + foreach($output as $key => $val) + { + $name = strtolower($val->Field); + if($column_name == $name) return true; + } + } + return false; + } /** * Add an index to the table @@ -301,12 +327,13 @@ class DBMysql extends DB { * @param boolean $is_unique * @return void */ - function addIndex($table_name, $index_name, $target_columns, $is_unique = false) { - if(!is_array($target_columns)) $target_columns = array($target_columns); + function addIndex($table_name, $index_name, $target_columns, $is_unique = false) + { + if(!is_array($target_columns)) $target_columns = array($target_columns); - $query = sprintf("alter table `%s%s` add %s index `%s` (%s);", $this->prefix, $table_name, $is_unique?'unique':'', $index_name, implode(',',$target_columns)); - $this->_query($query); - } + $query = sprintf("alter table `%s%s` add %s index `%s` (%s);", $this->prefix, $table_name, $is_unique?'unique':'', $index_name, implode(',',$target_columns)); + $this->_query($query); + } /** * Drop an index from the table @@ -315,10 +342,11 @@ class DBMysql extends DB { * @param boolean $is_unique * @return void */ - function dropIndex($table_name, $index_name, $is_unique = false) { - $query = sprintf("alter table `%s%s` drop index `%s`", $this->prefix, $table_name, $index_name); - $this->_query($query); - } + function dropIndex($table_name, $index_name, $is_unique = false) + { + $query = sprintf("alter table `%s%s` drop index `%s`", $this->prefix, $table_name, $index_name); + $this->_query($query); + } /** @@ -327,41 +355,45 @@ class DBMysql extends DB { * @param string $index_name index name * @return boolean */ - function isIndexExists($table_name, $index_name) { - //$query = sprintf("show indexes from %s%s where key_name = '%s' ", $this->prefix, $table_name, $index_name); - $query = sprintf("show indexes from `%s%s`", $this->prefix, $table_name); - $result = $this->_query($query); - if($this->isError()) return; - $output = $this->_fetch($result); - if(!$output) return; - if(!is_array($output)) $output = array($output); + function isIndexExists($table_name, $index_name) + { + //$query = sprintf("show indexes from %s%s where key_name = '%s' ", $this->prefix, $table_name, $index_name); + $query = sprintf("show indexes from `%s%s`", $this->prefix, $table_name); + $result = $this->_query($query); + if($this->isError()) return; + $output = $this->_fetch($result); + if(!$output) return; + if(!is_array($output)) $output = array($output); - for($i=0;$iKey_name == $index_name) return true; - } - return false; - } + for($i=0;$iKey_name == $index_name) return true; + } + return false; + } /** * Creates a table by using xml contents * @param string $xml_doc xml schema contents * @return void|object */ - function createTableByXml($xml_doc) { - return $this->_createTable($xml_doc); - } + function createTableByXml($xml_doc) + { + return $this->_createTable($xml_doc); + } /** * Creates a table by using xml file path * @param string $file_name xml schema file path * @return void|object */ - function createTableByXmlFile($file_name) { - if(!file_exists($file_name)) return; - // read xml file - $buff = FileHandler::readFile($file_name); - return $this->_createTable($buff); - } + function createTableByXmlFile($file_name) + { + if(!file_exists($file_name)) return; + // read xml file + $buff = FileHandler::readFile($file_name); + return $this->_createTable($buff); + } /** * Create table by using the schema xml @@ -372,68 +404,75 @@ class DBMysql extends DB { * @param string $xml_doc xml schema contents * @return void|object */ - function _createTable($xml_doc) { - // xml parsing - $oXml = new XmlParser(); - $xml_obj = $oXml->parse($xml_doc); - // Create a table schema - $table_name = $xml_obj->table->attrs->name; - if($this->isTableExists($table_name)) return; - $table_name = $this->prefix.$table_name; + function _createTable($xml_doc) + { + // xml parsing + $oXml = new XmlParser(); + $xml_obj = $oXml->parse($xml_doc); + // Create a table 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; + if(!is_array($xml_obj->table->column)) $columns[] = $xml_obj->table->column; + else $columns = $xml_obj->table->column; - $primary_list = array(); - $unique_list = array(); - $index_list = array(); + $primary_list = array(); + $unique_list = array(); + $index_list = array(); - 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; + 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.')':'', - isset($default)?"default '".$default."'":'', - $notnull?'not null':'', - $auto_increment?'auto_increment':'' - ); + $column_schema[] = sprintf('`%s` %s%s %s %s %s', + $name, + $this->column_type[$type], + $size?'('.$size.')':'', + isset($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($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($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($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,'`,`').'`'); - } - } + 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) %s;', $this->addQuotes($table_name), "\n", implode($column_schema,",\n"), "ENGINE = MYISAM 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 = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci"); - $output = $this->_query($schema); - if(!$output) return false; - } + $output = $this->_query($schema); + if(!$output) return false; + } /** * Handles insertAct @@ -441,12 +480,13 @@ class DBMysql extends DB { * @param boolean $with_values * @return resource */ - function _executeInsertAct($queryObject, $with_values = true) { - $query = $this->getInsertSql($queryObject, $with_values, true); + function _executeInsertAct($queryObject, $with_values = true) + { + $query = $this->getInsertSql($queryObject, $with_values, true); $query .= (__DEBUG_QUERY__ & 1 && $this->query_id) ? sprintf(' ' . $this->comment_syntax, $this->query_id) : ''; - if(is_a($query, 'Object')) return; - return $this->_query($query); - } + if(is_a($query, 'Object')) return; + return $this->_query($query); + } /** * Handles updateAct @@ -454,12 +494,13 @@ class DBMysql extends DB { * @param boolean $with_values * @return resource */ - function _executeUpdateAct($queryObject, $with_values = true) { - $query = $this->getUpdateSql($queryObject, $with_values, true); + function _executeUpdateAct($queryObject, $with_values = true) + { + $query = $this->getUpdateSql($queryObject, $with_values, true); $query .= (__DEBUG_QUERY__ & 1 && $this->query_id) ? sprintf(' ' . $this->comment_syntax, $this->query_id) : ''; - if(is_a($query, 'Object')) return; - return $this->_query($query); - } + if(is_a($query, 'Object')) return; + return $this->_query($query); + } /** * Handles deleteAct @@ -467,12 +508,13 @@ class DBMysql extends DB { * @param boolean $with_values * @return resource */ - function _executeDeleteAct($queryObject, $with_values = true) { - $query = $this->getDeleteSql($queryObject, $with_values, true); + function _executeDeleteAct($queryObject, $with_values = true) + { + $query = $this->getDeleteSql($queryObject, $with_values, true); $query .= (__DEBUG_QUERY__ & 1 && $this->query_id) ? sprintf(' ' . $this->comment_syntax, $this->query_id) : ''; - if(is_a($query, 'Object')) return; - return $this->_query($query); - } + if(is_a($query, 'Object')) return; + return $this->_query($query); + } /** * Handle selectAct @@ -483,27 +525,29 @@ class DBMysql extends DB { * @param boolean $with_values * @return Object */ - function _executeSelectAct($queryObject, $connection = null, $with_values = true) { - $limit = $queryObject->getLimit(); - $result = NULL; - if ($limit && $limit->isPageHandler()) - return $this->queryPageLimit($queryObject, $result, $connection, $with_values); - else { - $query = $this->getSelectSql($queryObject, $with_values); - if (is_a($query, 'Object')) - return; - $query .= (__DEBUG_QUERY__ & 1 && $queryObject->queryID) ? sprintf(' ' . $this->comment_syntax, $queryObject->queryID) : ''; + function _executeSelectAct($queryObject, $connection = null, $with_values = true) + { + $limit = $queryObject->getLimit(); + $result = NULL; + if ($limit && $limit->isPageHandler()) + return $this->queryPageLimit($queryObject, $result, $connection, $with_values); + else + { + $query = $this->getSelectSql($queryObject, $with_values); + if (is_a($query, 'Object')) + return; + $query .= (__DEBUG_QUERY__ & 1 && $queryObject->queryID) ? sprintf(' ' . $this->comment_syntax, $queryObject->queryID) : ''; - $result = $this->_query($query, $connection); - if ($this->isError()) - return $this->queryError($queryObject); + $result = $this->_query($query, $connection); + if ($this->isError()) + return $this->queryError($queryObject); - $data = $this->_fetch($result); - $buff = new Object (); - $buff->data = $data; - return $buff; - } - } + $data = $this->_fetch($result); + $buff = new Object (); + $buff->data = $data; + return $buff; + } + } /** * Get the ID generated in the last query @@ -511,59 +555,64 @@ class DBMysql extends DB { * This method use only mysql * @return int */ - function db_insert_id() - { - $connection = $this->_getConnection('master'); - return mysql_insert_id($connection); - } + function db_insert_id() + { + $connection = $this->_getConnection('master'); + return mysql_insert_id($connection); + } /** * Fetch a result row as an object * @param resource $result * @return object */ - function db_fetch_object(&$result) - { - return mysql_fetch_object($result); - } + function db_fetch_object(&$result) + { + return mysql_fetch_object($result); + } /** * Free result memory * @param resource $result * @return boolean Returns TRUE on success or FALSE on failure. */ - function db_free_result(&$result){ - return mysql_free_result($result); - } + function db_free_result(&$result) + { + return mysql_free_result($result); + } /** * Return the DBParser * @param boolean $force * @return DBParser */ - function &getParser($force = FALSE){ - $dbParser = new DBParser('`', '`', $this->prefix); - return $dbParser; - } + function &getParser($force = FALSE) + { + $dbParser = new DBParser('`', '`', $this->prefix); + return $dbParser; + } /** * If have a error, return error object * @param Object $queryObject * @return Object */ - function queryError($queryObject){ - $limit = $queryObject->getLimit(); - if ($limit && $limit->isPageHandler()){ - $buff = new Object (); - $buff->total_count = 0; - $buff->total_page = 0; - $buff->page = 1; - $buff->data = array (); - $buff->page_navigation = new PageHandler (/*$total_count*/0, /*$total_page*/1, /*$page*/1, /*$page_count*/10);//default page handler values - return $buff; - }else - return; - } + function queryError($queryObject) + { + $limit = $queryObject->getLimit(); + if ($limit && $limit->isPageHandler()) + { + $buff = new Object (); + $buff->total_count = 0; + $buff->total_page = 0; + $buff->page = 1; + $buff->data = array (); + $buff->page_navigation = new PageHandler (/*$total_count*/0, /*$total_page*/1, /*$page*/1, /*$page_count*/10);//default page handler values + return $buff; + } + else + return; + } /** * If select query execute, return page info @@ -573,77 +622,80 @@ class DBMysql extends DB { * @param boolean $with_values * @return Object Object with page info containing */ - function queryPageLimit($queryObject, $result, $connection, $with_values = true){ - $limit = $queryObject->getLimit(); - // Total count - $temp_where = $queryObject->getWhereString($with_values, false); - $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString($with_values), ($temp_where === '' ? '' : ' WHERE '. $temp_where)); + function queryPageLimit($queryObject, $result, $connection, $with_values = true) + { + $limit = $queryObject->getLimit(); + // Total count + $temp_where = $queryObject->getWhereString($with_values, false); + $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString($with_values), ($temp_where === '' ? '' : ' WHERE '. $temp_where)); - // Check for distinct query and if found update count query structure - $temp_select = $queryObject->getSelectString($with_values); - $uses_distinct = strpos(strtolower($temp_select), "distinct") !== false; - $uses_groupby = $queryObject->getGroupByString() != ''; - if($uses_distinct || $uses_groupby) { - $count_query = sprintf('select %s %s %s %s' - , $temp_select == '*' ? '1' : $temp_select - , 'FROM ' . $queryObject->getFromString($with_values) - , ($temp_where === '' ? '' : ' WHERE '. $temp_where) - , ($uses_groupby ? ' GROUP BY ' . $queryObject->getGroupByString() : '') - ); + // Check for distinct query and if found update count query structure + $temp_select = $queryObject->getSelectString($with_values); + $uses_distinct = strpos(strtolower($temp_select), "distinct") !== false; + $uses_groupby = $queryObject->getGroupByString() != ''; + if($uses_distinct || $uses_groupby) + { + $count_query = sprintf('select %s %s %s %s' + , $temp_select == '*' ? '1' : $temp_select + , 'FROM ' . $queryObject->getFromString($with_values) + , ($temp_where === '' ? '' : ' WHERE '. $temp_where) + , ($uses_groupby ? ' GROUP BY ' . $queryObject->getGroupByString() : '') + ); - // If query uses grouping or distinct, count from original select - $count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query); - } + // If query uses grouping or distinct, count from original select + $count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query); + } - $count_query .= (__DEBUG_QUERY__&1 && $queryObject->queryID)?sprintf (' '.$this->comment_syntax, $queryObject->queryID):''; - $result_count = $this->_query($count_query, $connection); - $count_output = $this->_fetch($result_count); - $total_count = (int)(isset($count_output->count) ? $count_output->count : NULL); + $count_query .= (__DEBUG_QUERY__&1 && $queryObject->queryID)?sprintf (' '.$this->comment_syntax, $queryObject->queryID):''; + $result_count = $this->_query($count_query, $connection); + $count_output = $this->_fetch($result_count); + $total_count = (int)(isset($count_output->count) ? $count_output->count : NULL); - $list_count = $limit->list_count->getValue(); - if (!$list_count) $list_count = 20; - $page_count = $limit->page_count->getValue(); - if (!$page_count) $page_count = 10; - $page = $limit->page->getValue(); - if (!$page) $page = 1; + $list_count = $limit->list_count->getValue(); + if (!$list_count) $list_count = 20; + $page_count = $limit->page_count->getValue(); + if (!$page_count) $page_count = 10; + $page = $limit->page->getValue(); + if (!$page) $page = 1; - // total pages - if ($total_count) - $total_page = (int) (($total_count - 1) / $list_count) + 1; - else - $total_page = 1; + // total pages + if ($total_count) + $total_page = (int) (($total_count - 1) / $list_count) + 1; + else + $total_page = 1; - // check the page variables - if ($page > $total_page) { - // If requested page is bigger than total number of pages, return empty list - $buff = new Object (); - $buff->total_count = $total_count; - $buff->total_page = $total_page; - $buff->page = $page; - $buff->data = array(); - $buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count); - return $buff; - } - $start_count = ($page - 1) * $list_count; + // check the page variables + if ($page > $total_page) + { + // If requested page is bigger than total number of pages, return empty list + $buff = new Object (); + $buff->total_count = $total_count; + $buff->total_page = $total_page; + $buff->page = $page; + $buff->data = array(); + $buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count); + return $buff; + } + $start_count = ($page - 1) * $list_count; - $query = $this->getSelectPageSql($queryObject, $with_values, $start_count, $list_count); + $query = $this->getSelectPageSql($queryObject, $with_values, $start_count, $list_count); - $query .= (__DEBUG_QUERY__&1 && $queryObject->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; - $result = $this->_query ($query, $connection); - if ($this->isError ()) - return $this->queryError($queryObject); + $query .= (__DEBUG_QUERY__&1 && $queryObject->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; + $result = $this->_query ($query, $connection); + if ($this->isError ()) + return $this->queryError($queryObject); - $virtual_no = $total_count - ($page - 1) * $list_count; - $data = $this->_fetch($result, $virtual_no); + $virtual_no = $total_count - ($page - 1) * $list_count; + $data = $this->_fetch($result, $virtual_no); - $buff = new Object (); - $buff->total_count = $total_count; - $buff->total_page = $total_page; - $buff->page = $page; - $buff->data = $data; - $buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count); - return $buff; - } + $buff = new Object (); + $buff->total_count = $total_count; + $buff->total_page = $total_page; + $buff->page = $page; + $buff->data = $data; + $buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count); + return $buff; + } /** * If select query execute, return paging sql @@ -653,28 +705,30 @@ class DBMysql extends DB { * @param int $list_count * @return string select paging sql */ - function getSelectPageSql($query, $with_values = true, $start_count = 0, $list_count = 0) { - $select = $query->getSelectString($with_values); - if($select == '') return new Object(-1, "Invalid query"); - $select = 'SELECT ' .$select; + function getSelectPageSql($query, $with_values = true, $start_count = 0, $list_count = 0) + { + $select = $query->getSelectString($with_values); + if($select == '') return new Object(-1, "Invalid query"); + $select = 'SELECT ' .$select; - $from = $query->getFromString($with_values); - if($from == '') return new Object(-1, "Invalid query"); - $from = ' FROM '.$from; + $from = $query->getFromString($with_values); + if($from == '') return new Object(-1, "Invalid query"); + $from = ' FROM '.$from; - $where = $query->getWhereString($with_values); - if($where != '') $where = ' WHERE ' . $where; + $where = $query->getWhereString($with_values); + if($where != '') $where = ' WHERE ' . $where; - $groupBy = $query->getGroupByString(); - if($groupBy != '') $groupBy = ' GROUP BY ' . $groupBy; + $groupBy = $query->getGroupByString(); + if($groupBy != '') $groupBy = ' GROUP BY ' . $groupBy; - $orderBy = $query->getOrderByString(); - if($orderBy != '') $orderBy = ' ORDER BY ' . $orderBy; + $orderBy = $query->getOrderByString(); + if($orderBy != '') $orderBy = ' ORDER BY ' . $orderBy; - $limit = $query->getLimitString(); - if ($limit != '') $limit = sprintf (' LIMIT %d, %d', $start_count, $list_count); + $limit = $query->getLimitString(); + if ($limit != '') $limit = sprintf (' LIMIT %d, %d', $start_count, $list_count); - return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit; - } + return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit; + } } -?> +/* End of file DBMysql.class.php */ +/* Location: ./classes/db/DBMysql.class.php */ diff --git a/classes/db/DBMysql_innodb.class.php b/classes/db/DBMysql_innodb.class.php index 9adcd58fb..c62ad709a 100644 --- a/classes/db/DBMysql_innodb.class.php +++ b/classes/db/DBMysql_innodb.class.php @@ -1,162 +1,176 @@ _setDBInfo(); + $this->_connect(); + } - /** - * Constructor - * @return void - **/ - function DBMysql_innodb() { - $this->_setDBInfo(); - $this->_connect(); - } + /** + * Create an instance of this class + * @return DBMysql_innodb return DBMysql_innodb object instance + */ + function create() + { + return new DBMysql_innodb; + } - /** - * Create an instance of this class - * @return DBMysql_innodb return DBMysql_innodb object instance - */ - function create() + /** + * DB disconnection + * this method is private + * @param resource $connection + * @return void + */ + function _close($connection) + { + $this->_query("commit", $connection); + @mysql_close($connection); + } + + /** + * DB transaction start + * this method is private + * @return boolean + */ + function _begin() + { + $connection = $this->_getConnection('master'); + $this->_query("begin", $connection); + return true; + } + + /** + * DB transaction rollback + * this method is private + * @return boolean + */ + function _rollback() + { + $connection = $this->_getConnection('master'); + $this->_query("rollback", $connection); + return true; + } + + /** + * DB transaction commit + * this method is private + * @return boolean + */ + function _commit() + { + $connection = $this->_getConnection('master'); + $this->_query("commit", $connection); + return true; + } + + /** + * Execute the query + * this method is private + * @param string $query + * @param resource $connection + * @return resource + */ + function __query($query, $connection) + { + // Run the query statement + $result = @mysql_query($query, $connection); + // Error Check + if(mysql_error($connection)) $this->setError(mysql_errno($connection), mysql_error($connection)); + // Return result + return $result; + } + + /** + * Create table by using the schema xml + * + * type : number, varchar, tinytext, text, bigtext, char, date, \n + * opt : notnull, default, size\n + * index : primary key, index, unique\n + * @param string $xml_doc xml schema contents + * @return void|object + */ + function _createTable($xml_doc) + { + // xml parsing + $oXml = new XmlParser(); + $xml_obj = $oXml->parse($xml_doc); + // Create a table 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) { - return new DBMysql_innodb; + $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.')':'', + isset($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; } - /** - * DB disconnection - * this method is private - * @param resource $connection - * @return void - */ - function _close($connection) { - $this->_query("commit", $connection); - @mysql_close($connection); - } + if(count($primary_list)) + { + $column_schema[] = sprintf("primary key (%s)", '`'.implode($primary_list,'`,`').'`'); + } - /** - * DB transaction start - * this method is private - * @return boolean - */ - function _begin() { - $connection = $this->_getConnection('master'); - $this->_query("begin", $connection); - return true; - } + if(count($unique_list)) + { + foreach($unique_list as $key => $val) + { + $column_schema[] = sprintf("unique %s (%s)", $key, '`'.implode($val,'`,`').'`'); + } + } - /** - * DB transaction rollback - * this method is private - * @return boolean - */ - function _rollback() { - $connection = $this->_getConnection('master'); - $this->_query("rollback", $connection); - return true; - } + if(count($index_list)) + { + foreach($index_list as $key => $val) + { + $column_schema[] = sprintf("index %s (%s)", $key, '`'.implode($val,'`,`').'`'); + } + } - /** - * DB transaction commit - * this method is private - * @return boolean - */ - function _commit() { - $connection = $this->_getConnection('master'); - $this->_query("commit", $connection); - return true; - } + $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"); - /** - * Execute the query - * this method is private - * @param string $query - * @param resource $connection - * @return resource - */ - function __query($query, $connection) { - // Run the query statement - $result = @mysql_query($query, $connection); - // Error Check - if(mysql_error($connection)) $this->setError(mysql_errno($connection), mysql_error($connection)); - // Return result - return $result; - } - - /** - * Create table by using the schema xml - * - * type : number, varchar, tinytext, text, bigtext, char, date, \n - * opt : notnull, default, size\n - * index : primary key, index, unique\n - * @param string $xml_doc xml schema contents - * @return void|object - */ - function _createTable($xml_doc) { - // xml parsing - $oXml = new XmlParser(); - $xml_obj = $oXml->parse($xml_doc); - // Create a table 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.')':'', - isset($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) %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; - } - } -?> + $output = $this->_query($schema); + if(!$output) return false; + } +} +/* End of file DBMysql_innodb.class.php */ +/* Location: ./classes/db/DBMysql_innodb.class.php */ diff --git a/classes/db/DBMysqli.class.php b/classes/db/DBMysqli.class.php index cb675f27b..af3b944e8 100644 --- a/classes/db/DBMysqli.class.php +++ b/classes/db/DBMysqli.class.php @@ -1,386 +1,409 @@ _setDBInfo(); + $this->_connect(); + } - /** - * Constructor - * @return void - **/ - function DBMysqli() { - $this->_setDBInfo(); - $this->_connect(); - } + /** + * Return if supportable + * Check 'mysqli_connect' function exists. + * @return boolean + */ + function isSupported() + { + if(!function_exists('mysqli_connect')) return false; + return true; + } - /** - * Return if supportable - * Check 'mysqli_connect' function exists. - * @return boolean - */ - function isSupported() { - if(!function_exists('mysqli_connect')) return false; - return true; - } + /** + * Create an instance of this class + * @return DBMysqli return DBMysqli object instance + */ + function create() + { + return new DBMysqli; + } - /** - * Create an instance of this class - * @return DBMysqli return DBMysqli object instance - */ - function create() + /** + * DB Connect + * this method is private + * @param array $connection connection's value is db_hostname, db_port, db_database, db_userid, db_password + * @return resource + */ + function __connect($connection) + { + // Attempt to connect + if ($connection["db_port"]) { - return new DBMysqli; + $result = @mysqli_connect($connection["db_hostname"] + , $connection["db_userid"] + , $connection["db_password"] + , $connection["db_database"] + , $connection["db_port"]); } + else + { + $result = @mysqli_connect($connection["db_hostname"] + , $connection["db_userid"] + , $connection["db_password"] + , $connection["db_database"]); + } + $error = mysqli_connect_errno(); + if($error) + { + $this->setError($error,mysqli_connect_error()); + return; + } + mysqli_set_charset($result,'utf8'); + return $result; + } - /** - * DB Connect - * this method is private - * @param array $connection connection's value is db_hostname, db_port, db_database, db_userid, db_password - * @return resource - */ - function __connect($connection) { - // Attempt to connect - if ($connection["db_port"]) { - $result = @mysqli_connect($connection["db_hostname"] - , $connection["db_userid"] - , $connection["db_password"] - , $connection["db_database"] - , $connection["db_port"]); - } else { - $result = @mysqli_connect($connection["db_hostname"] - , $connection["db_userid"] - , $connection["db_password"] - , $connection["db_database"]); - } - $error = mysqli_connect_errno(); - if($error) { - $this->setError($error,mysqli_connect_error()); - return; - } - mysqli_set_charset($result,'utf8'); - return $result; - } + /** + * DB disconnection + * this method is private + * @param resource $connection + * @return void + */ + function _close($connection) + { + mysqli_close($connection); + } - /** - * DB disconnection - * this method is private - * @param resource $connection - * @return void - */ - function _close($connection) { - mysqli_close($connection); - } + /** + * Handles quatation of the string variables from the query + * @param string $string + * @return string + */ + function addQuotes($string) + { + if(version_compare(PHP_VERSION, "5.9.0", "<") && get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$string)); + if(!is_numeric($string)) + { + $connection = $this->_getConnection('master'); + $string = mysqli_escape_string($connection,$string); + } + return $string; + } - /** - * Handles quatation of the string variables from the query - * @param string $string - * @return string - */ - function addQuotes($string) { - if(version_compare(PHP_VERSION, "5.9.0", "<") && get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$string)); - if(!is_numeric($string)){ - $connection = $this->_getConnection('master'); - $string = mysqli_escape_string($connection,$string); - } - return $string; - } + /** + * Execute the query + * this method is private + * @param string $query + * @param resource $connection + * @return resource + */ + function __query($query, $connection) + { + if($this->use_prepared_statements == 'Y') + { + // 1. Prepare query + $stmt = mysqli_prepare($connection, $query); + if($stmt) + { + $types = ''; + $params = array(); + $this->_prepareQueryParameters($types, $params); - /** - * Execute the query - * this method is private - * @param string $query - * @param resource $connection - * @return resource - */ - function __query($query, $connection) { - if($this->use_prepared_statements == 'Y') - { - // 1. Prepare query - $stmt = mysqli_prepare($connection, $query); - if($stmt){ - $types = ''; - $params = array(); - $this->_prepareQueryParameters($types, $params); - - if(!empty($params)) + if(!empty($params)) + { + $args[0] = $stmt; + $args[1] = $types; + + $i = 2; + foreach($params as $key => $param) { - $args[0] = $stmt; - $args[1] = $types; - - $i = 2; - foreach($params as $key => $param) { - $copy[$key] = $param; - $args[$i++] = &$copy[$key]; - } - - // 2. Bind parameters - $status = call_user_func_array('mysqli_stmt_bind_param',$args); - if(!$status) - $this->setError(-1, "Invalid arguments: $query" . mysqli_error($connection) . PHP_EOL . print_r($args, true)); + $copy[$key] = $param; + $args[$i++] = &$copy[$key]; } - - // 3. Execute query - $status = mysqli_stmt_execute($stmt); - + + // 2. Bind parameters + $status = call_user_func_array('mysqli_stmt_bind_param',$args); if(!$status) - $this->setError(-1, "Prepared statement failed: $query" . mysqli_error($connection) . PHP_EOL . print_r($args, true)); - - // Return stmt for other processing - like retrieving resultset (_fetch) - return $stmt; - // mysqli_stmt_close($stmt); + $this->setError(-1, "Invalid arguments: $query" . mysqli_error($connection) . PHP_EOL . print_r($args, true)); } - + + // 3. Execute query + $status = mysqli_stmt_execute($stmt); + + if(!$status) + $this->setError(-1, "Prepared statement failed: $query" . mysqli_error($connection) . PHP_EOL . print_r($args, true)); + + // Return stmt for other processing - like retrieving resultset (_fetch) + return $stmt; + // mysqli_stmt_close($stmt); } - // Run the query statement - $result = mysqli_query($connection,$query); - // Error Check - $error = mysqli_error($connection); - if($error){ - $this->setError(mysqli_errno($connection), $error); - } - // Return result - return $result; - } - - /** - * Before execute query, prepare statement - * this method is private - * @param string $types - * @param array $params - * @return void - */ - function _prepareQueryParameters(&$types, &$params){ - $types = ''; - $params = array(); - if(!$this->param) return; - - foreach($this->param as $k => $o){ - $value = $o->getUnescapedValue(); - $type = $o->getType(); - - // Skip column names -> this should be concatenated to query string - if($o->isColumnName()) continue; - - switch($type) + + } + // Run the query statement + $result = mysqli_query($connection,$query); + // Error Check + $error = mysqli_error($connection); + if($error) + { + $this->setError(mysqli_errno($connection), $error); + } + // Return result + return $result; + } + + /** + * Before execute query, prepare statement + * this method is private + * @param string $types + * @param array $params + * @return void + */ + function _prepareQueryParameters(&$types, &$params) + { + $types = ''; + $params = array(); + if(!$this->param) return; + + foreach($this->param as $k => $o) + { + $value = $o->getUnescapedValue(); + $type = $o->getType(); + + // Skip column names -> this should be concatenated to query string + if($o->isColumnName()) continue; + + switch($type) + { + case 'number' : + $type = 'i'; + break; + case 'varchar' : + $type = 's'; + break; + default: + $type = 's'; + } + + if(is_array($value)) + { + foreach($value as $v) { - case 'number' : - $type = 'i'; - break; - case 'varchar' : - $type = 's'; - break; - default: - $type = 's'; - } - - if(is_array($value)) - { - foreach($value as $v) - { - $params[] = $v; - $types .= $type; - } - } - else { - $params[] = $value; + $params[] = $v; $types .= $type; } - - - - } - } - - /** - * Fetch the result - * @param resource $result - * @param int|NULL $arrayIndexEndValue - * @return array - */ - function _fetch($result, $arrayIndexEndValue = NULL) { - if($this->use_prepared_statements != 'Y'){ - return parent::_fetch($result, $arrayIndexEndValue); } - $output = array(); - if(!$this->isConnected() || $this->isError() || !$result) return $output; - - // Prepared stements: bind result variable and fetch data - $stmt = $result; - $meta = mysqli_stmt_result_metadata($stmt); - $fields = mysqli_fetch_fields($meta); - - /** - * Mysqli has a bug that causes LONGTEXT columns not to get loaded - * Unless store_result is called before - * MYSQLI_TYPE for longtext is 252 - */ - $longtext_exists = false; - foreach($fields as $field) + else { - if(isset($resultArray[$field->name])) // When joined tables are used and the same column name appears twice, we should add it separately, otherwise bind_result fails - $field->name = 'repeat_' . $field->name; - - // Array passed needs to contain references, not values - $row[$field->name] = ""; - $resultArray[$field->name] = &$row[$field->name]; - - if($field->type == 252) $longtext_exists = true; + $params[] = $value; + $types .= $type; } - $resultArray = array_merge(array($stmt), $resultArray); - if($longtext_exists) - { - mysqli_stmt_store_result($stmt); - } - call_user_func_array('mysqli_stmt_bind_result', $resultArray); - $rows = array(); - while(mysqli_stmt_fetch($stmt)) - { - $resultObject = new stdClass(); - - foreach($resultArray as $key => $value) - { - if($key === 0) continue; // Skip stmt object - if(strpos($key, 'repeat_')) $key = substr($key, 6); - $resultObject->$key = $value; - } - - $rows[] = $resultObject; - } - - mysqli_stmt_close($stmt); + } + } - if($arrayIndexEndValue) - { - foreach($rows as $row) - { - $output[$arrayIndexEndValue--] = $row; - } - } - else - { - $output = $rows; - } - - if(count($output)==1){ - if(isset($arrayIndexEndValue)) return $output; - else return $output[0]; - } - - return $output; - } - - /** - * Handles insertAct - * @param Object $queryObject - * @param boolean $with_values - * @return resource - */ - function _executeInsertAct($queryObject, $with_values = false){ - if($this->use_prepared_statements != 'Y') - { - return parent::_executeInsertAct($queryObject); - } - $this->param = $queryObject->getArguments(); - $result = parent::_executeInsertAct($queryObject, $with_values); - unset($this->param); - return $result; - } - - /** - * Handles updateAct - * @param Object $queryObject - * @param boolean $with_values - * @return resource - */ - function _executeUpdateAct($queryObject, $with_values = false) { - if($this->use_prepared_statements != 'Y') - { - return parent::_executeUpdateAct($queryObject); - } - $this->param = $queryObject->getArguments(); - $result = parent::_executeUpdateAct($queryObject, $with_values); - unset($this->param); - return $result; - } - - /** - * Handles deleteAct - * @param Object $queryObject - * @param boolean $with_values - * @return resource - */ - function _executeDeleteAct($queryObject, $with_values = false) { - if($this->use_prepared_statements != 'Y') - { - return parent::_executeDeleteAct($queryObject); - } - $this->param = $queryObject->getArguments(); - $result = parent::_executeDeleteAct($queryObject, $with_values); - unset($this->param); - return $result; - } - - /** - * Handle selectAct - * In order to get a list of pages easily when selecting \n - * it supports a method as navigation - * @param Object $queryObject - * @param resource $connection - * @param boolean $with_values - * @return Object - */ - function _executeSelectAct($queryObject, $connection = null, $with_values = false) { - if($this->use_prepared_statements != 'Y') - { - return parent::_executeSelectAct($queryObject, $connection); - } - $this->param = $queryObject->getArguments(); - $result = parent::_executeSelectAct($queryObject, $connection, $with_values); - unset($this->param); - return $result; - } - - /** - * Get the ID generated in the last query - * Return next sequence from sequence table - * This method use only mysql - * @return int - */ - function db_insert_id() + /** + * Fetch the result + * @param resource $result + * @param int|NULL $arrayIndexEndValue + * @return array + */ + function _fetch($result, $arrayIndexEndValue = NULL) + { + if($this->use_prepared_statements != 'Y') { - $connection = $this->_getConnection('master'); - return mysqli_insert_id($connection); + return parent::_fetch($result, $arrayIndexEndValue); } + $output = array(); + if(!$this->isConnected() || $this->isError() || !$result) return $output; + + // Prepared stements: bind result variable and fetch data + $stmt = $result; + $meta = mysqli_stmt_result_metadata($stmt); + $fields = mysqli_fetch_fields($meta); /** - * Fetch a result row as an object - * @param resource $result - * @return object + * Mysqli has a bug that causes LONGTEXT columns not to get loaded + * Unless store_result is called before + * MYSQLI_TYPE for longtext is 252 */ - function db_fetch_object(&$result) + $longtext_exists = false; + foreach($fields as $field) { - return mysqli_fetch_object($result); + if(isset($resultArray[$field->name])) // When joined tables are used and the same column name appears twice, we should add it separately, otherwise bind_result fails + $field->name = 'repeat_' . $field->name; + + // Array passed needs to contain references, not values + $row[$field->name] = ""; + $resultArray[$field->name] = &$row[$field->name]; + + if($field->type == 252) $longtext_exists = true; } - - /** - * Free result memory - * @param resource $result - * @return boolean Returns TRUE on success or FALSE on failure. - */ - function db_free_result(&$result){ - return mysqli_free_result($result); - } - } -?> + $resultArray = array_merge(array($stmt), $resultArray); + + if($longtext_exists) + { + mysqli_stmt_store_result($stmt); + } + + call_user_func_array('mysqli_stmt_bind_result', $resultArray); + + $rows = array(); + while(mysqli_stmt_fetch($stmt)) + { + $resultObject = new stdClass(); + + foreach($resultArray as $key => $value) + { + if($key === 0) continue; // Skip stmt object + if(strpos($key, 'repeat_')) $key = substr($key, 6); + $resultObject->$key = $value; + } + + $rows[] = $resultObject; + } + + mysqli_stmt_close($stmt); + + if($arrayIndexEndValue) + { + foreach($rows as $row) + { + $output[$arrayIndexEndValue--] = $row; + } + } + else + { + $output = $rows; + } + + if(count($output)==1) + { + if(isset($arrayIndexEndValue)) return $output; + else return $output[0]; + } + + return $output; + } + + /** + * Handles insertAct + * @param Object $queryObject + * @param boolean $with_values + * @return resource + */ + function _executeInsertAct($queryObject, $with_values = false){ + if($this->use_prepared_statements != 'Y') + { + return parent::_executeInsertAct($queryObject); + } + $this->param = $queryObject->getArguments(); + $result = parent::_executeInsertAct($queryObject, $with_values); + unset($this->param); + return $result; + } + + /** + * Handles updateAct + * @param Object $queryObject + * @param boolean $with_values + * @return resource + */ + function _executeUpdateAct($queryObject, $with_values = false) { + if($this->use_prepared_statements != 'Y') + { + return parent::_executeUpdateAct($queryObject); + } + $this->param = $queryObject->getArguments(); + $result = parent::_executeUpdateAct($queryObject, $with_values); + unset($this->param); + return $result; + } + + /** + * Handles deleteAct + * @param Object $queryObject + * @param boolean $with_values + * @return resource + */ + function _executeDeleteAct($queryObject, $with_values = false) { + if($this->use_prepared_statements != 'Y') + { + return parent::_executeDeleteAct($queryObject); + } + $this->param = $queryObject->getArguments(); + $result = parent::_executeDeleteAct($queryObject, $with_values); + unset($this->param); + return $result; + } + + /** + * Handle selectAct + * In order to get a list of pages easily when selecting \n + * it supports a method as navigation + * @param Object $queryObject + * @param resource $connection + * @param boolean $with_values + * @return Object + */ + function _executeSelectAct($queryObject, $connection = null, $with_values = false) + { + if($this->use_prepared_statements != 'Y') + { + return parent::_executeSelectAct($queryObject, $connection); + } + $this->param = $queryObject->getArguments(); + $result = parent::_executeSelectAct($queryObject, $connection, $with_values); + unset($this->param); + return $result; + } + + /** + * Get the ID generated in the last query + * Return next sequence from sequence table + * This method use only mysql + * @return int + */ + function db_insert_id() + { + $connection = $this->_getConnection('master'); + return mysqli_insert_id($connection); + } + + /** + * Fetch a result row as an object + * @param resource $result + * @return object + */ + function db_fetch_object(&$result) + { + return mysqli_fetch_object($result); + } + + /** + * Free result memory + * @param resource $result + * @return boolean Returns TRUE on success or FALSE on failure. + */ + function db_free_result(&$result) + { + return mysqli_free_result($result); + } +} +/* End of file DBMysqli.class.php */ +/* Location: ./classes/db/DBMysqli.class.php */