Commit 075a5808 authored by Tanken's avatar Tanken

Fixed a missing space in the query build by count()

Fixed count()'s code formatting (was tabs in some lines)
fixes #171
Ticket: 171
parent a2299b2a
<?php <?php
/* /*
* $Id$ * $Id$
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
* This software consists of voluntary contributions made by many individuals * This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see * and is licensed under the LGPL. For more information, see
* <http://www.phpdoctrine.com>. * <http://www.phpdoctrine.com>.
*/ */
/** /**
* Doctrine_Query * Doctrine_Query
* *
* @package Doctrine ORM * @package Doctrine ORM
* @url www.phpdoctrine.com * @url www.phpdoctrine.com
* @license LGPL * @license LGPL
*/ */
class Doctrine_Query extends Doctrine_Hydrate implements Countable { class Doctrine_Query extends Doctrine_Hydrate implements Countable {
/** /**
* @param array $subqueryAliases the table aliases needed in some LIMIT subqueries * @param array $subqueryAliases the table aliases needed in some LIMIT subqueries
*/ */
private $subqueryAliases = array(); private $subqueryAliases = array();
/** /**
* @param boolean $needsSubquery * @param boolean $needsSubquery
*/ */
private $needsSubquery = false; private $needsSubquery = false;
/** /**
* @param boolean $limitSubqueryUsed * @param boolean $limitSubqueryUsed
*/ */
private $limitSubqueryUsed = false; private $limitSubqueryUsed = false;
private $tableStack; private $tableStack;
private $relationStack = array(); private $relationStack = array();
private $isDistinct = false; private $isDistinct = false;
/** /**
* create * create
* returns a new Doctrine_Query object * returns a new Doctrine_Query object
* *
* @return Doctrine_Query * @return Doctrine_Query
*/ */
public static function create() { public static function create() {
return new Doctrine_Query(); return new Doctrine_Query();
} }
public function getTableStack() { public function getTableStack() {
return $this->tableStack; return $this->tableStack;
} }
public function getRelationStack() { public function getRelationStack() {
return $this->relationStack; return $this->relationStack;
} }
public function isDistinct($distinct = null) { public function isDistinct($distinct = null) {
if(isset($distinct)) if(isset($distinct))
$this->isDistinct = (bool) $distinct; $this->isDistinct = (bool) $distinct;
return $this->isDistinct; return $this->isDistinct;
} }
/** /**
* count * count
* *
* @return integer * @return integer
*/ */
public function count(Doctrine_Table $table, $params = array()) { public function count(Doctrine_Table $table, $params = array()) {
$this->remove('select'); $this->remove('select');
$join = $this->join; $join = $this->join;
$where = $this->where; $where = $this->where;
$having = $this->having; $having = $this->having;
$q = "SELECT COUNT(DISTINCT ".$table->getTableName().'.'.$table->getIdentifier().") FROM ".$table->getTableName()." "; $q = "SELECT COUNT(DISTINCT ".$table->getTableName().'.'.$table->getIdentifier().") FROM ".$table->getTableName()." ";
foreach($join as $j) { foreach($join as $j) {
$q .= implode(" ",$j); $q .= " ".implode(" ",$j);
} }
$string = $this->applyInheritance(); $string = $this->applyInheritance();
if( ! empty($where)) { if( ! empty($where)) {
$q .= " WHERE ".implode(" AND ",$where); $q .= " WHERE ".implode(" AND ",$where);
if( ! empty($string)) if( ! empty($string))
$q .= " AND (".$string.")"; $q .= " AND (".$string.")";
} else { } else {
if( ! empty($string)) if( ! empty($string))
$q .= " WHERE (".$string.")"; $q .= " WHERE (".$string.")";
} }
if( ! empty($having)) if( ! empty($having))
$q .= " HAVING ".implode(' AND ',$having); $q .= " HAVING ".implode(' AND ',$having);
$a = $this->getConnection()->execute($q, $params)->fetch(PDO::FETCH_NUM); $a = $this->getConnection()->execute($q, $params)->fetch(PDO::FETCH_NUM);
return $a[0]; return $a[0];
} }
/** /**
* loadFields * loadFields
* loads fields for a given table and * loads fields for a given table and
* constructs a little bit of sql for every field * constructs a little bit of sql for every field
* *
* fields of the tables become: [tablename].[fieldname] as [tablename]__[fieldname] * fields of the tables become: [tablename].[fieldname] as [tablename]__[fieldname]
* *
* @access private * @access private
* @param object Doctrine_Table $table a Doctrine_Table object * @param object Doctrine_Table $table a Doctrine_Table object
* @param integer $fetchmode fetchmode the table is using eg. Doctrine::FETCH_LAZY * @param integer $fetchmode fetchmode the table is using eg. Doctrine::FETCH_LAZY
* @param array $names fields to be loaded (only used in lazy property loading) * @param array $names fields to be loaded (only used in lazy property loading)
* @return void * @return void
*/ */
protected function loadFields(Doctrine_Table $table, $fetchmode, array $names, $cpath) { protected function loadFields(Doctrine_Table $table, $fetchmode, array $names, $cpath) {
$name = $table->getComponentName(); $name = $table->getComponentName();
switch($fetchmode): switch($fetchmode):
case Doctrine::FETCH_OFFSET: case Doctrine::FETCH_OFFSET:
$this->limit = $table->getAttribute(Doctrine::ATTR_COLL_LIMIT); $this->limit = $table->getAttribute(Doctrine::ATTR_COLL_LIMIT);
case Doctrine::FETCH_IMMEDIATE: case Doctrine::FETCH_IMMEDIATE:
if( ! empty($names)) if( ! empty($names))
$names = array_unique(array_merge($table->getPrimaryKeys(), $names)); $names = array_unique(array_merge($table->getPrimaryKeys(), $names));
else else
$names = $table->getColumnNames(); $names = $table->getColumnNames();
break; break;
case Doctrine::FETCH_LAZY_OFFSET: case Doctrine::FETCH_LAZY_OFFSET:
$this->limit = $table->getAttribute(Doctrine::ATTR_COLL_LIMIT); $this->limit = $table->getAttribute(Doctrine::ATTR_COLL_LIMIT);
case Doctrine::FETCH_LAZY: case Doctrine::FETCH_LAZY:
case Doctrine::FETCH_BATCH: case Doctrine::FETCH_BATCH:
$names = array_unique(array_merge($table->getPrimaryKeys(), $names)); $names = array_unique(array_merge($table->getPrimaryKeys(), $names));
break; break;
default: default:
throw new Doctrine_Exception("Unknown fetchmode."); throw new Doctrine_Exception("Unknown fetchmode.");
endswitch; endswitch;
$component = $table->getComponentName(); $component = $table->getComponentName();
$tablename = $this->tableAliases[$cpath]; $tablename = $this->tableAliases[$cpath];
$this->fetchModes[$tablename] = $fetchmode; $this->fetchModes[$tablename] = $fetchmode;
$count = count($this->tables); $count = count($this->tables);
foreach($names as $name) { foreach($names as $name) {
if($count == 0) { if($count == 0) {
$this->parts["select"][] = $tablename.".".$name; $this->parts["select"][] = $tablename.".".$name;
} else { } else {
$this->parts["select"][] = $tablename.".".$name." AS ".$tablename."__".$name; $this->parts["select"][] = $tablename.".".$name." AS ".$tablename."__".$name;
} }
} }
} }
/** /**
* addFrom * addFrom
* *
* @param strint $from * @param strint $from
*/ */
public function addFrom($from) { public function addFrom($from) {
$class = "Doctrine_Query_From"; $class = "Doctrine_Query_From";
$parser = new $class($this); $parser = new $class($this);
$parser->parse($from); $parser->parse($from);
} }
/** /**
* addWhere * addWhere
* *
* @param string $where * @param string $where
* @param mixed $params * @param mixed $params
*/ */
public function addWhere($where, $params = array()) { public function addWhere($where, $params = array()) {
$class = "Doctrine_Query_Where"; $class = "Doctrine_Query_Where";
$parser = new $class($this); $parser = new $class($this);
$this->parts['where'][] = $parser->parse($where); $this->parts['where'][] = $parser->parse($where);
if(is_array($params)) { if(is_array($params)) {
$this->params = array_merge($this->params, $params); $this->params = array_merge($this->params, $params);
} else { } else {
$this->params[] = $params; $this->params[] = $params;
} }
} }
/** /**
* sets a query part * sets a query part
* *
* @param string $name * @param string $name
* @param array $args * @param array $args
* @return void * @return void
*/ */
public function __call($name, $args) { public function __call($name, $args) {
$name = strtolower($name); $name = strtolower($name);
if(isset($this->parts[$name])) { if(isset($this->parts[$name])) {
$method = "parse".ucwords($name); $method = "parse".ucwords($name);
switch($name): switch($name):
case "from": case "from":
$this->parts['from'] = array(); $this->parts['from'] = array();
$this->parts['select'] = array(); $this->parts['select'] = array();
$this->parts['join'] = array(); $this->parts['join'] = array();
$this->joins = array(); $this->joins = array();
$this->tables = array(); $this->tables = array();
$this->fetchModes = array(); $this->fetchModes = array();
$this->tableIndexes = array(); $this->tableIndexes = array();
$this->tableAliases = array(); $this->tableAliases = array();
$class = "Doctrine_Query_".ucwords($name); $class = "Doctrine_Query_".ucwords($name);
$parser = new $class($this); $parser = new $class($this);
$parser->parse($args[0]); $parser->parse($args[0]);
break; break;
case "where": case "where":
case "having": case "having":
case "orderby": case "orderby":
case "groupby": case "groupby":
$class = "Doctrine_Query_".ucwords($name); $class = "Doctrine_Query_".ucwords($name);
$parser = new $class($this); $parser = new $class($this);
$this->parts[$name] = array($parser->parse($args[0])); $this->parts[$name] = array($parser->parse($args[0]));
break; break;
case "limit": case "limit":
case "offset": case "offset":
if($args[0] == null) if($args[0] == null)
$args[0] = false; $args[0] = false;
$this->parts[$name] = $args[0]; $this->parts[$name] = $args[0];
break; break;
default: default:
$this->parts[$name] = array(); $this->parts[$name] = array();
$this->$method($args[0]); $this->$method($args[0]);
endswitch; endswitch;
} else } else
throw new Doctrine_Query_Exception("Unknown overload method"); throw new Doctrine_Query_Exception("Unknown overload method");
return $this; return $this;
} }
/** /**
* returns a query part * returns a query part
* *
* @param $name query part name * @param $name query part name
* @return mixed * @return mixed
*/ */
public function get($name) { public function get($name) {
if( ! isset($this->parts[$name])) if( ! isset($this->parts[$name]))
return false; return false;
return $this->parts[$name]; return $this->parts[$name];
} }
/** /**
* sets a query part * sets a query part
* *
* @param $name query part name * @param $name query part name
* @param $value query part value * @param $value query part value
* @return boolean * @return boolean
*/ */
public function set($name, $value) { public function set($name, $value) {
if(isset($this->parts[$name])) { if(isset($this->parts[$name])) {
$method = "parse".ucwords($name); $method = "parse".ucwords($name);
switch($name): switch($name):
case "where": case "where":
case "having": case "having":
$this->parts[$name] = array($this->$method($value)); $this->parts[$name] = array($this->$method($value));
break; break;
case "limit": case "limit":
case "offset": case "offset":
if($value == null) if($value == null)
$value = false; $value = false;
$this->parts[$name] = $value; $this->parts[$name] = $value;
break; break;
case "from": case "from":
$this->parts['select'] = array(); $this->parts['select'] = array();
$this->parts['join'] = array(); $this->parts['join'] = array();
$this->joins = array(); $this->joins = array();
$this->tables = array(); $this->tables = array();
$this->fetchModes = array(); $this->fetchModes = array();
$this->tableIndexes = array(); $this->tableIndexes = array();
$this->tableAliases = array(); $this->tableAliases = array();
default: default:
$this->parts[$name] = array(); $this->parts[$name] = array();
$this->$method($value); $this->$method($value);
endswitch; endswitch;
return true; return true;
} }
return false; return false;
} }
/** /**
* @return boolean * @return boolean
*/ */
public function isLimitSubqueryUsed() { public function isLimitSubqueryUsed() {
return $this->limitSubqueryUsed; return $this->limitSubqueryUsed;
} }
/** /**
* returns the built sql query * returns the built sql query
* *
* @return string * @return string
*/ */
public function getQuery() { public function getQuery() {
if(empty($this->parts["select"]) || empty($this->parts["from"])) if(empty($this->parts["select"]) || empty($this->parts["from"]))
return false; return false;
$needsSubQuery = false; $needsSubQuery = false;
$subquery = ''; $subquery = '';
$k = array_keys($this->tables); $k = array_keys($this->tables);
$table = $this->tables[$k[0]]; $table = $this->tables[$k[0]];
if( ! empty($this->parts['limit']) && $this->needsSubquery && $table->getAttribute(Doctrine::ATTR_QUERY_LIMIT) == Doctrine::LIMIT_RECORDS) { if( ! empty($this->parts['limit']) && $this->needsSubquery && $table->getAttribute(Doctrine::ATTR_QUERY_LIMIT) == Doctrine::LIMIT_RECORDS) {
$needsSubQuery = true; $needsSubQuery = true;
$this->limitSubqueryUsed = true; $this->limitSubqueryUsed = true;
} }
// build the basic query // build the basic query
$str = ''; $str = '';
if($this->isDistinct()) if($this->isDistinct())
$str = 'DISTINCT '; $str = 'DISTINCT ';
$q = "SELECT ".$str.implode(", ",$this->parts["select"]). $q = "SELECT ".$str.implode(", ",$this->parts["select"]).
" FROM "; " FROM ";
foreach($this->parts["from"] as $tname => $bool) { foreach($this->parts["from"] as $tname => $bool) {
$a[] = $tname; $a[] = $tname;
} }
$q .= implode(", ",$a); $q .= implode(", ",$a);
if($needsSubQuery) if($needsSubQuery)
$subquery = 'SELECT DISTINCT '.$table->getTableName().".".$table->getIdentifier(). $subquery = 'SELECT DISTINCT '.$table->getTableName().".".$table->getIdentifier().
' FROM '.$table->getTableName(); ' FROM '.$table->getTableName();
if( ! empty($this->parts['join'])) { if( ! empty($this->parts['join'])) {
foreach($this->parts['join'] as $part) { foreach($this->parts['join'] as $part) {
$q .= " ".implode(' ', $part); $q .= " ".implode(' ', $part);
} }
if($needsSubQuery) { if($needsSubQuery) {
foreach($this->parts['join'] as $parts) { foreach($this->parts['join'] as $parts) {
foreach($parts as $part) { foreach($parts as $part) {
if(substr($part,0,9) === 'LEFT JOIN') { if(substr($part,0,9) === 'LEFT JOIN') {
$e = explode(' ', $part); $e = explode(' ', $part);
if( ! in_array($e[2],$this->subqueryAliases)) if( ! in_array($e[2],$this->subqueryAliases))
continue; continue;
} }
$subquery .= " ".$part; $subquery .= " ".$part;
} }
} }
} }
} }
$string = $this->applyInheritance(); $string = $this->applyInheritance();
if( ! empty($string)) if( ! empty($string))
$this->parts['where'][] = '('.$string.')'; $this->parts['where'][] = '('.$string.')';
if($needsSubQuery) { if($needsSubQuery) {
// all conditions must be preserved in subquery // all conditions must be preserved in subquery
$subquery .= ( ! empty($this->parts['where']))?" WHERE ".implode(" AND ",$this->parts["where"]):''; $subquery .= ( ! empty($this->parts['where']))?" WHERE ".implode(" AND ",$this->parts["where"]):'';
$subquery .= ( ! empty($this->parts['groupby']))?" GROUP BY ".implode(", ",$this->parts["groupby"]):''; $subquery .= ( ! empty($this->parts['groupby']))?" GROUP BY ".implode(", ",$this->parts["groupby"]):'';
$subquery .= ( ! empty($this->parts['having']))?" HAVING ".implode(" ",$this->parts["having"]):''; $subquery .= ( ! empty($this->parts['having']))?" HAVING ".implode(" ",$this->parts["having"]):'';
} }
$modifyLimit = true; $modifyLimit = true;
if( ! empty($this->parts["limit"]) || ! empty($this->parts["offset"])) { if( ! empty($this->parts["limit"]) || ! empty($this->parts["offset"])) {
if($needsSubQuery) { if($needsSubQuery) {
$subquery = $this->connection->modifyLimitQuery($subquery,$this->parts["limit"],$this->parts["offset"]); $subquery = $this->connection->modifyLimitQuery($subquery,$this->parts["limit"],$this->parts["offset"]);
$dbh = $this->connection->getDBH(); $dbh = $this->connection->getDBH();
// mysql doesn't support LIMIT in subqueries // mysql doesn't support LIMIT in subqueries
if($dbh->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') { } if($dbh->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') { }
//$dbh->query(); //$dbh->query();
$field = $table->getTableName().'.'.$table->getIdentifier(); $field = $table->getTableName().'.'.$table->getIdentifier();
array_unshift($this->parts['where'], $field.' IN ('.$subquery.')'); array_unshift($this->parts['where'], $field.' IN ('.$subquery.')');
$modifyLimit = false; $modifyLimit = false;
} }
} }
$q .= ( ! empty($this->parts['where']))?" WHERE ".implode(" AND ",$this->parts["where"]):''; $q .= ( ! empty($this->parts['where']))?" WHERE ".implode(" AND ",$this->parts["where"]):'';
$q .= ( ! empty($this->parts['groupby']))?" GROUP BY ".implode(", ",$this->parts["groupby"]):''; $q .= ( ! empty($this->parts['groupby']))?" GROUP BY ".implode(", ",$this->parts["groupby"]):'';
$q .= ( ! empty($this->parts['having']))?" HAVING ".implode(" ",$this->parts["having"]):''; $q .= ( ! empty($this->parts['having']))?" HAVING ".implode(" ",$this->parts["having"]):'';
$q .= ( ! empty($this->parts['orderby']))?" ORDER BY ".implode(" ",$this->parts["orderby"]):''; $q .= ( ! empty($this->parts['orderby']))?" ORDER BY ".implode(" ",$this->parts["orderby"]):'';
if($modifyLimit) if($modifyLimit)
$q = $this->connection->modifyLimitQuery($q,$this->parts["limit"],$this->parts["offset"]); $q = $this->connection->modifyLimitQuery($q,$this->parts["limit"],$this->parts["offset"]);
// return to the previous state // return to the previous state
if( ! empty($string)) if( ! empty($string))
array_pop($this->parts['where']); array_pop($this->parts['where']);
if($needsSubQuery) if($needsSubQuery)
array_shift($this->parts['where']); array_shift($this->parts['where']);
return $q; return $q;
} }
/** /**
* query the database with DQL (Doctrine Query Language) * query the database with DQL (Doctrine Query Language)
* *
* @param string $query DQL query * @param string $query DQL query
* @param array $params parameters * @param array $params parameters
*/ */
public function query($query,$params = array()) { public function query($query,$params = array()) {
$this->parseQuery($query); $this->parseQuery($query);
if($this->aggregate) { if($this->aggregate) {
$keys = array_keys($this->tables); $keys = array_keys($this->tables);
$query = $this->getQuery(); $query = $this->getQuery();
$stmt = $this->tables[$keys[0]]->getConnection()->select($query,$this->parts["limit"],$this->parts["offset"]); $stmt = $this->tables[$keys[0]]->getConnection()->select($query,$this->parts["limit"],$this->parts["offset"]);
$data = $stmt->fetch(PDO::FETCH_ASSOC); $data = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($data) == 1) { if(count($data) == 1) {
return current($data); return current($data);
} else { } else {
return $data; return $data;
} }
} else { } else {
return $this->execute($params); return $this->execute($params);
} }
} }
/** /**
* DQL PARSER * DQL PARSER
* parses a DQL query * parses a DQL query
* first splits the query in parts and then uses individual * first splits the query in parts and then uses individual
* parsers for each part * parsers for each part
* *
* @param string $query DQL query * @param string $query DQL query
* @param boolean $clear whether or not to clear the aliases * @param boolean $clear whether or not to clear the aliases
* @throws Doctrine_Query_Exception if some generic parsing error occurs * @throws Doctrine_Query_Exception if some generic parsing error occurs
* @return Doctrine_Query * @return Doctrine_Query
*/ */
public function parseQuery($query, $clear = true) { public function parseQuery($query, $clear = true) {
if($clear) if($clear)
$this->clear(); $this->clear();
$query = trim($query); $query = trim($query);
$query = str_replace("\n"," ",$query); $query = str_replace("\n"," ",$query);
$query = str_replace("\r"," ",$query); $query = str_replace("\r"," ",$query);
$e = self::sqlExplode($query," ","(",")"); $e = self::sqlExplode($query," ","(",")");
foreach($e as $k=>$part) { foreach($e as $k=>$part) {
$part = trim($part); $part = trim($part);
switch(strtolower($part)) { switch(strtolower($part)) {
case "select": case "select":
case "from": case "from":
case "where": case "where":
case "limit": case "limit":
case "offset": case "offset":
case "having": case "having":
$p = $part; $p = $part;
$parts[$part] = array(); $parts[$part] = array();
break; break;
case "order": case "order":
case "group": case "group":
$i = ($k + 1); $i = ($k + 1);
if(isset($e[$i]) && strtolower($e[$i]) === "by") { if(isset($e[$i]) && strtolower($e[$i]) === "by") {
$p = $part; $p = $part;
$parts[$part] = array(); $parts[$part] = array();
} else } else
$parts[$p][] = $part; $parts[$p][] = $part;
break; break;
case "by": case "by":
continue; continue;
default: default:
if( ! isset($p)) if( ! isset($p))
throw new Doctrine_Query_Exception("Couldn't parse query."); throw new Doctrine_Query_Exception("Couldn't parse query.");
$parts[$p][] = $part; $parts[$p][] = $part;
} }
} }
foreach($parts as $k => $part) { foreach($parts as $k => $part) {
$part = implode(" ",$part); $part = implode(" ",$part);
switch(strtoupper($k)) { switch(strtoupper($k)) {
case "SELECT": case "SELECT":
$this->parseSelect($part); $this->parseSelect($part);
break; break;
case "FROM": case "FROM":
$class = "Doctrine_Query_".ucwords(strtolower($k)); $class = "Doctrine_Query_".ucwords(strtolower($k));
$parser = new $class($this); $parser = new $class($this);
$parser->parse($part); $parser->parse($part);
break; break;
case "GROUP": case "GROUP":
case "ORDER": case "ORDER":
$k .= "by"; $k .= "by";
case "WHERE": case "WHERE":
case "HAVING": case "HAVING":
$class = "Doctrine_Query_".ucwords(strtolower($k)); $class = "Doctrine_Query_".ucwords(strtolower($k));
$parser = new $class($this); $parser = new $class($this);
$name = strtolower($k); $name = strtolower($k);
$this->parts[$name][] = $parser->parse($part); $this->parts[$name][] = $parser->parse($part);
break; break;
case "LIMIT": case "LIMIT":
$this->parts["limit"] = trim($part); $this->parts["limit"] = trim($part);
break; break;
case "OFFSET": case "OFFSET":
$this->parts["offset"] = trim($part); $this->parts["offset"] = trim($part);
break; break;
} }
} }
return $this; return $this;
} }
/** /**
* DQL ORDER BY PARSER * DQL ORDER BY PARSER
* parses the order by part of the query string * parses the order by part of the query string
* *
* @param string $str * @param string $str
* @return void * @return void
*/ */
final public function parseOrderBy($str) { final public function parseOrderBy($str) {
$parser = new Doctrine_Query_Part_Orderby($this); $parser = new Doctrine_Query_Part_Orderby($this);
return $parser->parse($str); return $parser->parse($str);
} }
/** /**
* returns Doctrine::FETCH_* constant * returns Doctrine::FETCH_* constant
* *
* @param string $mode * @param string $mode
* @return integer * @return integer
*/ */
final public function parseFetchMode($mode) { final public function parseFetchMode($mode) {
switch(strtolower($mode)): switch(strtolower($mode)):
case "i": case "i":
case "immediate": case "immediate":
$fetchmode = Doctrine::FETCH_IMMEDIATE; $fetchmode = Doctrine::FETCH_IMMEDIATE;
break; break;
case "b": case "b":
case "batch": case "batch":
$fetchmode = Doctrine::FETCH_BATCH; $fetchmode = Doctrine::FETCH_BATCH;
break; break;
case "l": case "l":
case "lazy": case "lazy":
$fetchmode = Doctrine::FETCH_LAZY; $fetchmode = Doctrine::FETCH_LAZY;
break; break;
case "o": case "o":
case "offset": case "offset":
$fetchmode = Doctrine::FETCH_OFFSET; $fetchmode = Doctrine::FETCH_OFFSET;
break; break;
case "lo": case "lo":
case "lazyoffset": case "lazyoffset":
$fetchmode = Doctrine::FETCH_LAZYOFFSET; $fetchmode = Doctrine::FETCH_LAZYOFFSET;
default: default:
throw new Doctrine_Query_Exception("Unknown fetchmode '$mode'. The availible fetchmodes are 'i', 'b' and 'l'."); throw new Doctrine_Query_Exception("Unknown fetchmode '$mode'. The availible fetchmodes are 'i', 'b' and 'l'.");
endswitch; endswitch;
return $fetchmode; return $fetchmode;
} }
/** /**
* trims brackets * trims brackets
* *
* @param string $str * @param string $str
* @param string $e1 the first bracket, usually '(' * @param string $e1 the first bracket, usually '('
* @param string $e2 the second bracket, usually ')' * @param string $e2 the second bracket, usually ')'
*/ */
public static function bracketTrim($str,$e1 = '(',$e2 = ')') { public static function bracketTrim($str,$e1 = '(',$e2 = ')') {
if(substr($str,0,1) == $e1 && substr($str,-1) == $e2) if(substr($str,0,1) == $e1 && substr($str,-1) == $e2)
return substr($str,1,-1); return substr($str,1,-1);
else else
return $str; return $str;
} }
/** /**
* bracketExplode * bracketExplode
* usage: * usage:
* $str = (age < 20 AND age > 18) AND email LIKE 'John@example.com' * $str = (age < 20 AND age > 18) AND email LIKE 'John@example.com'
* now exploding $str with parameters $d = ' AND ', $e1 = '(' and $e2 = ')' * now exploding $str with parameters $d = ' AND ', $e1 = '(' and $e2 = ')'
* would return an array: * would return an array:
* array("(age < 20 AND age > 18)", "email LIKE 'John@example.com'") * array("(age < 20 AND age > 18)", "email LIKE 'John@example.com'")
* *
* @param string $str * @param string $str
* @param string $d the delimeter which explodes the string * @param string $d the delimeter which explodes the string
* @param string $e1 the first bracket, usually '(' * @param string $e1 the first bracket, usually '('
* @param string $e2 the second bracket, usually ')' * @param string $e2 the second bracket, usually ')'
* *
*/ */
public static function bracketExplode($str,$d,$e1 = '(',$e2 = ')') { public static function bracketExplode($str,$d,$e1 = '(',$e2 = ')') {
if(is_array($d)) { if(is_array($d)) {
$a = preg_split('/('.implode('|', $d).')/', $str); $a = preg_split('/('.implode('|', $d).')/', $str);
$d = stripslashes($d[0]); $d = stripslashes($d[0]);
} else } else
$a = explode("$d",$str); $a = explode("$d",$str);
$i = 0; $i = 0;
$term = array(); $term = array();
foreach($a as $key=>$val) { foreach($a as $key=>$val) {
if (empty($term[$i])) { if (empty($term[$i])) {
$term[$i] = trim($val); $term[$i] = trim($val);
$s1 = substr_count($term[$i],"$e1"); $s1 = substr_count($term[$i],"$e1");
$s2 = substr_count($term[$i],"$e2"); $s2 = substr_count($term[$i],"$e2");
if($s1 == $s2) $i++; if($s1 == $s2) $i++;
} else { } else {
$term[$i] .= "$d".trim($val); $term[$i] .= "$d".trim($val);
$c1 = substr_count($term[$i],"$e1"); $c1 = substr_count($term[$i],"$e1");
$c2 = substr_count($term[$i],"$e2"); $c2 = substr_count($term[$i],"$e2");
if($c1 == $c2) $i++; if($c1 == $c2) $i++;
} }
} }
return $term; return $term;
} }
/** /**
* sqlExplode * sqlExplode
* *
* explodes a string into array using custom brackets and * explodes a string into array using custom brackets and
* quote delimeters * quote delimeters
* *
* @param string $str * @param string $str
* @param string $d the delimeter which explodes the string * @param string $d the delimeter which explodes the string
* @param string $e1 the first bracket, usually '(' * @param string $e1 the first bracket, usually '('
* @param string $e2 the second bracket, usually ')' * @param string $e2 the second bracket, usually ')'
* *
* @return array * @return array
*/ */
public static function sqlExplode($str,$d = " ",$e1 = '(',$e2 = ')') { public static function sqlExplode($str,$d = " ",$e1 = '(',$e2 = ')') {
if(is_array($d)) { if(is_array($d)) {
$str = preg_split('/('.implode('|', $d).')/', $str); $str = preg_split('/('.implode('|', $d).')/', $str);
$d = stripslashes($d[0]); $d = stripslashes($d[0]);
} else } else
$str = explode("$d",$str); $str = explode("$d",$str);
$i = 0; $i = 0;
$term = array(); $term = array();
foreach($str as $key => $val) { foreach($str as $key => $val) {
if (empty($term[$i])) { if (empty($term[$i])) {
$term[$i] = trim($val); $term[$i] = trim($val);
$s1 = substr_count($term[$i],"$e1"); $s1 = substr_count($term[$i],"$e1");
$s2 = substr_count($term[$i],"$e2"); $s2 = substr_count($term[$i],"$e2");
if(substr($term[$i],0,1) == "(") { if(substr($term[$i],0,1) == "(") {
if($s1 == $s2) if($s1 == $s2)
$i++; $i++;
} else { } else {
if( ! (substr_count($term[$i], "'") & 1) && if( ! (substr_count($term[$i], "'") & 1) &&
! (substr_count($term[$i], "\"") & 1) && ! (substr_count($term[$i], "\"") & 1) &&
! (substr_count($term[$i], "") & 1) ! (substr_count($term[$i], "") & 1)
) $i++; ) $i++;
} }
} else { } else {
$term[$i] .= "$d".trim($val); $term[$i] .= "$d".trim($val);
$c1 = substr_count($term[$i],"$e1"); $c1 = substr_count($term[$i],"$e1");
$c2 = substr_count($term[$i],"$e2"); $c2 = substr_count($term[$i],"$e2");
if(substr($term[$i],0,1) == "(") { if(substr($term[$i],0,1) == "(") {
if($c1 == $c2) if($c1 == $c2)
$i++; $i++;
} else { } else {
if( ! (substr_count($term[$i], "'") & 1) && if( ! (substr_count($term[$i], "'") & 1) &&
! (substr_count($term[$i], "\"") & 1) && ! (substr_count($term[$i], "\"") & 1) &&
! (substr_count($term[$i], "") & 1) ! (substr_count($term[$i], "") & 1)
) $i++; ) $i++;
} }
} }
} }
return $term; return $term;
} }
/** /**
* generateAlias * generateAlias
* *
* @param string $tableName * @param string $tableName
* @return string * @return string
*/ */
public function generateAlias($tableName) { public function generateAlias($tableName) {
if(isset($this->tableIndexes[$tableName])) { if(isset($this->tableIndexes[$tableName])) {
return $tableName.++$this->tableIndexes[$tableName]; return $tableName.++$this->tableIndexes[$tableName];
} else { } else {
$this->tableIndexes[$tableName] = 1; $this->tableIndexes[$tableName] = 1;
return $tableName; return $tableName;
} }
} }
/** /**
* loads a component * loads a component
* *
* @param string $path the path of the loadable component * @param string $path the path of the loadable component
* @param integer $fetchmode optional fetchmode, if not set the components default fetchmode will be used * @param integer $fetchmode optional fetchmode, if not set the components default fetchmode will be used
* @throws Doctrine_Query_Exception * @throws Doctrine_Query_Exception
* @return Doctrine_Table * @return Doctrine_Table
*/ */
final public function load($path, $loadFields = true) { final public function load($path, $loadFields = true) {
$tmp = explode(' ',$path); $tmp = explode(' ',$path);
$componentAlias = (count($tmp) > 1) ? end($tmp) : false; $componentAlias = (count($tmp) > 1) ? end($tmp) : false;
$e = preg_split("/[.:]/", $tmp[0], -1); $e = preg_split("/[.:]/", $tmp[0], -1);
if(isset($this->compAliases[$e[0]])) { if(isset($this->compAliases[$e[0]])) {
$end = substr($tmp[0], strlen($e[0])); $end = substr($tmp[0], strlen($e[0]));
$path = $this->compAliases[$e[0]] . $end; $path = $this->compAliases[$e[0]] . $end;
$e = preg_split("/[.:]/", $path, -1); $e = preg_split("/[.:]/", $path, -1);
} else } else
$path = $tmp[0]; $path = $tmp[0];
$index = 0; $index = 0;
$currPath = ''; $currPath = '';
$this->tableStack = array(); $this->tableStack = array();
foreach($e as $key => $fullname) { foreach($e as $key => $fullname) {
try { try {
$copy = $e; $copy = $e;
$e2 = preg_split("/[-(]/",$fullname); $e2 = preg_split("/[-(]/",$fullname);
$name = $e2[0]; $name = $e2[0];
$currPath .= ".".$name; $currPath .= ".".$name;
if($key == 0) { if($key == 0) {
$currPath = substr($currPath,1); $currPath = substr($currPath,1);
$table = $this->connection->getTable($name); $table = $this->connection->getTable($name);
$tname = $table->getTableName(); $tname = $table->getTableName();
if( ! isset($this->tableAliases[$currPath])) if( ! isset($this->tableAliases[$currPath]))
$this->tableIndexes[$tname] = 1; $this->tableIndexes[$tname] = 1;
$this->parts["from"][$tname] = true; $this->parts["from"][$tname] = true;
$this->tableAliases[$currPath] = $tname; $this->tableAliases[$currPath] = $tname;
$tableName = $tname; $tableName = $tname;
} else { } else {
$index += strlen($e[($key - 1)]) + 1; $index += strlen($e[($key - 1)]) + 1;
// the mark here is either '.' or ':' // the mark here is either '.' or ':'
$mark = substr($path,($index - 1),1); $mark = substr($path,($index - 1),1);
if(isset($this->tableAliases[$prevPath])) { if(isset($this->tableAliases[$prevPath])) {
$tname = $this->tableAliases[$prevPath]; $tname = $this->tableAliases[$prevPath];
} else } else
$tname = $table->getTableName(); $tname = $table->getTableName();
$fk = $table->getRelation($name); $fk = $table->getRelation($name);
$name = $fk->getTable()->getComponentName(); $name = $fk->getTable()->getComponentName();
$original = $fk->getTable()->getTableName(); $original = $fk->getTable()->getTableName();
if(isset($this->tableAliases[$currPath])) { if(isset($this->tableAliases[$currPath])) {
$tname2 = $this->tableAliases[$currPath]; $tname2 = $this->tableAliases[$currPath];
} else } else
$tname2 = $this->generateAlias($original); $tname2 = $this->generateAlias($original);
if($original !== $tname2) if($original !== $tname2)
$aliasString = $original." AS ".$tname2; $aliasString = $original." AS ".$tname2;
else else
$aliasString = $original; $aliasString = $original;
switch($mark): switch($mark):
case ":": case ":":
$join = 'INNER JOIN '; $join = 'INNER JOIN ';
break; break;
case ".": case ".":
$join = 'LEFT JOIN '; $join = 'LEFT JOIN ';
break; break;
default: default:
throw new Doctrine_Exception("Unknown operator '$mark'"); throw new Doctrine_Exception("Unknown operator '$mark'");
endswitch; endswitch;
if($fk->getType() == Doctrine_Relation::MANY_AGGREGATE || if($fk->getType() == Doctrine_Relation::MANY_AGGREGATE ||
$fk->getType() == Doctrine_Relation::MANY_COMPOSITE) { $fk->getType() == Doctrine_Relation::MANY_COMPOSITE) {
if( ! $loadFields) { if( ! $loadFields) {
$this->subqueryAliases[] = $tname2; $this->subqueryAliases[] = $tname2;
} }
$this->needsSubquery = true; $this->needsSubquery = true;
} }
if($fk instanceof Doctrine_Relation_ForeignKey || if($fk instanceof Doctrine_Relation_ForeignKey ||
$fk instanceof Doctrine_Relation_LocalKey) { $fk instanceof Doctrine_Relation_LocalKey) {
$this->parts["join"][$tname][$tname2] = $join.$aliasString." ON ".$tname.".".$fk->getLocal()." = ".$tname2.".".$fk->getForeign(); $this->parts["join"][$tname][$tname2] = $join.$aliasString." ON ".$tname.".".$fk->getLocal()." = ".$tname2.".".$fk->getForeign();
} elseif($fk instanceof Doctrine_Relation_Association) { } elseif($fk instanceof Doctrine_Relation_Association) {
$asf = $fk->getAssociationFactory(); $asf = $fk->getAssociationFactory();
$assocTableName = $asf->getTableName(); $assocTableName = $asf->getTableName();
if( ! $loadFields) { if( ! $loadFields) {
$this->subqueryAliases[] = $assocTableName; $this->subqueryAliases[] = $assocTableName;
} }
$this->parts["join"][$tname][$assocTableName] = $join.$assocTableName." ON ".$tname.".".$table->getIdentifier()." = ".$assocTableName.".".$fk->getLocal(); $this->parts["join"][$tname][$assocTableName] = $join.$assocTableName." ON ".$tname.".".$table->getIdentifier()." = ".$assocTableName.".".$fk->getLocal();
$this->parts["join"][$tname][$tname2] = $join.$aliasString." ON ".$tname2.".".$table->getIdentifier()." = ".$assocTableName.".".$fk->getForeign(); $this->parts["join"][$tname][$tname2] = $join.$aliasString." ON ".$tname2.".".$table->getIdentifier()." = ".$assocTableName.".".$fk->getForeign();
} }
$this->joins[$tname2] = $prevTable; $this->joins[$tname2] = $prevTable;
$table = $fk->getTable(); $table = $fk->getTable();
$this->tableAliases[$currPath] = $tname2; $this->tableAliases[$currPath] = $tname2;
$tableName = $tname2; $tableName = $tname2;
$this->relationStack[] = $fk; $this->relationStack[] = $fk;
} }
$this->tableStack[] = $table; $this->tableStack[] = $table;
if( ! isset($this->tables[$tableName])) { if( ! isset($this->tables[$tableName])) {
$this->tables[$tableName] = $table; $this->tables[$tableName] = $table;
if($loadFields) { if($loadFields) {
$this->parseFields($fullname, $tableName, $e2, $currPath); $this->parseFields($fullname, $tableName, $e2, $currPath);
} }
} }
$prevPath = $currPath; $prevPath = $currPath;
$prevTable = $tableName; $prevTable = $tableName;
} catch(Exception $e) { } catch(Exception $e) {
throw new Doctrine_Query_Exception($e->__toString()); throw new Doctrine_Query_Exception($e->__toString());
} }
} }
if($componentAlias !== false) { if($componentAlias !== false) {
$this->compAliases[$componentAlias] = $currPath; $this->compAliases[$componentAlias] = $currPath;
} }
return $table; return $table;
} }
/** /**
* parseFields * parseFields
* *
* @param string $fullName * @param string $fullName
* @param string $tableName * @param string $tableName
* @param array $exploded * @param array $exploded
* @param string $currPath * @param string $currPath
* @return void * @return void
*/ */
final public function parseFields($fullName, $tableName, array $exploded, $currPath) { final public function parseFields($fullName, $tableName, array $exploded, $currPath) {
$table = $this->tables[$tableName]; $table = $this->tables[$tableName];
$fields = array(); $fields = array();
if(strpos($fullName, "-") === false) { if(strpos($fullName, "-") === false) {
$fetchmode = $table->getAttribute(Doctrine::ATTR_FETCHMODE); $fetchmode = $table->getAttribute(Doctrine::ATTR_FETCHMODE);
if(isset($exploded[1])) { if(isset($exploded[1])) {
if(count($exploded) > 2) { if(count($exploded) > 2) {
$fields = $this->parseAggregateValues($fullName, $tableName, $exploded, $currPath); $fields = $this->parseAggregateValues($fullName, $tableName, $exploded, $currPath);
} elseif(count($exploded) == 2) { } elseif(count($exploded) == 2) {
$fields = explode(",",substr($exploded[1],0,-1)); $fields = explode(",",substr($exploded[1],0,-1));
} }
} }
} else { } else {
if(isset($exploded[1])) { if(isset($exploded[1])) {
$fetchmode = $this->parseFetchMode($exploded[1]); $fetchmode = $this->parseFetchMode($exploded[1]);
} else } else
$fetchmode = $table->getAttribute(Doctrine::ATTR_FETCHMODE); $fetchmode = $table->getAttribute(Doctrine::ATTR_FETCHMODE);
if(isset($exploded[2])) { if(isset($exploded[2])) {
if(substr_count($exploded[2], ")") > 1) { if(substr_count($exploded[2], ")") > 1) {
} else { } else {
$fields = explode(",",substr($exploded[2],0,-1)); $fields = explode(",",substr($exploded[2],0,-1));
} }
} }
} }
if( ! $this->aggregate) if( ! $this->aggregate)
$this->loadFields($table, $fetchmode, $fields, $currPath); $this->loadFields($table, $fetchmode, $fields, $currPath);
} }
/** /**
* parseAggregateFunction * parseAggregateFunction
* *
* @param string $func * @param string $func
* @param string $reference * @param string $reference
* @return string * @return string
*/ */
public function parseAggregateFunction($func,$reference) { public function parseAggregateFunction($func,$reference) {
$pos = strpos($func,"("); $pos = strpos($func,"(");
if($pos !== false) { if($pos !== false) {
$funcs = array(); $funcs = array();
$name = substr($func, 0, $pos); $name = substr($func, 0, $pos);
$func = substr($func, ($pos + 1), -1); $func = substr($func, ($pos + 1), -1);
$params = Doctrine_Query::bracketExplode($func, ",", "(", ")"); $params = Doctrine_Query::bracketExplode($func, ",", "(", ")");
foreach($params as $k => $param) { foreach($params as $k => $param) {
$params[$k] = $this->parseAggregateFunction($param,$reference); $params[$k] = $this->parseAggregateFunction($param,$reference);
} }
$funcs = $name."(".implode(", ", $params).")"; $funcs = $name."(".implode(", ", $params).")";
return $funcs; return $funcs;
} else { } else {
if( ! is_numeric($func)) { if( ! is_numeric($func)) {
$func = $this->getTableAlias($reference).".".$func; $func = $this->getTableAlias($reference).".".$func;
return $func; return $func;
} else { } else {
return $func; return $func;
} }
} }
} }
/** /**
* parseAggregateValues * parseAggregateValues
*/ */
public function parseAggregateValues($fullName, $tableName, array $exploded, $currPath) { public function parseAggregateValues($fullName, $tableName, array $exploded, $currPath) {
$this->aggregate = true; $this->aggregate = true;
$pos = strpos($fullName,"("); $pos = strpos($fullName,"(");
$name = substr($fullName, 0, $pos); $name = substr($fullName, 0, $pos);
$string = substr($fullName, ($pos + 1), -1); $string = substr($fullName, ($pos + 1), -1);
$exploded = Doctrine_Query::bracketExplode($string, ','); $exploded = Doctrine_Query::bracketExplode($string, ',');
foreach($exploded as $k => $value) { foreach($exploded as $k => $value) {
$func = $this->parseAggregateFunction($value, $currPath); $func = $this->parseAggregateFunction($value, $currPath);
$exploded[$k] = $func; $exploded[$k] = $func;
$this->parts["select"][] = $exploded[$k]; $this->parts["select"][] = $exploded[$k];
} }
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment