Fixed a few MSSQL bugs - related to array query arguments and increment columns.

git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8632 201d5d3c-b55e-5fd7-737f-ddc643e51545
This commit is contained in:
ucorina 2011-07-25 15:35:43 +00:00
parent 6edd5f03a7
commit b3c75ac4db
15 changed files with 411 additions and 276 deletions

View file

@ -320,12 +320,12 @@
require_once(_XE_PATH_.'classes/db/queryparts/limit/Limit.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/limit/Limit.class.php');
require_once(_XE_PATH_.'classes/db/queryparts/Query.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/Query.class.php');
require_once(_XE_PATH_.'classes/db/queryparts/Subquery.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/Subquery.class.php');
$output = include($cache_file); $output = include($cache_file);
if( (is_a($output, 'Object') || is_subclass_of($output, 'Object')) && !$output->toBool()) return $output; if( (is_a($output, 'Object') || is_subclass_of($output, 'Object')) && !$output->toBool()) return $output;
// execute appropriate query // execute appropriate query
switch($output->getAction()) { switch($output->getAction()) {
case 'insert' : case 'insert' :
@ -346,7 +346,7 @@
$output = $this->_executeSelectAct($output); $output = $this->_executeSelectAct($output);
break; break;
} }
if($this->isError()) $output = $this->getError(); if($this->isError()) $output = $this->getError();
else if(!is_a($output, 'Object') && !is_subclass_of($output, 'Object')) $output = new Object(); else if(!is_a($output, 'Object') && !is_subclass_of($output, 'Object')) $output = new Object();
$output->add('_query', $this->query); $output->add('_query', $this->query);
@ -458,76 +458,76 @@
$query = sprintf("drop table %s%s", $this->prefix, $table_name); $query = sprintf("drop table %s%s", $this->prefix, $table_name);
$this->_query($query); $this->_query($query);
} }
function getSelectSql($query, $with_values = true){ function getSelectSql($query, $with_values = true){
$select = $query->getSelectString($with_values); $select = $query->getSelectString($with_values);
if($select == '') return new Object(-1, "Invalid query"); if($select == '') return new Object(-1, "Invalid query");
$select = 'SELECT ' .$select; $select = 'SELECT ' .$select;
$from = $query->getFromString($with_values); $from = $query->getFromString($with_values);
if($from == '') return new Object(-1, "Invalid query"); if($from == '') return new Object(-1, "Invalid query");
$from = ' FROM '.$from; $from = ' FROM '.$from;
$where = $query->getWhereString($with_values); $where = $query->getWhereString($with_values);
if($where != '') $where = ' WHERE ' . $where; if($where != '') $where = ' WHERE ' . $where;
$groupBy = $query->getGroupByString(); $groupBy = $query->getGroupByString();
if($groupBy != '') $groupBy = ' GROUP BY ' . $groupBy; if($groupBy != '') $groupBy = ' GROUP BY ' . $groupBy;
$orderBy = $query->getOrderByString(); $orderBy = $query->getOrderByString();
if($orderBy != '') $orderBy = ' ORDER BY ' . $orderBy; if($orderBy != '') $orderBy = ' ORDER BY ' . $orderBy;
$limit = $query->getLimitString(); $limit = $query->getLimitString();
if($limit != '') $limit = ' LIMIT ' . $limit; if($limit != '') $limit = ' LIMIT ' . $limit;
return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit; return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit;
} }
function getDeleteSql($query, $with_values = true){ function getDeleteSql($query, $with_values = true){
$sql = 'DELETE '; $sql = 'DELETE ';
// TODO Add support for deleting based on alias, for both simple FROM and multi table join FROM clause // TODO Add support for deleting based on alias, for both simple FROM and multi table join FROM clause
$tables = $query->getTables(); $tables = $query->getTables();
$sql .= $tables[0]->getAlias(); $sql .= $tables[0]->getAlias();
$from = $query->getFromString($with_values); $from = $query->getFromString($with_values);
if($from == '') return new Object(-1, "Invalid query"); if($from == '') return new Object(-1, "Invalid query");
$sql .= ' FROM '.$from; $sql .= ' FROM '.$from;
$where = $query->getWhereString($with_values); $where = $query->getWhereString($with_values);
if($where != '') $sql .= ' WHERE ' . $where; if($where != '') $sql .= ' WHERE ' . $where;
return $sql; return $sql;
} }
function getUpdateSql($query, $with_values = true){ function getUpdateSql($query, $with_values = true){
$columnsList = $query->getSelectString(); $columnsList = $query->getSelectString($with_values);
if($columnsList == '') return new Object(-1, "Invalid query"); if($columnsList == '') return new Object(-1, "Invalid query");
$tableName = $query->getFirstTableName(); $tableName = $query->getFirstTableName();
if($tableName == '') return new Object(-1, "Invalid query"); if($tableName == '') return new Object(-1, "Invalid query");
$where = $query->getWhereString($with_values); $where = $query->getWhereString($with_values);
if($where != '') $where = ' WHERE ' . $where; if($where != '') $where = ' WHERE ' . $where;
return "UPDATE $tableName SET $columnsList ".$where; return "UPDATE $tableName SET $columnsList ".$where;
} }
function getInsertSql($query, $with_values = true){ function getInsertSql($query, $with_values = true){
$tableName = $query->getFirstTableName(); $tableName = $query->getFirstTableName();
$values = $query->getInsertString($with_values); $values = $query->getInsertString($with_values);
return "INSERT INTO $tableName \n $values"; return "INSERT INTO $tableName \n $values";
} }
// HACK This is needed because on installation, the XmlQueryParer is used without any configured database // HACK This is needed because on installation, the XmlQueryParer is used without any configured database
// TODO Change this or make sure the query cache files created before db.config exists are deleted // TODO Change this or make sure the query cache files created before db.config exists are deleted
function getParser(){ function getParser(){
return new DBParser('"'); return new DBParser('"');
} }
// TO BE REMOVED - Used for query compare // TO BE REMOVED - Used for query compare
/** /**
* @brief returns type of column * @brief returns type of column
@ -560,7 +560,7 @@
if(strpos($value, ',') === false && strpos($value, '(') === false) return (int)$value; if(strpos($value, ',') === false && strpos($value, '(') === false) return (int)$value;
return $value; return $value;
} }
if(!is_array($value) && strpos($name, '.') !== false && strpos($value, '.') !== false) { if(!is_array($value) && strpos($name, '.') !== false && strpos($value, '.') !== false) {
list($table_name, $column_name) = explode('.', $value); list($table_name, $column_name) = explode('.', $value);
if($column_type[$column_name]) return $value; if($column_type[$column_name]) return $value;
@ -713,6 +713,6 @@
} }
return $conditions; return $conditions;
} }
} }
?> ?>

View file

@ -17,7 +17,7 @@
var $prefix = 'xe'; // / <prefix of XE tables(One more XE can be installed on a single DB) var $prefix = 'xe'; // / <prefix of XE tables(One more XE can be installed on a single DB)
var $param = array(); var $param = array();
var $comment_syntax = '/* %s */'; var $comment_syntax = '/* %s */';
/** /**
* @brief column type used in mssql * @brief column type used in mssql
* *
@ -42,7 +42,7 @@
$this->_setDBInfo(); $this->_setDBInfo();
$this->_connect(); $this->_connect();
} }
/** /**
* @brief create an instance of this class * @brief create an instance of this class
*/ */
@ -70,7 +70,7 @@
$this->password = $db_info->db_password; $this->password = $db_info->db_password;
$this->database = $db_info->db_database; $this->database = $db_info->db_database;
$this->prefix = $db_info->db_table_prefix; $this->prefix = $db_info->db_table_prefix;
if(!substr($this->prefix,-1)!='_') $this->prefix .= '_'; if(!substr($this->prefix,-1)!='_') $this->prefix .= '_';
} }
@ -85,10 +85,10 @@
//sqlsrv_configure( 'LogSeverity', SQLSRV_LOG_SEVERITY_ALL ); //sqlsrv_configure( 'LogSeverity', SQLSRV_LOG_SEVERITY_ALL );
//sqlsrv_configure( 'LogSubsystems', SQLSRV_LOG_SYSTEM_ALL ); //sqlsrv_configure( 'LogSubsystems', SQLSRV_LOG_SYSTEM_ALL );
$this->conn = sqlsrv_connect( $this->hostname, $this->conn = sqlsrv_connect( $this->hostname,
array( 'Database' => $this->database,'UID'=>$this->userid,'PWD'=>$this->password )); array( 'Database' => $this->database,'UID'=>$this->userid,'PWD'=>$this->password ));
// Check connections // Check connections
if($this->conn){ if($this->conn){
$this->is_connected = true; $this->is_connected = true;
@ -103,7 +103,7 @@
**/ **/
function close() { function close() {
if($this->is_connected == false) return; if($this->is_connected == false) return;
$this->commit(); $this->commit();
sqlsrv_close($this->conn); sqlsrv_close($this->conn);
$this->conn = null; $this->conn = null;
@ -116,7 +116,7 @@
function addQuotes($string) { function addQuotes($string) {
if(version_compare(PHP_VERSION, "5.9.0", "<") && get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$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); //if(!is_numeric($string)) $string = str_replace("'","''",$string);
return $string; return $string;
} }
@ -126,7 +126,7 @@
function begin() { function begin() {
if($this->is_connected == false || $this->transaction_started) return; if($this->is_connected == false || $this->transaction_started) return;
if(sqlsrv_begin_transaction( $this->conn ) === false) return; if(sqlsrv_begin_transaction( $this->conn ) === false) return;
$this->transaction_started = true; $this->transaction_started = true;
} }
@ -135,7 +135,7 @@
**/ **/
function rollback() { function rollback() {
if($this->is_connected == false || !$this->transaction_started) return; if($this->is_connected == false || !$this->transaction_started) return;
$this->transaction_started = false; $this->transaction_started = false;
sqlsrv_rollback( $this->conn ); sqlsrv_rollback( $this->conn );
} }
@ -145,8 +145,8 @@
**/ **/
function commit($force = false) { function commit($force = false) {
if(!$force && ($this->is_connected == false || !$this->transaction_started)) return; if(!$force && ($this->is_connected == false || !$this->transaction_started)) return;
$this->transaction_started = false; $this->transaction_started = false;
sqlsrv_commit( $this->conn ); sqlsrv_commit( $this->conn );
} }
@ -159,25 +159,37 @@
* object if a row returned \n * object if a row returned \n
* return\n * return\n
**/ **/
// TODO Support array arguments in sql server
/*
* $query_emp="select name from employee where id in (?,?,?)";
$params_emp= Array(1,2,3);
$res_emp = sqlsrv_query($conn, $query_emp, $params_emp);
*
*/
function _query($query) { function _query($query) {
if($this->is_connected == false || !$query) return; if($this->is_connected == false || !$query) return;
$_param = array(); $_param = array();
if(count($this->param)){ if(count($this->param)){
foreach($this->param as $k => $o){ foreach($this->param as $k => $o){
if($o->getType() == 'number'){ if($o->getType() == 'number'){
$_param[] = $o->getUnescapedValue(); $value = $o->getUnescapedValue();
if(is_array($value)) $_param = array_merge($_param, $value);
else $_param[] = $o->getUnescapedValue();
}else{ }else{
// TODO treat arrays here too
$value = $o->getUnescapedValue(); $value = $o->getUnescapedValue();
$_param[] = array($value, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STRING('utf-8')); $_param[] = array($value, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STRING('utf-8'));
} }
} }
} }
// Notify to start a query execution // Notify to start a query execution
$this->actStart($query); $this->actStart($query);
// Run the query statement // Run the query statement
$result = false; $result = false;
if(count($_param)){ if(count($_param)){
@ -186,9 +198,9 @@
$result = @sqlsrv_query($this->conn, $query); $result = @sqlsrv_query($this->conn, $query);
} }
// Error Check // Error Check
if(!$result) $this->setError(print_r(sqlsrv_errors(),true)); if(!$result) $this->setError(print_r(sqlsrv_errors(),true));
// Notify to complete a query execution // Notify to complete a query execution
$this->actFinish(); $this->actFinish();
$this->param = array(); $this->param = array();
@ -201,16 +213,16 @@
**/ **/
function _fetch($result, $arrayIndexEndValue = NULL) { function _fetch($result, $arrayIndexEndValue = NULL) {
if(!$this->isConnected() || $this->isError() || !$result) return; if(!$this->isConnected() || $this->isError() || !$result) return;
$c = sqlsrv_num_fields($result); $c = sqlsrv_num_fields($result);
$m = null; $m = null;
$output = array(); $output = array();
while(sqlsrv_fetch($result)){ while(sqlsrv_fetch($result)){
if(!$m) $m = sqlsrv_field_metadata($result); if(!$m) $m = sqlsrv_field_metadata($result);
unset($row); unset($row);
for($i=0;$i<$c;$i++){ for($i=0;$i<$c;$i++){
$row->{$m[$i]['Name']} = sqlsrv_get_field( $result, $i, SQLSRV_PHPTYPE_STRING( 'utf-8' )); $row->{$m[$i]['Name']} = sqlsrv_get_field( $result, $i, SQLSRV_PHPTYPE_STRING( 'utf-8' ));
} }
if($arrayIndexEndValue) $output[$arrayIndexEndValue--] = $row; if($arrayIndexEndValue) $output[$arrayIndexEndValue--] = $row;
else $output[] = $row; else $output[] = $row;
@ -230,12 +242,12 @@
function getNextSequence() { function getNextSequence() {
$query = sprintf("insert into %ssequence (seq) values (ident_incr('%ssequence'))", $this->prefix, $this->prefix); $query = sprintf("insert into %ssequence (seq) values (ident_incr('%ssequence'))", $this->prefix, $this->prefix);
$this->_query($query); $this->_query($query);
$query = sprintf("select ident_current('%ssequence')+1 as sequence", $this->prefix); $query = sprintf("select ident_current('%ssequence')+1 as sequence", $this->prefix);
$result = $this->_query($query); $result = $this->_query($query);
$tmp = $this->_fetch($result); $tmp = $this->_fetch($result);
return $tmp->sequence; return $tmp->sequence;
} }
@ -244,9 +256,9 @@
**/ **/
function isTableExists($target_name) { function isTableExists($target_name) {
$query = sprintf("select name from sysobjects where name = '%s%s' and xtype='U'", $this->prefix, $this->addQuotes($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); $result = $this->_query($query);
$tmp = $this->_fetch($result); $tmp = $this->_fetch($result);
if(!$tmp) return false; if(!$tmp) return false;
return true; return true;
} }
@ -391,11 +403,11 @@
if($unique) $unique_list[$unique][] = $name; if($unique) $unique_list[$unique][] = $name;
else if($index) $index_list[$index][] = $name; else if($index) $index_list[$index][] = $name;
} }
$schema = sprintf('create table [%s] (xe_seq int identity(1,1),%s%s)', $this->addQuotes($table_name), "\n", implode($column_schema,",\n")); $schema = sprintf('create table [%s] (xe_seq int identity(1,1),%s%s)', $this->addQuotes($table_name), "\n", implode($column_schema,",\n"));
$output = $this->_query($schema); $output = $this->_query($schema);
if(!$output) return false; if(!$output) return false;
if(count($unique_list)) { if(count($unique_list)) {
foreach($unique_list as $key => $val) { foreach($unique_list as $key => $val) {
$query = sprintf("create unique index %s on %s (%s);", $key, $table_name, '['.implode('],[',$val).']'); $query = sprintf("create unique index %s on %s (%s);", $key, $table_name, '['.implode('],[',$val).']');
@ -413,13 +425,13 @@
} }
} }
/** /**
* @brief Handle the insertAct * @brief Handle the insertAct
**/ **/
// TODO Lookup _filterNumber against sql injection - see if it is still needed and how to integrate // TODO Lookup _filterNumber against sql injection - see if it is still needed and how to integrate
function _executeInsertAct($queryObject) { function _executeInsertAct($queryObject) {
$query = $this->getInsertSql($queryObject); $query = $this->getInsertSql($queryObject, false);
$this->param = $queryObject->getArguments(); $this->param = $queryObject->getArguments();
return $this->_query($query); return $this->_query($query);
} }
@ -428,7 +440,7 @@
* @brief Handle updateAct * @brief Handle updateAct
**/ **/
function _executeUpdateAct($queryObject) { function _executeUpdateAct($queryObject) {
$query = $this->getUpdateSql($queryObject); $query = $this->getUpdateSql($queryObject, false);
$this->param = $queryObject->getArguments(); $this->param = $queryObject->getArguments();
return $this->_query($query); return $this->_query($query);
} }
@ -437,47 +449,47 @@
* @brief Handle deleteAct * @brief Handle deleteAct
**/ **/
function _executeDeleteAct($queryObject) { function _executeDeleteAct($queryObject) {
$query = $this->getDeleteSql($queryObject); $query = $this->getDeleteSql($queryObject, false);
$this->param = $queryObject->getArguments(); $this->param = $queryObject->getArguments();
return $this->_query($query); return $this->_query($query);
} }
function getSelectSql($query){ function getSelectSql($query){
$with_value = false; $with_value = false;
//$limitOffset = $query->getLimit()->getOffset(); //$limitOffset = $query->getLimit()->getOffset();
//if($limitOffset) //if($limitOffset)
// TODO Implement Limit with offset with subquery // TODO Implement Limit with offset with subquery
$limit = '';$limitCount = ''; $limit = '';$limitCount = '';
if($query->getLimit()) if($query->getLimit())
$limitCount = $query->getLimit()->getLimit(); $limitCount = $query->getLimit()->getLimit();
if($limitCount != '') $limit = 'SELECT TOP ' . $limitCount; if($limitCount != '') $limit = 'SELECT TOP ' . $limitCount;
$select = $query->getSelectString($with_values); $select = $query->getSelectString($with_values);
if($select == '') return new Object(-1, "Invalid query"); if($select == '') return new Object(-1, "Invalid query");
if($limit != '') if($limit != '')
$select = $limit.' '.$select; $select = $limit.' '.$select;
else else
$select = 'SELECT ' .$select; $select = 'SELECT ' .$select;
$from = $query->getFromString($with_values); $from = $query->getFromString($with_values);
if($from == '') return new Object(-1, "Invalid query"); if($from == '') return new Object(-1, "Invalid query");
$from = ' FROM '.$from; $from = ' FROM '.$from;
$where = $query->getWhereString($with_values); $where = $query->getWhereString($with_values);
if($where != '') $where = ' WHERE ' . $where; if($where != '') $where = ' WHERE ' . $where;
$groupBy = $query->getGroupByString(); $groupBy = $query->getGroupByString();
if($groupBy != '') $groupBy = ' GROUP BY ' . $groupBy; if($groupBy != '') $groupBy = ' GROUP BY ' . $groupBy;
$orderBy = $query->getOrderByString(); $orderBy = $query->getOrderByString();
if($orderBy != '') $orderBy = ' ORDER BY ' . $orderBy; if($orderBy != '') $orderBy = ' ORDER BY ' . $orderBy;
return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy; return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy;
} }
/** /**
* @brief Handle selectAct * @brief Handle selectAct
* *
@ -486,21 +498,21 @@
**/ **/
function _executeSelectAct($queryObject) { function _executeSelectAct($queryObject) {
$query = $this->getSelectSql($queryObject); $query = $this->getSelectSql($queryObject);
// TODO Decide if we continue to pass parameters like this // TODO Decide if we continue to pass parameters like this
$this->param = $queryObject->getArguments(); $this->param = $queryObject->getArguments();
$query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):'';
$result = $this->_query($query);
if ($this->isError ()) return $this->queryError($queryObject); $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):'';
else return $this->queryPageLimit($queryObject, $result); $result = $this->_query($query);
if ($this->isError ()) return $this->queryError($queryObject);
else return $this->queryPageLimit($queryObject, $result);
} }
function getParser(){ function getParser(){
return new DBParser("[", "]"); return new DBParser("[", "]");
} }
function queryError($queryObject){ function queryError($queryObject){
if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()){ if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()){
$buff = new Object (); $buff = new Object ();
@ -510,10 +522,10 @@
$buff->data = array (); $buff->data = array ();
$buff->page_navigation = new PageHandler (/*$total_count*/0, /*$total_page*/1, /*$page*/1, /*$page_count*/10);//default page handler values $buff->page_navigation = new PageHandler (/*$total_count*/0, /*$total_page*/1, /*$page*/1, /*$page_count*/10);//default page handler values
return $buff; return $buff;
}else }else
return; return;
} }
function queryPageLimit($queryObject, $result){ function queryPageLimit($queryObject, $result){
if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) {
// Total count // Total count
@ -526,12 +538,12 @@
$result_count = $this->_query($count_query); $result_count = $this->_query($count_query);
$count_output = $this->_fetch($result_count); $count_output = $this->_fetch($result_count);
$total_count = (int)$count_output->count; $total_count = (int)$count_output->count;
// Total pages // Total pages
if ($total_count) { if ($total_count) {
$total_page = (int) (($total_count - 1) / $queryObject->getLimit()->list_count) + 1; $total_page = (int) (($total_count - 1) / $queryObject->getLimit()->list_count) + 1;
} else $total_page = 1; } else $total_page = 1;
$virtual_no = $total_count - ($queryObject->getLimit()->page - 1) * $queryObject->getLimit()->list_count; $virtual_no = $total_count - ($queryObject->getLimit()->page - 1) * $queryObject->getLimit()->list_count;
$data = $this->_fetch($result, $virtual_no); $data = $this->_fetch($result, $virtual_no);
@ -540,15 +552,15 @@
$buff->total_page = $total_page; $buff->total_page = $total_page;
$buff->page = $queryObject->getLimit()->page; $buff->page = $queryObject->getLimit()->page;
$buff->data = $data; $buff->data = $data;
$buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page, $queryObject->getLimit()->page_count); $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page, $queryObject->getLimit()->page_count);
}else{ }else{
$data = $this->_fetch($result); $data = $this->_fetch($result);
$buff = new Object (); $buff = new Object ();
$buff->data = $data; $buff->data = $data;
} }
return $buff; return $buff;
} }
} }
return new DBMssql; return new DBMssql;

View file

@ -1,13 +1,13 @@
<?php <?php
class Condition { class Condition {
var $column_name; var $column_name;
var $argument; var $argument;
var $operation; var $operation;
var $pipe; var $pipe;
var $_value; var $_value;
function Condition($column_name, $argument, $operation, $pipe = ""){ function Condition($column_name, $argument, $operation, $pipe = ""){
$this->column_name = $column_name; $this->column_name = $column_name;
$this->argument = $argument; $this->argument = $argument;
@ -17,40 +17,50 @@
$this->_value = $argument->getValue(); $this->_value = $argument->getValue();
else if(is_a($this->argument, 'Subquery')) else if(is_a($this->argument, 'Subquery'))
$this->_value = $argument->toString(); $this->_value = $argument->toString();
else else
$this->_value = $argument; $this->_value = $argument;
} }
function hasArgument(){ function hasArgument(){
return is_a($this->argument, 'Argument'); return is_a($this->argument, 'Argument');
} }
function getArgument(){ function getArgument(){
if($this->hasArgument()) return $this->argument; if($this->hasArgument()) return $this->argument;
return null; return null;
} }
function toString($withValue = true){ function toString($withValue = true){
if(!$this->show()) return ''; if(!$this->show()) return '';
if($withValue) if($withValue)
return $this->toStringWithValue(); return $this->toStringWithValue();
return $this->toStringWithoutValue(); return $this->toStringWithoutValue();
} }
function toStringWithoutValue(){ function toStringWithoutValue(){
if($this->hasArgument()) if($this->hasArgument()){
return $this->pipe . ' ' . $this->getConditionPart("?"); $value = $this->argument->getUnescapedValue();
if(is_array($value)){
$q = '';
foreach ($value as $v) $q .= '?,';
if($q !== '') $q = substr($q, 0, -1);
$q = '(' . $q . ')';
}
else $q = '?';
return $this->pipe . ' ' . $this->getConditionPart($q);
}
else return $this->toString(); else return $this->toString();
} }
function toStringWithValue(){ function toStringWithValue(){
return $this->pipe . ' ' . $this->getConditionPart($this->_value); return $this->pipe . ' ' . $this->getConditionPart($this->_value);
} }
function setPipe($pipe){ function setPipe($pipe){
$this->pipe = $pipe; $this->pipe = $pipe;
} }
function show(){ function show(){
if($this->hasArgument() && !$this->argument->isValid()) return false; if($this->hasArgument() && !$this->argument->isValid()) return false;
if($this->hasArgument() && ($this->_value === '\'\'')) return false; if($this->hasArgument() && ($this->_value === '\'\'')) return false;
@ -75,14 +85,14 @@
if(!is_array($this->_value)) return false; if(!is_array($this->_value)) return false;
if(count($this->_value)!=2) return false; if(count($this->_value)!=2) return false;
} }
return true; return true;
} }
function getConditionPart($value) { function getConditionPart($value) {
$name = $this->column_name; $name = $this->column_name;
$operation = $this->operation; $operation = $this->operation;
switch($operation) { switch($operation) {
case 'equal' : case 'equal' :
return $name.' = '.$value; return $name.' = '.$value;
@ -123,7 +133,7 @@
return $name.' between ' . $value[0] . ' and ' . $value[1]; return $name.' between ' . $value[0] . ' and ' . $value[1];
break; break;
} }
} }
} }
?> ?>

View file

@ -1,46 +1,52 @@
<?php <?php
/** /**
* @class UpdateExpression * @class UpdateExpression
* @author Arnia Software * @author Arnia Software
* @brief * @brief
* *
*/ */
class UpdateExpression extends Expression { class UpdateExpression extends Expression {
var $argument; var $argument;
function UpdateExpression($column_name, $argument){ function UpdateExpression($column_name, $argument){
parent::Expression($column_name); parent::Expression($column_name);
$this->argument = $argument; $this->argument = $argument;
} }
function getExpression($with_value = true){ function getExpression($with_value = true){
if($with_value) if($with_value)
return $this->getExpressionWithValue(); return $this->getExpressionWithValue();
return $this->getExpressionWithoutValue(); return $this->getExpressionWithoutValue();
} }
function getExpressionWithValue(){ function getExpressionWithValue(){
$value = $this->argument->getValue(); $value = $this->argument->getValue();
$operation = $this->argument->getColumnOperation();
if(isset($operation))
return "$this->column_name = $this->column_name $operation $value";
return "$this->column_name = $value"; return "$this->column_name = $value";
} }
function getExpressionWithoutValue(){ function getExpressionWithoutValue(){
$operation = $this->argument->getColumnOperation();
if(isset($operation))
return "$this->column_name = $this->column_name $operation ?";
return "$this->column_name = ?"; return "$this->column_name = ?";
} }
function getValue(){ function getValue(){
// TODO Escape value according to column type instead of variable type // TODO Escape value according to column type instead of variable type
$value = $this->argument->getValue(); $value = $this->argument->getValue();
if(!is_numeric($value)) return "'".$value."'"; if(!is_numeric($value)) return "'".$value."'";
return $value; return $value;
} }
function show(){ function show(){
if(!$this->argument->getValue()) return false; if(!$this->argument->getValue()) return false;
return true; return true;
} }
function getArgument(){ function getArgument(){
return $this->argument; return $this->argument;
} }

View file

@ -1,52 +1,62 @@
<?php <?php
class Argument { class Argument {
var $value; var $value;
var $name; var $name;
var $type; var $type;
var $isValid; var $isValid;
var $errorMessage; var $errorMessage;
var $column_operation;
function Argument($name, $value){ function Argument($name, $value){
$this->value = $value; $this->value = $value;
$this->name = $name; $this->name = $name;
$this->isValid = true; $this->isValid = true;
} }
function getType(){ function getType(){
if(isset($this->type)) return $this->type; if(isset($this->type)) return $this->type;
if(is_string($this->value)) return 'column_name'; if(is_string($this->value)) return 'column_name';
return 'number'; return 'number';
} }
function setColumnType($value){ function setColumnType($value){
$this->type = $value; $this->type = $value;
} }
function setColumnOperation($operation){
$this->column_operation = $operation;
}
function getName(){ function getName(){
return $this->name; return $this->name;
} }
function getValue(){ function getValue(){
$value = $this->escapeValue($this->value); $value = $this->escapeValue($this->value);
return $this->toString($value); return $this->toString($value);
} }
function getColumnOperation(){
return $this->column_operation;
}
function getUnescapedValue(){ function getUnescapedValue(){
return $this->toString($this->value); return $this->value;
} }
function toString($value){ function toString($value){
if(is_array($value)) return '('.implode(',', $value).')'; if(is_array($value)) return '('.implode(',', $value).')';
return $value; return $value;
} }
function escapeValue($value){ function escapeValue($value){
if($this->getType() == 'column_name'){ if($this->getType() == 'column_name'){
$dbParser = XmlQueryParser::getDBParser(); $dbParser = XmlQueryParser::getDBParser();
return $dbParser->parseExpression($value); return $dbParser->parseExpression($value);
} }
if(!isset($value)) return null; if(!isset($value)) return null;
if(in_array($this->type, array('date', 'varchar', 'char','text', 'bigtext'))){ if(in_array($this->type, array('date', 'varchar', 'char','text', 'bigtext'))){
if(!is_array($value)) if(!is_array($value))
@ -57,32 +67,32 @@
$value[$i] = $this->_escapeStringValue($value[$i]); $value[$i] = $this->_escapeStringValue($value[$i]);
//$value[$i] = '\''.$value[$i].'\''; //$value[$i] = '\''.$value[$i].'\'';
} }
} }
return $value; return $value;
} }
function _escapeStringValue($value){ function _escapeStringValue($value){
$db = &DB::getInstance(); $db = &DB::getInstance();
$value = $db->addQuotes($value); $value = $db->addQuotes($value);
return '\''.$value.'\''; return '\''.$value.'\'';
} }
function isValid(){ function isValid(){
return $this->isValid; return $this->isValid;
} }
function getErrorMessage(){ function getErrorMessage(){
return $this->errorMessage; return $this->errorMessage;
} }
function ensureDefaultValue($default_value){ function ensureDefaultValue($default_value){
if(!isset($this->value) || $this->value == '') if(!isset($this->value) || $this->value == '')
$this->value = $default_value; $this->value = $default_value;
} }
function checkFilter($filter_type){ function checkFilter($filter_type){
if(isset($this->value) && $this->value != ''){ if(isset($this->value) && $this->value != ''){
$val = $this->value; $val = $this->value;
@ -90,7 +100,7 @@
switch($filter_type) { switch($filter_type) {
case 'email' : case 'email' :
case 'email_address' : case 'email_address' :
if(!preg_match('/^[_0-9a-z-]+(\.[_0-9a-z-]+)*@[0-9a-z-]+(\.[0-9a-z-]+)*$/is', $val)) { if(!preg_match('/^[_0-9a-z-]+(\.[_0-9a-z-]+)*@[0-9a-z-]+(\.[0-9a-z-]+)*$/is', $val)) {
$this->isValid = false; $this->isValid = false;
$this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_email, $lang->{$key} ? $lang->{$key} : $key)); $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_email, $lang->{$key} ? $lang->{$key} : $key));
} }
@ -111,7 +121,7 @@
case 'number' : case 'number' :
case 'numbers' : case 'numbers' :
if(is_array($val)) $val = join(',', $val); if(is_array($val)) $val = join(',', $val);
if(!preg_match('/^(-?)[0-9]+(,\-?[0-9]+)*$/is', $val)){ if(!preg_match('/^(-?)[0-9]+(,\-?[0-9]+)*$/is', $val)){
$this->isValid = false; $this->isValid = false;
$this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_number, $lang->{$key} ? $lang->{$key} : $key)); $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_number, $lang->{$key} ? $lang->{$key} : $key));
} }
@ -128,10 +138,10 @@
$this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_alpha_number, $lang->{$key} ? $lang->{$key} : $key)); $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_alpha_number, $lang->{$key} ? $lang->{$key} : $key));
} }
break; break;
} }
} }
} }
function checkMaxLength($length){ function checkMaxLength($length){
if($this->value && (strlen($this->value) > $length)){ if($this->value && (strlen($this->value) > $length)){
$this->isValid = false; $this->isValid = false;
@ -139,15 +149,15 @@
$this->errorMessage = new Object(-1, $lang->filter->outofrange, $lang->{$key} ? $lang->{$key} : $key); $this->errorMessage = new Object(-1, $lang->filter->outofrange, $lang->{$key} ? $lang->{$key} : $key);
} }
} }
function checkMinLength($length){ function checkMinLength($length){
if($this->value && (strlen($this->value) > $length)){ if($this->value && (strlen($this->value) > $length)){
$this->isValid = false; $this->isValid = false;
$key = $this->name; $key = $this->name;
$this->errorMessage = new Object(-1, $lang->filter->outofrange, $lang->{$key} ? $lang->{$key} : $key); $this->errorMessage = new Object(-1, $lang->filter->outofrange, $lang->{$key} ? $lang->{$key} : $key);
} }
} }
function checkNotNull(){ function checkNotNull(){
if(!isset($this->value)){ if(!isset($this->value)){
$this->isValid = false; $this->isValid = false;

View file

@ -1,35 +1,46 @@
<?php <?php
class DefaultValue { class DefaultValue {
var $column_name; var $column_name;
var $value; var $value;
var $is_sequence = false; var $is_sequence = false;
var $is_operation = false;
var $operation = '';
function DefaultValue($column_name, $value){ function DefaultValue($column_name, $value){
$this->column_name = $column_name; $dbParser = &XmlQueryParser::getDBParser();
$this->column_name = $dbParser->parseColumnName($column_name);
$this->value = $value; $this->value = $value;
$this->value = $this->_setValue(); $this->value = $this->_setValue();
} }
function isString(){ function isString(){
$str_pos = strpos($this->value, '('); $str_pos = strpos($this->value, '(');
if($str_pos===false) return true; if($str_pos===false) return true;
return false; return false;
} }
function isSequence(){ function isSequence(){
return $this->is_sequence; return $this->is_sequence;
} }
function isOperation(){
return $this->is_operation;
}
function getOperation(){
return $this->operation;
}
function _setValue(){ function _setValue(){
if(!isset($this->value)) return; if(!isset($this->value)) return;
// If value contains comma separated values and does not contain paranthesis // If value contains comma separated values and does not contain paranthesis
// -> default value is an array // -> default value is an array
if(strpos($this->value, ',') !== false && strpos($this->value, '(') === false) { if(strpos($this->value, ',') !== false && strpos($this->value, '(') === false) {
return sprintf('array(%s)', $this->value); return sprintf('array(%s)', $this->value);
} }
$str_pos = strpos($this->value, '('); $str_pos = strpos($this->value, '(');
// // TODO Replace this with parseExpression // // TODO Replace this with parseExpression
if($str_pos===false) return '\''.$this->value.'\''; if($str_pos===false) return '\''.$this->value.'\'';
@ -37,7 +48,7 @@
$func_name = substr($this->value, 0, $str_pos); $func_name = substr($this->value, 0, $str_pos);
$args = substr($this->value, $str_pos+1, strlen($value)-1); $args = substr($this->value, $str_pos+1, strlen($value)-1);
switch($func_name) { switch($func_name) {
case 'ipaddress' : case 'ipaddress' :
$val = '$_SERVER[\'REMOTE_ADDR\']'; $val = '$_SERVER[\'REMOTE_ADDR\']';
@ -54,25 +65,30 @@
break; break;
case 'plus' : case 'plus' :
$args = abs($args); $args = abs($args);
// TODO Make sure column name is escaped $this->is_operation = true;
$val = sprintf('"%s+%d"', $this->column_name, $args); $this->operation = '+';
$val = sprintf('%d', $args);
break; break;
case 'minus' : case 'minus' :
$args = abs($args); $args = abs($args);
$val = sprintf('"%s-%d"', $this->column_name, $args); $this->is_operation = true;
break; $this->operation = '-';
$val = sprintf('%d', $args);
break;
case 'multiply' : case 'multiply' :
$args = intval($args); $args = intval($args);
$val = sprintf('"%s*%d"', $this->column_name, $args); $this->is_operation = true;
$this->operation = '*';
$val = sprintf('%d', $args);
break; break;
default : default :
$val = '\'' . $this->value . '\''; $val = '\'' . $this->value . '\'';
//$val = $this->value; //$val = $this->value;
} }
return $val; return $val;
} }
function toString(){ function toString(){
return $this->value; return $this->value;
} }

View file

@ -1,4 +1,4 @@
<?php <?php
require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/DefaultValue.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/DefaultValue.class.php');
class QueryArgumentValidator { class QueryArgumentValidator {
@ -10,54 +10,59 @@
var $max_length; var $max_length;
var $validator_string; var $validator_string;
var $argument; var $argument;
function QueryArgumentValidator($tag, $argument){ function QueryArgumentValidator($tag, $argument){
$this->argument = $argument; $this->argument = $argument;
$this->argument_name = $this->argument->getArgumentName(); $this->argument_name = $this->argument->getArgumentName();
$this->default_value = $tag->attrs->default; $this->default_value = $tag->attrs->default;
$this->notnull = $tag->attrs->notnull; $this->notnull = $tag->attrs->notnull;
$this->filter = $tag->attrs->filter; $this->filter = $tag->attrs->filter;
$this->min_length = $tag->attrs->min_length; $this->min_length = $tag->attrs->min_length;
$this->max_length = $tag->attrs->max_length; $this->max_length = $tag->attrs->max_length;
} }
function toString(){ function toString(){
$validator = ''; $validator = '';
if(isset($this->default_value)){ if(isset($this->default_value)){
$this->default_value = new DefaultValue($this->argument_name, $this->default_value); $this->default_value = new DefaultValue($this->argument_name, $this->default_value);
if($this->default_value->isSequence()) if($this->default_value->isSequence())
$validator .= '$db = &DB::getInstance(); $sequence = $db->getNextSequence(); '; $validator .= '$db = &DB::getInstance(); $sequence = $db->getNextSequence(); ';
if($this->default_value->isOperation())
$validator .= sprintf("$%s_argument->setColumnOperation('%s');\n"
, $this->argument_name
, $this->default_value->getOperation()
);
$validator .= sprintf("$%s_argument->ensureDefaultValue(%s);\n" $validator .= sprintf("$%s_argument->ensureDefaultValue(%s);\n"
, $this->argument_name , $this->argument_name
, $this->default_value->toString() , $this->default_value->toString()
); );
} }
if($this->notnull){ if($this->notnull){
$validator .= sprintf("$%s_argument->checkNotNull();\n" $validator .= sprintf("$%s_argument->checkNotNull();\n"
, $this->argument_name , $this->argument_name
); );
} }
if($this->filter){ if($this->filter){
$validator .= sprintf("$%s_argument->checkFilter('%s');\n" $validator .= sprintf("$%s_argument->checkFilter('%s');\n"
, $this->argument_name , $this->argument_name
, $this->filter , $this->filter
); );
} }
if($this->min_length){ if($this->min_length){
$validator .= sprintf("$%s_argument->checkMinLength(%s);\n" $validator .= sprintf("$%s_argument->checkMinLength(%s);\n"
, $this->argument_name , $this->argument_name
, $this->min_length , $this->min_length
); );
} }
if($this->max_length){ if($this->max_length){
$validator .= sprintf("$%s_argument->checkMaxLength(%s);\n" $validator .= sprintf("$%s_argument->checkMaxLength(%s);\n"
, $this->argument_name , $this->argument_name
, $this->max_length , $this->max_length
); );
} }
return $validator; return $validator;
} }
} }

View file

@ -1,30 +1,32 @@
<?php <?php
error_reporting(E_ALL ^ E_NOTICE); error_reporting(E_ALL ^ E_NOTICE);
define('_XE_PATH_', str_replace('test-phpUnit/config/config.inc.php', '', str_replace('\\', '/', __FILE__))); define('_XE_PATH_', str_replace('test-phpUnit/config/config.inc.php', '', str_replace('\\', '/', __FILE__)));
define('_TEST_PATH_', _XE_PATH_ . 'test-phpUnit/'); define('_TEST_PATH_', _XE_PATH_ . 'test-phpUnit/');
if(!defined('__DEBUG__')) define('__DEBUG__', 4); if(!defined('__DEBUG__')) define('__DEBUG__', 4);
define('__ZBXE__', true); define('__ZBXE__', true);
require_once(_XE_PATH_.'test-phpUnit/Helper.class.php'); require_once(_XE_PATH_.'test-phpUnit/Helper.class.php');
require_once(_XE_PATH_.'test-phpUnit/QueryTester.class.php'); require_once(_XE_PATH_.'test-phpUnit/QueryTester.class.php');
require_once(_XE_PATH_.'test-phpUnit/db/DBTest.php'); require_once(_XE_PATH_.'test-phpUnit/db/DBTest.php');
require_once(_XE_PATH_.'test-phpUnit/db/CubridTest.php'); require_once(_XE_PATH_.'test-phpUnit/db/CubridTest.php');
require_once(_XE_PATH_.'test-phpUnit/db/CubridOnlineTest.php'); require_once(_XE_PATH_.'test-phpUnit/db/CubridOnlineTest.php');
require_once(_XE_PATH_.'test-phpUnit/db/MssqlTest.php');
require_once(_XE_PATH_.'config/config.inc.php'); require_once(_XE_PATH_.'test-phpUnit/db/MssqlOnlineTest.php');
// require_once(_XE_PATH_.'classes/object/Object.class.php');
// require_once(_XE_PATH_.'classes/handler/Handler.class.php'); require_once(_XE_PATH_.'config/config.inc.php');
// require_once(_XE_PATH_.'classes/context/Context.class.php'); // require_once(_XE_PATH_.'classes/object/Object.class.php');
// require_once(_XE_PATH_.'classes/handler/Handler.class.php');
// require_once(_XE_PATH_.'classes/context/Context.class.php');
// require_once(_XE_PATH_.'classes/file/FileHandler.class.php'); // require_once(_XE_PATH_.'classes/file/FileHandler.class.php');
// require_once(_XE_PATH_.'classes/xml/XmlParser.class.php'); // require_once(_XE_PATH_.'classes/xml/XmlParser.class.php');
require_once(_XE_PATH_.'classes/xml/XmlQueryParser.class.php'); require_once(_XE_PATH_.'classes/xml/XmlQueryParser.class.php');
// //
require_once(_XE_PATH_.'classes/db/DB.class.php'); require_once(_XE_PATH_.'classes/db/DB.class.php');
require_once(_XE_PATH_.'classes/db/DBCubrid.class.php'); require_once(_XE_PATH_.'classes/db/DBCubrid.class.php');
require_once(_XE_PATH_.'classes/db/DBMssql.class.php'); require_once(_XE_PATH_.'classes/db/DBMssql.class.php');
require_once(_XE_PATH_.'classes/xml/xmlquery/DBParser.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/DBParser.class.php');
require_once(_XE_PATH_.'classes/xml/xmlquery/argument/Argument.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/argument/Argument.class.php');
require_once(_XE_PATH_.'classes/xml/xmlquery/argument/ConditionArgument.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/argument/ConditionArgument.class.php');
@ -42,7 +44,7 @@
require_once(_XE_PATH_.'classes/db/queryparts/limit/Limit.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/limit/Limit.class.php');
require_once(_XE_PATH_.'classes/db/queryparts/Query.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/Query.class.php');
require_once(_XE_PATH_.'classes/db/queryparts/Subquery.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/Subquery.class.php');
require_once(_XE_PATH_.'classes/xml/xmlquery/tags/table/TableTag.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/table/TableTag.class.php');
require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/ConditionTag.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/ConditionTag.class.php');
require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php');

View file

@ -9,11 +9,11 @@
protected $backupGlobals = FALSE; protected $backupGlobals = FALSE;
protected $backupStaticAttributes = FALSE; protected $backupStaticAttributes = FALSE;
protected $preserveGlobalState = FALSE; protected $preserveGlobalState = FALSE;
/** /**
* Prepare runtime context - tell DB class that current DB is CUBRID * Prepare runtime context - tell DB class that current DB is CUBRID
*/ */
protected function setUp() { protected function setUp() {
$oContext = &Context::getInstance(); $oContext = &Context::getInstance();
$db_info->db_type = 'cubrid'; $db_info->db_type = 'cubrid';
@ -22,17 +22,12 @@
$db_info->db_userid = 'dba'; $db_info->db_userid = 'dba';
$db_info->db_password = 'arniarules'; $db_info->db_password = 'arniarules';
$db_info->db_database = 'xe15QA'; $db_info->db_database = 'xe15QA';
$db_info->db_table_prefix = 'xe'; $db_info->db_table_prefix = 'xe';
$oContext->setDbInfo($db_info);
$oContext->setDbInfo($db_info);
// remove cache dir // remove cache dir
$tmp_cache_list = FileHandler::readDir('./files','/(^cache_[0-9]+)/'); FileHandler::removeDir( _XE_PATH_ . 'files/cache');
if($tmp_cache_list){
foreach($tmp_cache_list as $tmp_dir){
if($tmp_dir) FileHandler::removeDir('./files/'.$tmp_dir);
}
}
} }
/** /**
@ -41,6 +36,6 @@
protected function tearDown() { protected function tearDown() {
unset($GLOBALS['__DB__']); unset($GLOBALS['__DB__']);
XmlQueryParser::setDBParser(null); XmlQueryParser::setDBParser(null);
} }
} }
?> ?>

View file

@ -1,16 +1,16 @@
<?php <?php
class DBTest extends PHPUnit_Framework_TestCase { class DBTest extends PHPUnit_Framework_TestCase {
function _testQuery($xml_file, $argsString, $expected, $methodName, $columnList = null){ function _testQuery($xml_file, $argsString, $expected, $methodName, $columnList = null){
echo PHP_EOL . ' ----------------------------------- ' .PHP_EOL; echo PHP_EOL . ' ----------------------------------- ' .PHP_EOL;
echo $xml_file; echo $xml_file;
echo PHP_EOL . ' ----------------------------------- ' .PHP_EOL; echo PHP_EOL . ' ----------------------------------- ' .PHP_EOL;
$tester = new QueryTester(); $tester = new QueryTester();
$outputString = $tester->getNewParserOutputString($xml_file, $argsString); $outputString = $tester->getNewParserOutputString($xml_file, $argsString);
echo $outputString; echo $outputString;
$output = eval($outputString); $output = eval($outputString);
if(!is_a($output, 'Query')){ if(!is_a($output, 'Query')){
if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat.";
}else { }else {
@ -23,8 +23,8 @@
$expected = Helper::cleanString($expected); $expected = Helper::cleanString($expected);
} }
$this->assertEquals($expected, $querySql); $this->assertEquals($expected, $querySql);
} }
function _testPreparedQuery($xml_file, $argsString, $expected, $methodName, $expectedArgs = NULL){ function _testPreparedQuery($xml_file, $argsString, $expected, $methodName, $expectedArgs = NULL){
$tester = new QueryTester(); $tester = new QueryTester();
$outputString = $tester->getNewParserOutputString($xml_file, $argsString); $outputString = $tester->getNewParserOutputString($xml_file, $argsString);
@ -34,7 +34,7 @@
if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat.";
}else { }else {
$db = &DB::getInstance(); $db = &DB::getInstance();
$querySql = $db->{$methodName}($output); $querySql = $db->{$methodName}($output, false);
$queryArguments = $output->getArguments(); $queryArguments = $output->getArguments();
// Remove whitespaces, tabs and all // Remove whitespaces, tabs and all
@ -51,14 +51,14 @@
//echo "$i: $expectedArgs[$i] vs $queryArguments[$i]->getValue()"; //echo "$i: $expectedArgs[$i] vs $queryArguments[$i]->getValue()";
$this->assertEquals($expectedArgs[$i], $queryArguments[$i]->getValue()); $this->assertEquals($expectedArgs[$i], $queryArguments[$i]->getValue());
} }
} }
function _testCachedOutput($expected, $actual){ function _testCachedOutput($expected, $actual){
$expected = Helper::cleanString($expected); $expected = Helper::cleanString($expected);
$actual = Helper::cleanString($actual); $actual = Helper::cleanString($actual);
$this->assertEquals($expected, $actual); $this->assertEquals($expected, $actual);
} }
} }

View file

@ -0,0 +1,41 @@
<?php
/**
* Base class for tests for MSSQL SQL syntax
*/
class MssqlOnlineTest extends PHPUnit_Framework_TestCase {
protected $backupGlobals = FALSE;
protected $backupStaticAttributes = FALSE;
protected $preserveGlobalState = FALSE;
/**
* Prepare runtime context - tell DB class that current DB is CUBRID
*/
protected function setUp() {
$oContext = &Context::getInstance();
$db_info->db_type = 'mssql';
$db_info->db_port = '3306';
$db_info->db_hostname = 'PHENOMII\SQL2008EXPRESS';
$db_info->db_userid = 'dba';
$db_info->db_password = 'arniarules';
$db_info->db_database = 'xe-15-db';
$db_info->db_table_prefix = 'xe';
$oContext->setDbInfo($db_info);
// remove cache dir
FileHandler::removeDir( _XE_PATH_ . 'files/cache');
}
/**
* Free resources - reset static DB and QueryParser
*/
protected function tearDown() {
unset($GLOBALS['__DB__']);
XmlQueryParser::setDBParser(null);
}
}
?>

View file

@ -6,10 +6,10 @@
function _test($xml_file, $argsString, $expected){ function _test($xml_file, $argsString, $expected){
$this->_testQuery($xml_file, $argsString, $expected, 'getUpdateSql'); $this->_testQuery($xml_file, $argsString, $expected, 'getUpdateSql');
} }
function test_module_updateModule(){ function test_module_updateModule(){
$xml_file = _XE_PATH_ . "modules/module/queries/updateModule.xml"; $xml_file = _XE_PATH_ . "modules/module/queries/updateModule.xml";
$argsString = ' $args->module_category_srl = 0; $argsString = ' $args->module_category_srl = 0;
$args->browser_title = "test"; $args->browser_title = "test";
$args->layout_srl = 0; $args->layout_srl = 0;
$args->mlayout_srl = 0; $args->mlayout_srl = 0;
@ -18,7 +18,7 @@
$args->use_mobile = ""; $args->use_mobile = "";
$args->site_srl = 0; $args->site_srl = 0;
$args->module_srl = 47374;'; $args->module_srl = 47374;';
$expected = 'UPDATE "xe_modules" $expected = 'UPDATE "xe_modules"
SET "module" = \'page\' SET "module" = \'page\'
, "mid" = \'test\' , "mid" = \'test\'
, "browser_title" = \'test\' , "browser_title" = \'test\'
@ -27,47 +27,47 @@
, "open_rss" = \'Y\' , "open_rss" = \'Y\'
, "header_text" = \'\' , "header_text" = \'\'
, "footer_text" = \'\' , "footer_text" = \'\'
, "use_mobile" = \'n\' , "use_mobile" = \'n\'
WHERE "site_srl" = 0 WHERE "site_srl" = 0
AND "module_srl" = 47374'; AND "module_srl" = 47374';
$this->_test($xml_file, $argsString, $expected); $this->_test($xml_file, $argsString, $expected);
} }
function test_module_updateMember(){ function test_member_updateLastLogin(){
$xml_file = _XE_PATH_ . "modules/member/queries/updateLastLogin.xml"; $xml_file = _XE_PATH_ . "modules/member/queries/updateLastLogin.xml";
$argsString = ' $args->member_srl = 4; $argsString = ' $args->member_srl = 4;
$args->last_login = "20110607120549";'; $args->last_login = "20110607120549";';
$expected = 'UPDATE "xe_member" SET "member_srl" = 4, "last_login" = \'20110607120549\' WHERE "member_srl" = 4'; $expected = 'UPDATE "xe_member" SET "member_srl" = 4, "last_login" = \'20110607120549\' WHERE "member_srl" = 4';
$this->_test($xml_file, $argsString, $expected); $this->_test($xml_file, $argsString, $expected);
} }
function test_module_updatePoint(){ function test_module_updatePoint(){
$xml_file = _XE_PATH_ . "modules/point/queries/updatePoint.xml"; $xml_file = _XE_PATH_ . "modules/point/queries/updatePoint.xml";
$argsString = ' $args->member_srl = 4; $argsString = ' $args->member_srl = 4;
$args->point = 105;'; $args->point = 105;';
$expected = 'UPDATE "xe_point" SET "point" = 105 WHERE "member_srl" = 4'; $expected = 'UPDATE "xe_point" SET "point" = 105 WHERE "member_srl" = 4';
$this->_test($xml_file, $argsString, $expected); $this->_test($xml_file, $argsString, $expected);
} }
function test_module_updateCounterUnique(){ function test_module_updateCounterUnique(){
$xml_file = _XE_PATH_ . "modules/counter/queries/updateCounterUnique.xml"; $xml_file = _XE_PATH_ . "modules/counter/queries/updateCounterUnique.xml";
$argsString = '$args->regdate = 20110607; $argsString = '$args->regdate = 20110607;
'; ';
$expected = 'UPDATE "xe_counter_status" SET "unique_visitor" = unique_visitor+1, $expected = 'UPDATE "xe_counter_status" SET "unique_visitor" = "unique_visitor" + 1,
"pageview" = pageview+1 WHERE "regdate" = 20110607 '; "pageview" = "pageview" + 1 WHERE "regdate" = 20110607 ';
$this->_test($xml_file, $argsString, $expected); $this->_test($xml_file, $argsString, $expected);
} }
function test_module_updateMenu(){ function test_module_updateMenu(){
$xml_file = _XE_PATH_ . "modules/menu/queries/updateMenu.xml"; $xml_file = _XE_PATH_ . "modules/menu/queries/updateMenu.xml";
$argsString = '$args->menu_srl = 204; $argsString = '$args->menu_srl = 204;
$args->title = "test_menu"; $args->title = "test_menu";
'; ';
$expected = 'UPDATE "xe_menu" SET "title" = \'test_menu\' WHERE "menu_srl" = 204'; $expected = 'UPDATE "xe_menu" SET "title" = \'test_menu\' WHERE "menu_srl" = 204';
$this->_test($xml_file, $argsString, $expected); $this->_test($xml_file, $argsString, $expected);
} }
// $queryTester->test_admin_deleteActionForward(); // $queryTester->test_admin_deleteActionForward();
// $queryTester->test_module_insertModule(); // $queryTester->test_module_insertModule();
} }

View file

@ -6,28 +6,28 @@
function _test($xml_file, $argsString, $expected, $expectedArgs = NULL){ function _test($xml_file, $argsString, $expected, $expectedArgs = NULL){
$this->_testPreparedQuery($xml_file, $argsString, $expected, 'getSelectSql', $expectedArgs = NULL); $this->_testPreparedQuery($xml_file, $argsString, $expected, 'getSelectSql', $expectedArgs = NULL);
} }
function testSelectStar(){ function testSelectStar(){
$xml_file = _XE_PATH_ . "modules/module/queries/getAdminId.xml"; $xml_file = _XE_PATH_ . "modules/module/queries/getAdminId.xml";
$argsString = '$args->module_srl = 10;'; $argsString = '$args->module_srl = 10;';
$expected = 'SELECT * FROM [xe_module_admins] as [module_admins] , [xe_member] as [member] WHERE [module_srl] = ? and [member].[member_srl] = [module_admins].[member_srl]'; $expected = 'SELECT * FROM [xe_module_admins] as [module_admins] , [xe_member] as [member] WHERE [module_srl] = ? and [member].[member_srl] = [module_admins].[member_srl]';
$this->_test($xml_file, $argsString, $expected, array(10)); $this->_test($xml_file, $argsString, $expected, array(10));
} }
function testRquiredParameter(){ function testRquiredParameter(){
$xml_file = _XE_PATH_ . "modules/module/queries/getAdminId.xml"; $xml_file = _XE_PATH_ . "modules/module/queries/getAdminId.xml";
$argsString = ''; $argsString = '';
$expected = 'Date incorecte! Query-ul nu a putut fi executat.'; $expected = 'Date incorecte! Query-ul nu a putut fi executat.';
$this->_test($xml_file, $argsString, $expected); $this->_test($xml_file, $argsString, $expected);
} }
function testWithoutCategoriesTag(){ function testWithoutCategoriesTag(){
$xml_file = _XE_PATH_ . "modules/module/queries/getModuleCategories.xml"; $xml_file = _XE_PATH_ . "modules/module/queries/getModuleCategories.xml";
$argsString = ''; $argsString = '';
$expected = 'SELECT * FROM [xe_module_categories] as [module_categories] ORDER BY [title] asc'; $expected = 'SELECT * FROM [xe_module_categories] as [module_categories] ORDER BY [title] asc';
$this->_test($xml_file, $argsString, $expected); $this->_test($xml_file, $argsString, $expected);
} }
function test_module_getDefaultModules(){ function test_module_getDefaultModules(){
$xml_file = _XE_PATH_ . "modules/module/queries/getDefaultModules.xml"; $xml_file = _XE_PATH_ . "modules/module/queries/getDefaultModules.xml";
$argsString = ''; $argsString = '';
@ -36,14 +36,14 @@
, [modules].[mid] , [modules].[mid]
, [modules].[browser_title] , [modules].[browser_title]
, [module_categories].[title] as [category] , [module_categories].[title] as [category]
, [modules].[module_srl] , [modules].[module_srl]
FROM [xe_modules] as [modules] FROM [xe_modules] as [modules]
left join [xe_module_categories] as [module_categories] left join [xe_module_categories] as [module_categories]
on [module_categories].[module_category_srl] = [modules].[module_category_srl] on [module_categories].[module_category_srl] = [modules].[module_category_srl]
WHERE [modules].[site_srl] = ? WHERE [modules].[site_srl] = ?
ORDER BY [modules].[module] asc, [module_categories].[title] asc, [modules].[mid] asc'; ORDER BY [modules].[module] asc, [module_categories].[title] asc, [modules].[mid] asc';
$this->_test($xml_file, $argsString, $expected, array(0)); $this->_test($xml_file, $argsString, $expected, array(0));
} }
function test_module_getSiteInfo(){ function test_module_getSiteInfo(){
$xml_file = _XE_PATH_ . "modules/module/queries/getSiteInfo.xml"; $xml_file = _XE_PATH_ . "modules/module/queries/getSiteInfo.xml";
@ -72,8 +72,8 @@
, [sites].[domain] as [domain] , [sites].[domain] as [domain]
, [sites].[index_module_srl] as [index_module_srl] , [sites].[index_module_srl] as [index_module_srl]
, [sites].[default_language] as [default_language] , [sites].[default_language] as [default_language]
FROM [xe_sites] as [sites] FROM [xe_sites] as [sites]
left join [xe_modules] as [modules] on [modules].[module_srl] = [sites].[index_module_srl] left join [xe_modules] as [modules] on [modules].[module_srl] = [sites].[index_module_srl]
WHERE [sites].[site_srl] = ? '; WHERE [sites].[site_srl] = ? ';
$this->_test($xml_file, $argsString, $expected, array(0)); $this->_test($xml_file, $argsString, $expected, array(0));
} }
@ -81,77 +81,86 @@
function test_addon_getAddonInfo(){ function test_addon_getAddonInfo(){
$xml_file = _XE_PATH_ . "modules/addon/queries/getAddonInfo.xml"; $xml_file = _XE_PATH_ . "modules/addon/queries/getAddonInfo.xml";
$argsString = '$args->addon = "captcha";'; $argsString = '$args->addon = "captcha";';
$expected = 'SELECT * $expected = 'SELECT *
FROM [xe_addons] as [addons] FROM [xe_addons] as [addons]
WHERE [addon] = ? '; WHERE [addon] = ? ';
$this->_test($xml_file, $argsString, $expected, array("'captcha'")); $this->_test($xml_file, $argsString, $expected, array("'captcha'"));
} }
function test_addon_getAddons(){ function test_addon_getAddons(){
$xml_file = _XE_PATH_ . "modules/addon/queries/getAddons.xml"; $xml_file = _XE_PATH_ . "modules/addon/queries/getAddons.xml";
$argsString = ''; $argsString = '';
$expected = 'SELECT * $expected = 'SELECT *
FROM [xe_addons] as [addons] FROM [xe_addons] as [addons]
ORDER BY [addon] asc'; ORDER BY [addon] asc';
$this->_test($xml_file, $argsString, $expected); $this->_test($xml_file, $argsString, $expected);
} }
function test_admin_getCommentCount(){ function test_admin_getCommentCount(){
$xml_file = _XE_PATH_ . "modules/admin/queries/getCommentCount.xml"; $xml_file = _XE_PATH_ . "modules/admin/queries/getCommentCount.xml";
$argsString = ''; $argsString = '';
$expected = 'SELECT count(*) as [count] $expected = 'SELECT count(*) as [count]
FROM [xe_comments] as [comments]'; FROM [xe_comments] as [comments]';
$this->_test($xml_file, $argsString, $expected); $this->_test($xml_file, $argsString, $expected);
} }
function test_admin_getCommentDeclaredStatus(){ function test_admin_getCommentDeclaredStatus(){
$xml_file = _XE_PATH_ . "modules/admin/queries/getCommentDeclaredStatus.xml"; $xml_file = _XE_PATH_ . "modules/admin/queries/getCommentDeclaredStatus.xml";
$argsString = '$args->date = "20110411";'; $argsString = '$args->date = "20110411";';
$expected = 'SELECT TOP 2 substr([regdate],1,8) as [date], count(*) as [count] $expected = 'SELECT TOP 2 substr([regdate],1,8) as [date], count(*) as [count]
FROM [xe_comment_declared_log] as [comment_declared_log] FROM [xe_comment_declared_log] as [comment_declared_log]
WHERE [regdate] >= ? WHERE [regdate] >= ?
GROUP BY substr([regdate],1,8) GROUP BY substr([regdate],1,8)
ORDER BY substr([regdate],1,8) asc'; ORDER BY substr([regdate],1,8) asc';
$this->_test($xml_file, $argsString, $expected, array("'20110411'")); $this->_test($xml_file, $argsString, $expected, array("'20110411'"));
} }
function test_member_getAutoLogin(){ function test_member_getAutoLogin(){
$xml_file = _XE_PATH_ . "modules/member/queries/getAutoLogin.xml"; $xml_file = _XE_PATH_ . "modules/member/queries/getAutoLogin.xml";
$argsString = '$args->autologin_key = 10;'; $argsString = '$args->autologin_key = 10;';
$expected = 'SELECT [member].[user_id] as [user_id] $expected = 'SELECT [member].[user_id] as [user_id]
, [member].[password] as [password] , [member].[password] as [password]
, [member_autologin].[autologin_key] as [autologin_key] , [member_autologin].[autologin_key] as [autologin_key]
FROM [xe_member] as [member] , [xe_member_autologin] as [member_autologin] FROM [xe_member] as [member] , [xe_member_autologin] as [member_autologin]
WHERE [member_autologin].[autologin_key] = ? WHERE [member_autologin].[autologin_key] = ?
and [member].[member_srl] = [member_autologin].[member_srl]'; and [member].[member_srl] = [member_autologin].[member_srl]';
$this->_test($xml_file, $argsString, $expected, array("'10'")); $this->_test($xml_file, $argsString, $expected, array("'10'"));
} }
function test_opage_getOpageList(){ function test_opage_getOpageList(){
$xml_file = _XE_PATH_ . "modules/opage/queries/getOpageList.xml"; $xml_file = _XE_PATH_ . "modules/opage/queries/getOpageList.xml";
$argsString = '$args->s_title = "yuhuu"; $argsString = '$args->s_title = "yuhuu";
$args->module = \'opage\';'; $args->module = \'opage\';';
$expected = 'SELECT TOP 20 * $expected = 'SELECT TOP 20 *
FROM [xe_modules] as [modules] FROM [xe_modules] as [modules]
WHERE [module] = ? and ([browser_title] like ?) WHERE [module] = ? and ([browser_title] like ?)
ORDER BY [module_srl] desc'; ORDER BY [module_srl] desc';
$this->_test($xml_file, $argsString, $expected, array("'opage'", "'%yuhuu%'")); $this->_test($xml_file, $argsString, $expected, array("'opage'", "'%yuhuu%'"));
} }
function test_module_getExtraVars(){
$xml_file = _XE_PATH_ . "modules/module/queries/getModuleExtraVars.xml";
$argsString = '$args->module_srl = 25;';
$expected = 'SELECT * FROM [xe_module_extra_vars] as [module_extra_vars] WHERE [module_srl] in (?)';
$this->_test($xml_file, $argsString, $expected, array("25"));
}
// TODO Something fishy about this query - to be investigated // TODO Something fishy about this query - to be investigated
/* /*
function test_syndication_getGrantedModules(){ function test_syndication_getGrantedModules(){
$xml_file = _XE_PATH_ . "modules/syndication/queries/getGrantedModules.xml"; $xml_file = _XE_PATH_ . "modules/syndication/queries/getGrantedModules.xml";
$argsString = '$args->module_srl = 12; $argsString = '$args->module_srl = 12;
$args->name = array(\'access\',\'view\',\'list\');'; $args->name = array(\'access\',\'view\',\'list\');';
$expected = 'select "module_srl" $expected = 'select "module_srl"
from "xe_module_grants" as "module_grants" from "xe_module_grants" as "module_grants"
where "name" in (?) where "name" in (?)
and ("group_srl" >= -2 and ("group_srl" >= -2
or "group_srl" = -2 or "group_srl" = -2
or "group_srl" = -2) or "group_srl" = -2)
group by "module_srl"'; group by "module_srl"';
$this->_test($xml_file, $argsString, $expected); $this->_test($xml_file, $argsString, $expected);
} }
*/ */
} }

View file

@ -0,0 +1,12 @@
<?php
class MssqlUpdateOnlineTest extends MssqlOnlineTest {
function test_counter_updateCounterUnique(){
$args->regdate = 20110211;
$output = executeQuery("counter.updateCounterUnique", $args);
$this->assertEquals(0, $output->error, $output->error + ' ' + $output->message);
}
}
?>

View file

@ -0,0 +1,17 @@
<?php
require(_XE_PATH_ . 'test-phpUnit/config/config.inc.php');
class MssqlUpdateTest extends MssqlTest {
function _test($xml_file, $argsString, $expected, $expectedArgs = NULL){
$this->_testPreparedQuery($xml_file, $argsString, $expected, 'getUpdateSql', $expectedArgs = NULL);
}
function test_counter_updateCounterUnique(){
$xml_file = _XE_PATH_ . "modules/counter/queries/updateCounterUnique.xml";
$argsString = '$args->regdate = 25;';
$expected = 'UPDATE [xe_counter_status] SET [unique_visitor] = [unique_visitor] + ?, [pageview] = [pageview] + ? WHERE [regdate] = ?';
$this->_test($xml_file, $argsString, $expected, array("25", 1, 1));
}
}
?>