Doctrine 1.2.4
Doctrine_Query Class Reference

Inherits Doctrine_Query_Abstract, and Countable.

Public Member Functions

 __clone ()
 
 __toString ()
 
 addFrom ($from)
 
 addGroupBy ($groupby)
 
 addHaving ($having, $params=array())
 
 addOrderBy ($orderby)
 
 addPendingJoinCondition ($componentAlias, $joinCondition)
 
 addSelect ($select)
 
 addSqlQueryPart ($name, $part)
 
 addSqlTableAlias ($sqlTableAlias, $componentAlias)
 
 addWhere ($where, $params=array())
 
 adjustProcessedParam ($index)
 
 andWhere ($where, $params=array())
 
 andWhereIn ($expr, $params=array(), $not=false)
 
 andWhereNotIn ($expr, $params=array())
 
 buildInheritanceJoinSql ($name, $componentAlias)
 
 buildSqlQuery ($limitSubquery=true)
 
 calculateQueryCacheHash ()
 
 calculateResultCacheHash ($params=array())
 
 clearResultCache ()
 
 contains ($dql)
 
 copy (Doctrine_Query $query=null)
 
 copySubqueryInfo (Doctrine_Query_Abstract $query)
 
 count ($params=array())
 
 createSubquery ()
 
 delete ($from=null)
 
 distinct ($flag=true)
 
 execute ($params=array(), $hydrationMode=null)
 
 expireQueryCache ($expire=true)
 
 expireResultCache ($expire=true)
 
 fetchArray ($params=array())
 
 fetchOne ($params=array(), $hydrationMode=null)
 
 fixArrayParameterValues ($params=array())
 
 forUpdate ($flag=true)
 
 free ()
 
 from ($from)
 
 generateNewSqlTableAlias ($oldAlias)
 
 generateSqlTableAlias ($componentAlias, $tableName)
 
 getCachedForm ($customComponent=null)
 
 getComponentAlias ($sqlTableAlias)
 
 getConnection ()
 
 getCountQueryParams ($params=array())
 
 getCountSqlQuery ()
 
 getDql ()
 
 getDqlPart ($queryPart)
 
 getExpressionOwner ($expr)
 
 getFlattenedParams ($params=array())
 
 getInheritanceCondition ($componentAlias)
 
 getInternalParams ($params=array())
 
 getLimitSubquery ()
 
 getParams ()
 
 getQueryCacheDriver ()
 
 getQueryCacheLifeSpan ()
 
 getQueryComponent ($componentAlias)
 
 getQueryComponents ()
 
 getResultCacheDriver ()
 
 getResultCacheHash ($params=array())
 
 getResultCacheLifeSpan ()
 
 getRoot ()
 
 getRootAlias ()
 
 getRootDeclaration ()
 
 getSqlAggregateAlias ($dqlAlias)
 
 getSqlParts ()
 
 getSqlQuery ($params=array(), $limitSubquery=true)
 
 getSqlQuery ($params=array())
 
 getSqlQueryPart ($part)
 
 getSqlTableAlias ($componentAlias, $tableName=null)
 
 getSqlTableAliasSeed ($sqlTableAlias)
 
 getTableAliasMap ()
 
 getType ()
 
 getView ()
 
 groupBy ($groupby)
 
 hasAliasDeclaration ($componentAlias)
 
 hasSqlAggregateAlias ($dqlAlias)
 
 hasSqlTableAlias ($sqlTableAlias)
 
 having ($having, $params=array())
 
 innerJoin ($join, $params=array())
 
 isLimitSubqueryUsed ()
 
 isSubquery ($bool=null)
 
 leftJoin ($join, $params=array())
 
 limit ($limit)
 
 load ($path, $loadFields=true)
 
 loadRoot ($name, $componentAlias)
 
 offset ($offset)
 
 orderBy ($orderby)
 
 orWhere ($where, $params=array())
 
 orWhereIn ($expr, $params=array(), $not=false)
 
 orWhereNotIn ($expr, $params=array())
 
 parseClause ($clause)
 
 parseDqlQuery ($query, $clear=true)
 
 parseDqlQuery ($query)
 
 parseSelect ($dql)
 
 parseSelectField ($field)
 
 preQuery ()
 
 processPendingAggregates ()
 
 processPendingFields ($componentAlias)
 
 processPendingSubqueries ()
 
 query ($query, $params=array(), $hydrationMode=null)
 
 removeDqlQueryPart ($name)
 
 removeSqlQueryPart ($name)
 
 reset ()
 
 select ($select=null)
 
 set ($key, $value=null, $params=null)
 
 setConnection (Doctrine_Connection $connection)
 
 setOption ($name, $value)
 
 setParams (array $params=array())
 
 setQueryCacheLifeSpan ($timeToLive)
 
 setResultCacheHash ($resultCacheHash)
 
 setResultCacheLifeSpan ($timeToLive)
 
 setSqlQueryPart ($name, $part)
 
 setView (Doctrine_View $view)
 
 update ($from=null)
 
 useQueryCache ($driver=true, $timeToLive=null)
 
 useResultCache ($driver=true, $timeToLive=null, $resultCacheHash=null)
 
 where ($where, $params=array())
 
 whereIn ($expr, $params=array(), $not=false)
 
 whereNotIn ($expr, $params=array())
 

Static Public Member Functions

static create ($conn=null, $class=null)
 

Data Fields

const CREATE = 4
 
const DELETE = 1
 
const INSERT = 3
 
const SELECT = 0
 
const STATE_CLEAN = 1
 
const STATE_DIRECT = 3
 
const STATE_DIRTY = 2
 
const STATE_LOCKED = 4
 
const UPDATE = 2
 

Protected Member Functions

 _addDqlQueryPart ($queryPartName, $queryPart, $append=false)
 
 _buildSqlFromPart ($ignorePending=false)
 
 _buildSqlQueryBase ()
 
 _constructQueryFromCache ($cached)
 
 _execute ($params)
 
 _getDqlCallback ()
 
 _getDqlCallbackComponents ($params=array())
 
 _getParser ($name)
 
 _hasDqlQueryPart ($queryPartName)
 
 _killReference ($key)
 
 _preQuery ($params=array())
 
 _processDqlQueryPart ($queryPartName, $queryParts)
 
 _processPendingJoinConditions ($alias)
 
 _processWhereIn ($expr, $params=array(), $not=false)
 
 clear ()
 

Protected Attributes

 $_isSubquery
 
 $_needsSubquery = false
 

Detailed Description

Definition at line 59 of file Query.php.

Member Function Documentation

Doctrine_Query::__clone ( )

Magic method called after cloning process.

Returns
void

Definition at line 2186 of file Query.php.

{
$this->_parsers = array();
$this->_hydrator = clone $this->_hydrator;
// Subqueries share some information from the parent so it can intermingle
// with the dql of the main query. So when a subquery is cloned we need to
// kill those references or it causes problems
if ($this->isSubquery()) {
$this->_killReference('_params');
$this->_killReference('_tableAliasMap');
$this->_killReference('_queryComponents');
}
}
Doctrine_Query_Abstract::__toString ( )
inherited

toString magic call this method is automatically called when Doctrine_Query object is trying to be used as a string So, it it converted into its DQL correspondant

Returns
string DQL string

Definition at line 2139 of file Abstract.php.

{
return $this->getDql();
}
Doctrine_Query_Abstract::_addDqlQueryPart (   $queryPartName,
  $queryPart,
  $append = false 
)
protectedinherited

Adds a DQL part to the internal parts collection.

This method add the part specified to the array named by $queryPartName. Most part names support multiple parts addition.

See Also
$_dqlParts;
Doctrine_Query::getDqlPart()
Parameters
string$queryPartNameThe name of the query part.
string$queryPartThe actual query part to add.
boolean$appendWhether to append $queryPart to already existing parts under the same $queryPartName. Defaults to FALSE (previously added parts with the same name get overridden).

Definition at line 2043 of file Abstract.php.

{
// We should prevent nullable query parts
if ($queryPart === null) {
throw new Doctrine_Query_Exception('Cannot define NULL as part of query when defining \'' . $queryPartName . '\'.');
}
if ($append) {
$this->_dqlParts[$queryPartName][] = $queryPart;
} else {
$this->_dqlParts[$queryPartName] = array($queryPart);
}
$this->_state = Doctrine_Query::STATE_DIRTY;
return $this;
}
Doctrine_Query::_buildSqlFromPart (   $ignorePending = false)
protected

_buildSqlFromPart builds the from part of the query and returns it

Returns
string the query sql from part

Definition at line 1011 of file Query.php.

{
$q = '';
foreach ($this->_sqlParts['from'] as $k => $part) {
$e = explode(' ', $part);
if ($k === 0) {
if ( ! $ignorePending && $this->_type == self::SELECT) {
// We may still have pending conditions
$alias = count($e) > 1
? $this->getComponentAlias($e[1])
: null;
$where = $this->_processPendingJoinConditions($alias);
// apply inheritance to WHERE part
if ( ! empty($where)) {
if (count($this->_sqlParts['where']) > 0) {
$this->_sqlParts['where'][] = 'AND';
}
if (substr($where, 0, 1) === '(' && substr($where, -1) === ')') {
$this->_sqlParts['where'][] = $where;
} else {
$this->_sqlParts['where'][] = '(' . $where . ')';
}
}
}
$q .= $part;
continue;
}
// preserve LEFT JOINs only if needed
// Check if it's JOIN, if not add a comma separator instead of space
if ( ! preg_match('/\bJOIN\b/i', $part) && ! isset($this->_pendingJoinConditions[$k])) {
$q .= ', ' . $part;
} else {
if (substr($part, 0, 9) === 'LEFT JOIN') {
$aliases = array_merge($this->_subqueryAliases,
array_keys($this->_neededTables));
if ( ! in_array($e[3], $aliases) && ! in_array($e[2], $aliases) && ! empty($this->_pendingFields)) {
continue;
}
}
if ( ! $ignorePending && isset($this->_pendingJoinConditions[$k])) {
if (strpos($part, ' ON ') !== false) {
$part .= ' AND ';
} else {
$part .= ' ON ';
}
$part .= $this->_processPendingJoinConditions($k);
}
$componentAlias = $this->getComponentAlias($e[3]);
$string = $this->getInheritanceCondition($componentAlias);
if ($string) {
$part = $part . ' AND ' . $string;
}
$q .= ' ' . $part;
}
$this->_sqlParts['from'][$k] = $part;
}
return $q;
}
Doctrine_Query::_buildSqlQueryBase ( )
protected

_buildSqlQueryBase returns the base of the generated sql query On mysql driver special strategy has to be used for DELETE statements (where is this special strategy??)

Returns
string the base of the generated sql query

Definition at line 988 of file Query.php.

{
switch ($this->_type) {
case self::DELETE:
$q = 'DELETE FROM ';
break;
case self::UPDATE:
$q = 'UPDATE ';
break;
case self::SELECT:
$distinct = ($this->_sqlParts['distinct']) ? 'DISTINCT ' : '';
$q = 'SELECT ' . $distinct . implode(', ', $this->_sqlParts['select']) . ' FROM ';
break;
}
return $q;
}
Doctrine_Query_Abstract::_constructQueryFromCache (   $cached)
protectedinherited

Constructs the query from the cached form.

Parameters
stringThe cached query, in a serialized form.
Returns
array The custom component that was cached together with the essential query data. This can be either a result set (result caching) or an SQL query string (query caching).

Definition at line 1168 of file Abstract.php.

{
$cached = unserialize($cached);
$this->_tableAliasMap = $cached[2];
$customComponent = $cached[0];
$queryComponents = array();
$cachedComponents = $cached[1];
foreach ($cachedComponents as $alias => $components) {
$e = explode('.', $components['name']);
if (count($e) === 1) {
if ( ! $this->_passedConn && $manager->hasConnectionForComponent($e[0])) {
$this->_conn = $manager->getConnectionForComponent($e[0]);
}
$queryComponents[$alias]['table'] = $this->_conn->getTable($e[0]);
} else {
$queryComponents[$alias]['parent'] = $e[0];
$queryComponents[$alias]['relation'] = $queryComponents[$e[0]]['table']->getRelation($e[1]);
$queryComponents[$alias]['table'] = $queryComponents[$alias]['relation']->getTable();
}
if (isset($components['agg'])) {
$queryComponents[$alias]['agg'] = $components['agg'];
}
if (isset($components['map'])) {
$queryComponents[$alias]['map'] = $components['map'];
}
}
$this->_queryComponents = $queryComponents;
return $customComponent;
}
Doctrine_Query_Abstract::_execute (   $params)
protectedinherited

_execute

Parameters
array$params
Returns
PDOStatement The executed PDOStatement.

Definition at line 912 of file Abstract.php.

{
// Apply boolean conversion in DQL params
$params = $this->_conn->convertBooleans($params);
foreach ($this->_params as $k => $v) {
$this->_params[$k] = $this->_conn->convertBooleans($v);
}
$dqlParams = $this->getFlattenedParams($params);
// Check if we're not using a Doctrine_View
if ( ! $this->_view) {
if ($this->_queryCache !== false && ($this->_queryCache || $this->_conn->getAttribute(Doctrine_Core::ATTR_QUERY_CACHE))) {
$queryCacheDriver = $this->getQueryCacheDriver();
$hash = $this->calculateQueryCacheHash();
$cached = $queryCacheDriver->fetch($hash);
// If we have a cached query...
if ($cached) {
// Rebuild query from cache
$query = $this->_constructQueryFromCache($cached);
// Assign building/execution specific params
$this->_params['exec'] = $params;
// Initialize prepared parameters array
$this->_execParams = $this->getFlattenedParams();
// Fix possible array parameter values in SQL params
} else {
// Generate SQL or pick already processed one
$query = $this->getSqlQuery($params);
// Check again because getSqlQuery() above could have flipped the _queryCache flag
// if this query contains the limit sub query algorithm we don't need to cache it
if ($this->_queryCache !== false && ($this->_queryCache || $this->_conn->getAttribute(Doctrine_Core::ATTR_QUERY_CACHE))) {
// Convert query into a serialized form
$serializedQuery = $this->getCachedForm($query);
// Save cached query
$queryCacheDriver->save($hash, $serializedQuery, $this->getQueryCacheLifeSpan());
}
}
} else {
$query = $this->getSqlQuery($params);
}
} else {
$query = $this->_view->getSelectSql();
}
// Get prepared SQL params for execution
$params = $this->getInternalParams();
if ($this->isLimitSubqueryUsed() &&
$this->_conn->getAttribute(Doctrine_Core::ATTR_DRIVER_NAME) !== 'mysql') {
$params = array_merge((array) $params, (array) $params);
}
if ($this->_type !== self::SELECT) {
return $this->_conn->exec($query, $params);
}
$stmt = $this->_conn->execute($query, $params);
$this->_params['exec'] = array();
return $stmt;
}
Doctrine_Query_Abstract::_getDqlCallback ( )
protectedinherited

Get the dql call back for this query

Returns
array $callback

Definition at line 1059 of file Abstract.php.

{
$callback = false;
if ( ! empty($this->_dqlParts['from'])) {
switch ($this->_type) {
case self::DELETE:
$callback = array(
'callback' => 'preDqlDelete',
'const' => Doctrine_Event::RECORD_DQL_DELETE
);
break;
case self::UPDATE:
$callback = array(
'callback' => 'preDqlUpdate',
'const' => Doctrine_Event::RECORD_DQL_UPDATE
);
break;
case self::SELECT:
$callback = array(
'callback' => 'preDqlSelect',
'const' => Doctrine_Event::RECORD_DQL_SELECT
);
break;
}
}
return $callback;
}
Doctrine_Query_Abstract::_getDqlCallbackComponents (   $params = array())
protectedinherited

Returns an array of components to execute the query callbacks for

Parameters
array$params
Returns
array $components

Definition at line 1129 of file Abstract.php.

{
$componentsBefore = array();
if ($this->isSubquery()) {
$componentsBefore = $this->getQueryComponents();
}
$copy = $this->copy();
$copy->getSqlQuery($params, false);
$componentsAfter = $copy->getQueryComponents();
$this->_rootAlias = $copy->getRootAlias();
$copy->free();
if ($componentsBefore !== $componentsAfter) {
return array_diff($componentsAfter, $componentsBefore);
} else {
return $componentsAfter;
}
}
Doctrine_Query_Abstract::_getParser (   $name)
protectedinherited

_getParser parser lazy-loader

Exceptions
Doctrine_Query_Exceptionif unknown parser name given
Returns
Doctrine_Query_Part
Todo:
Doc/Description: What is the parameter for? Which parsers are available?

Definition at line 2097 of file Abstract.php.

{
if ( ! isset($this->_parsers[$name])) {
$class = 'Doctrine_Query_' . ucwords(strtolower($name));
if ( ! class_exists($class)) {
throw new Doctrine_Query_Exception('Unknown parser ' . $name);
}
$this->_parsers[$name] = new $class($this, $this->_tokenizer);
}
return $this->_parsers[$name];
}
Doctrine_Query_Abstract::_hasDqlQueryPart (   $queryPartName)
protectedinherited

Checks if there's at least one DQL part defined to the internal parts collection.

Parameters
string$queryPartNameThe name of the query part.
Returns
boolean

Definition at line 2024 of file Abstract.php.

{
return count($this->_dqlParts[$queryPartName]) > 0;
}
Doctrine_Query::_killReference (   $key)
protected

Kill the reference for the passed class property. This method simply copies the value to a temporary variable and then unsets the reference and re-assigns the old value but not by reference

Parameters
string$key

Definition at line 2208 of file Query.php.

{
$tmp = $this->$key;
unset($this->$key);
$this->$key = $tmp;
}
Doctrine_Query_Abstract::_preQuery (   $params = array())
protectedinherited

Pre query method which invokes the pre*Query() methods on the model instance or any attached record listeners

Returns
void

Definition at line 1094 of file Abstract.php.

{
if ( ! $this->_preQueried && $this->getConnection()->getAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS)) {
$this->_preQueried = true;
$callback = $this->_getDqlCallback();
// if there is no callback for the query type, then we can return early
if ( ! $callback) {
return;
}
foreach ($this->_getDqlCallbackComponents($params) as $alias => $component) {
$table = $component['table'];
$record = $table->getRecordInstance();
// Trigger preDql*() callback event
$params = array('component' => $component, 'alias' => $alias);
$event = new Doctrine_Event($record, $callback['const'], $this, $params);
$record->$callback['callback']($event);
$table->getRecordListener()->$callback['callback']($event);
}
}
// Invoke preQuery() hook on Doctrine_Query for child classes which implement this hook
$this->preQuery();
}
Doctrine_Query_Abstract::_processDqlQueryPart (   $queryPartName,
  $queryParts 
)
protectedinherited

_processDqlQueryPart parses given query part

Parameters
string$queryPartNamethe name of the query part
array$queryPartsan array containing the query part data
Returns
Doctrine_Query this object
Todo:
Better description. "parses given query part" ??? Then wheres the difference between process/parseQueryPart? I suppose this does something different.

Definition at line 2070 of file Abstract.php.

{
$this->removeSqlQueryPart($queryPartName);
if (is_array($queryParts) && ! empty($queryParts)) {
foreach ($queryParts as $queryPart) {
$parser = $this->_getParser($queryPartName);
$sql = $parser->parse($queryPart);
if (isset($sql)) {
if ($queryPartName == 'limit' || $queryPartName == 'offset') {
$this->setSqlQueryPart($queryPartName, $sql);
} else {
$this->addSqlQueryPart($queryPartName, $sql);
}
}
}
}
}
Doctrine_Query::_processPendingJoinConditions (   $alias)
protected

Processes the pending join conditions, used for dynamically add conditions to root component/joined components without interfering in the main dql handling.

Parameters
string$aliasComponent Alias
Returns
Processed pending conditions

Definition at line 1092 of file Query.php.

{
$parts = array();
if ($alias !== null && isset($this->_pendingJoinConditions[$alias])) {
$parser = new Doctrine_Query_JoinCondition($this, $this->_tokenizer);
foreach ($this->_pendingJoinConditions[$alias] as $joinCondition) {
$parts[] = $parser->parse($joinCondition);
}
// FIX #1860 and #1876: Cannot unset them, otherwise query cannot be reused later
//unset($this->_pendingJoinConditions[$alias]);
}
return (count($parts) > 0 ? '(' . implode(') AND (', $parts) . ')' : '');
}
Doctrine_Query_Abstract::_processWhereIn (   $expr,
  $params = array(),
  $not = false 
)
protectedinherited

Definition at line 1404 of file Abstract.php.

{
$params = (array) $params;
// if there's no params, return (else we'll get a WHERE IN (), invalid SQL)
if (count($params) == 0) {
throw new Doctrine_Query_Exception('You must pass at least one parameter when using an IN() condition.');
}
$a = array();
foreach ($params as $k => $value) {
if ($value instanceof Doctrine_Expression) {
$value = $value->getSql();
unset($params[$k]);
} else {
$value = '?';
}
$a[] = $value;
}
$this->_params['where'] = array_merge($this->_params['where'], $params);
return $expr . ($not === true ? ' NOT' : '') . ' IN (' . implode(', ', $a) . ')';
}
Doctrine_Query_Abstract::addFrom (   $from)
inherited

addFrom adds fields to the FROM part of the query

Parameters
string$fromQuery FROM part
Returns
Doctrine_Query

Definition at line 1272 of file Abstract.php.

{
return $this->_addDqlQueryPart('from', $from, true);
}
Doctrine_Query_Abstract::addGroupBy (   $groupby)
inherited

Adds fields to the GROUP BY part of the query. $q->groupBy('u.id');

Parameters
string$groupbyQuery GROUP BY part
Returns
Doctrine_Query

Definition at line 1479 of file Abstract.php.

{
return $this->_addDqlQueryPart('groupby', $groupby, true);
}
Doctrine_Query_Abstract::addHaving (   $having,
  $params = array() 
)
inherited

Adds conditions to the HAVING part of the query.

This methods add HAVING clauses. These clauses are used to narrow the results by operating on aggregated values. $q->having('num_phonenumbers > ?', 1);

Parameters
string$havingQuery HAVING part
mixed$paramsan array of parameters or a simple scalar
Returns
Doctrine_Query

Definition at line 1497 of file Abstract.php.

{
if (is_array($params)) {
$this->_params['having'] = array_merge($this->_params['having'], $params);
} else {
$this->_params['having'][] = $params;
}
return $this->_addDqlQueryPart('having', $having, true);
}
Doctrine_Query_Abstract::addOrderBy (   $orderby)
inherited

addOrderBy adds fields to the ORDER BY part of the query

Parameters
string$orderbyQuery ORDER BY part
Returns
Doctrine_Query

Definition at line 1514 of file Abstract.php.

{
return $this->_addDqlQueryPart('orderby', $orderby, true);
}
Doctrine_Query::addPendingJoinCondition (   $componentAlias,
  $joinCondition 
)

addPendingJoinCondition

Parameters
string$componentAliascomponent alias
string$joinConditiondql join condition
Returns
Doctrine_Query this object

Definition at line 249 of file Query.php.

{
if ( ! isset($this->_pendingJoinConditions[$componentAlias])) {
$this->_pendingJoinConditions[$componentAlias] = array();
}
$this->_pendingJoinConditions[$componentAlias][] = $joinCondition;
}
Doctrine_Query_Abstract::addSelect (   $select)
inherited

Adds fields or aliased functions.

This method adds fields or dbms functions to the SELECT query part. $query->addSelect('COUNT(p.id) as num_phonenumbers');

Parameters
string$selectQuery SELECT part
Returns
Doctrine_Query

Definition at line 1246 of file Abstract.php.

{
return $this->_addDqlQueryPart('select', $select, true);
}
Doctrine_Query_Abstract::addSqlQueryPart (   $name,
  $part 
)
inherited

addSqlQueryPart adds an SQL query part to the SQL query part array

Parameters
string$namethe name of the query part to be added
string$partquery part string
Exceptions
Doctrine_Query_Exceptionif trying to add unknown query part
Returns
Doctrine_Query this object

Definition at line 426 of file Abstract.php.

{
if ( ! isset($this->_sqlParts[$name])) {
throw new Doctrine_Query_Exception('Unknown query part ' . $name);
}
if (is_array($part)) {
$this->_sqlParts[$name] = array_merge($this->_sqlParts[$name], $part);
} else {
$this->_sqlParts[$name][] = $part;
}
return $this;
}
Doctrine_Query_Abstract::addSqlTableAlias (   $sqlTableAlias,
  $componentAlias 
)
inherited

addSqlTableAlias adds an SQL table alias and associates it a component alias

Parameters
string$componentAliasthe alias for the query component associated with given tableAlias
string$tableAliasthe table alias to be added
Returns
Doctrine_Query_Abstract

Definition at line 1259 of file Abstract.php.

{
$this->_tableAliasMap[$sqlTableAlias] = $componentAlias;
return $this;
}
Doctrine_Query_Abstract::addWhere (   $where,
  $params = array() 
)
inherited

Alias for

See Also
andWhere().
Returns
Doctrine_Query this object

Definition at line 1281 of file Abstract.php.

{
return $this->andWhere($where, $params);
}
Doctrine_Query::adjustProcessedParam (   $index)

Adjust the processed param index for "foo.bar IN ?" support

Definition at line 367 of file Query.php.

{
// Retrieve all params
$params = $this->getInternalParams();
// Retrieve already processed values
$first = array_slice($params, 0, $index);
$last = array_slice($params, $index, count($params) - $index);
// Include array as values splicing the params array
array_splice($last, 0, 1, $last[0]);
// Put all param values into a single index
$this->_execParams = array_merge($first, $last);
}
Doctrine_Query_Abstract::andWhere (   $where,
  $params = array() 
)
inherited

Adds conditions to the WHERE part of the query. $q->andWhere('u.birthDate > ?', '1975-01-01');

Parameters
string$whereQuery WHERE part
mixed$paramsAn array of parameters or a simple scalar
Returns
Doctrine_Query

Definition at line 1296 of file Abstract.php.

{
if (is_array($params)) {
$this->_params['where'] = array_merge($this->_params['where'], $params);
} else {
$this->_params['where'][] = $params;
}
if ($this->_hasDqlQueryPart('where')) {
$this->_addDqlQueryPart('where', 'AND', true);
}
return $this->_addDqlQueryPart('where', $where, true);
}
Doctrine_Query_Abstract::andWhereIn (   $expr,
  $params = array(),
  $not = false 
)
inherited

Adds IN condition to the query WHERE part $q->whereIn('u.id', array(10, 23, 44));

Parameters
string$exprThe operand of the IN
mixed$paramsAn array of parameters or a simple scalar
boolean$notWhether or not to use NOT in front of IN. Defaults to false (simple IN clause)
Returns
Doctrine_Query this object.

Definition at line 1360 of file Abstract.php.

{
// if there's no params, return (else we'll get a WHERE IN (), invalid SQL)
if (isset($params) and (count($params) == 0)) {
return $this;
}
if ($this->_hasDqlQueryPart('where')) {
$this->_addDqlQueryPart('where', 'AND', true);
}
return $this->_addDqlQueryPart('where', $this->_processWhereIn($expr, $params, $not), true);
}
Doctrine_Query_Abstract::andWhereNotIn (   $expr,
  $params = array() 
)
inherited

Adds NOT IN condition to the query WHERE part Alias for

See Also
whereNotIn().
Parameters
string$exprThe operand of the NOT IN
mixed$paramsAn array of parameters or a simple scalar
Returns
Doctrine_Query

Definition at line 1453 of file Abstract.php.

{
return $this->andWhereIn($expr, $params, true);
}
Doctrine_Query::buildInheritanceJoinSql (   $name,
  $componentAlias 
)
Todo:
DESCRIBE ME!
Parameters
string$namecomponent class name
string$componentAliasalias of the component in the dql
Returns
string query part

Definition at line 1971 of file Query.php.

{
// get the connection for the component
if ( ! $this->_passedConn && $manager->hasConnectionForComponent($name)) {
$this->_conn = $manager->getConnectionForComponent($name);
}
$table = $this->_conn->getTable($name);
$tableName = $table->getTableName();
// get the short alias for this table
$tableAlias = $this->getSqlTableAlias($componentAlias, $tableName);
$queryPart = '';
foreach ($table->getOption('joinedParents') as $parent) {
$parentTable = $this->_conn->getTable($parent);
$parentAlias = $componentAlias . '.' . $parent;
// get the short alias for the parent table
$parentTableAlias = $this->getSqlTableAlias($parentAlias, $parentTable->getTableName());
$queryPart .= ' LEFT JOIN ' . $this->_conn->quoteIdentifier($parentTable->getTableName())
. ' ' . $this->_conn->quoteIdentifier($parentTableAlias) . ' ON ';
//Doctrine_Core::dump($table->getIdentifier());
foreach ((array) $table->getIdentifier() as $identifier) {
$column = $table->getColumnName($identifier);
$queryPart .= $this->_conn->quoteIdentifier($tableAlias)
. '.' . $this->_conn->quoteIdentifier($column)
. ' = ' . $this->_conn->quoteIdentifier($parentTableAlias)
. '.' . $this->_conn->quoteIdentifier($column);
}
}
return $queryPart;
}
Doctrine_Query::buildSqlQuery (   $limitSubquery = true)

Build the SQL query from the DQL

Parameters
bool$limitSubqueryWhether or not to try and apply the limit subquery algorithm
Returns
string $sql The generated SQL string

Definition at line 1142 of file Query.php.

{
// reset the state
if ( ! $this->isSubquery()) {
$this->_queryComponents = array();
$this->_pendingAggregates = array();
$this->_aggregateAliasMap = array();
}
$this->reset();
// invoke the preQuery hook
$this->_preQuery();
// process the DQL parts => generate the SQL parts.
// this will also populate the $_queryComponents.
foreach ($this->_dqlParts as $queryPartName => $queryParts) {
// If we are parsing FROM clause, we'll need to diff the queryComponents later
if ($queryPartName == 'from') {
// Pick queryComponents before processing
$queryComponentsBefore = $this->getQueryComponents();
}
// FIX #1667: _sqlParts are cleaned inside _processDqlQueryPart.
if ($queryPartName != 'forUpdate') {
$this->_processDqlQueryPart($queryPartName, $queryParts);
}
// We need to define the root alias
if ($queryPartName == 'from') {
// Pick queryComponents aftr processing
$queryComponentsAfter = $this->getQueryComponents();
// Root alias is the key of difference of query components
$diffQueryComponents = array_diff_key($queryComponentsAfter, $queryComponentsBefore);
$this->_rootAlias = key($diffQueryComponents);
}
}
$this->_state = self::STATE_CLEAN;
// Proceed with the generated SQL
if (empty($this->_sqlParts['from'])) {
return false;
}
$needsSubQuery = false;
$subquery = '';
$map = $this->getRootDeclaration();
$table = $map['table'];
$rootAlias = $this->getRootAlias();
if ( ! empty($this->_sqlParts['limit']) && $this->_needsSubquery &&
$table->getAttribute(Doctrine_Core::ATTR_QUERY_LIMIT) == Doctrine_Core::LIMIT_RECORDS) {
// We do not need a limit-subquery if DISTINCT is used
// and the selected fields are either from the root component or from a localKey relation (hasOne)
// (i.e. DQL: SELECT DISTINCT u.id FROM User u LEFT JOIN u.phonenumbers LIMIT 5).
if(!$this->_sqlParts['distinct']) {
$this->_isLimitSubqueryUsed = true;
$needsSubQuery = true;
} else {
foreach( array_keys($this->_pendingFields) as $alias){
//no subquery for root fields
if($alias == $this->getRootAlias()){
continue;
}
//no subquery for ONE relations
if(isset($this->_queryComponents[$alias]['relation']) &&
$this->_queryComponents[$alias]['relation']->getType() == Doctrine_Relation::ONE){
continue;
}
$this->_isLimitSubqueryUsed = true;
$needsSubQuery = true;
}
}
}
$sql = array();
if ( ! empty($this->_pendingFields)) {
foreach ($this->_queryComponents as $alias => $map) {
$fieldSql = $this->processPendingFields($alias);
if ( ! empty($fieldSql)) {
$sql[] = $fieldSql;
}
}
}
if ( ! empty($sql)) {
array_unshift($this->_sqlParts['select'], implode(', ', $sql));
}
$this->_pendingFields = array();
// build the basic query
$q = $this->_buildSqlQueryBase();
$q .= $this->_buildSqlFromPart();
if ( ! empty($this->_sqlParts['set'])) {
$q .= ' SET ' . implode(', ', $this->_sqlParts['set']);
}
$string = $this->getInheritanceCondition($this->getRootAlias());
// apply inheritance to WHERE part
if ( ! empty($string)) {
if (count($this->_sqlParts['where']) > 0) {
$this->_sqlParts['where'][] = 'AND';
}
if (substr($string, 0, 1) === '(' && substr($string, -1) === ')') {
$this->_sqlParts['where'][] = $string;
} else {
$this->_sqlParts['where'][] = '(' . $string . ')';
}
}
$modifyLimit = true;
$limitSubquerySql = '';
if ( ( ! empty($this->_sqlParts['limit']) || ! empty($this->_sqlParts['offset'])) && $needsSubQuery && $limitSubquery) {
$subquery = $this->getLimitSubquery();
// what about composite keys?
$idColumnName = $table->getColumnName($table->getIdentifier());
switch (strtolower($this->_conn->getDriverName())) {
case 'mysql':
$this->useQueryCache(false);
// mysql doesn't support LIMIT in subqueries
$list = $this->_conn->execute($subquery, $this->_execParams)->fetchAll(Doctrine_Core::FETCH_COLUMN);
$subquery = implode(', ', array_map(array($this->_conn, 'quote'), $list));
break;
case 'pgsql':
$subqueryAlias = $this->_conn->quoteIdentifier('doctrine_subquery_alias');
// pgsql needs special nested LIMIT subquery
$subquery = 'SELECT ' . $subqueryAlias . '.' . $this->_conn->quoteIdentifier($idColumnName)
. ' FROM (' . $subquery . ') AS ' . $subqueryAlias;
break;
}
$field = $this->getSqlTableAlias($rootAlias) . '.' . $idColumnName;
// FIX #1868: If not ID under MySQL is found to be restricted, restrict pk column for null
// (which will lead to a return of 0 items)
$limitSubquerySql = $this->_conn->quoteIdentifier($field)
. (( ! empty($subquery)) ? ' IN (' . $subquery . ')' : ' IS NULL')
. ((count($this->_sqlParts['where']) > 0) ? ' AND ' : '');
$modifyLimit = false;
}
// FIX #DC-26: Include limitSubquerySql as major relevance in conditions
$emptyWhere = empty($this->_sqlParts['where']);
if ( ! ($emptyWhere && $limitSubquerySql == '')) {
$where = implode(' ', $this->_sqlParts['where']);
$where = ($where == '' || (substr($where, 0, 1) === '(' && substr($where, -1) === ')'))
? $where : '(' . $where . ')';
$q .= ' WHERE ' . $limitSubquerySql . $where;
// . (($limitSubquerySql == '' && count($this->_sqlParts['where']) == 1) ? substr($where, 1, -1) : $where);
}
// Fix the orderbys so we only have one orderby per value
foreach ($this->_sqlParts['orderby'] as $k => $orderBy) {
$e = explode(', ', $orderBy);
unset($this->_sqlParts['orderby'][$k]);
foreach ($e as $v) {
$this->_sqlParts['orderby'][] = $v;
}
}
// Add the default orderBy statements defined in the relationships and table classes
// Only do this for SELECT queries
if ($this->_type === self::SELECT) {
foreach ($this->_queryComponents as $alias => $map) {
$sqlAlias = $this->getSqlTableAlias($alias);
if (isset($map['relation'])) {
$orderBy = $map['relation']->getOrderByStatement($sqlAlias, true);
if ($orderBy == $map['relation']['orderBy']) {
if (isset($map['ref'])) {
$orderBy = $map['relation']['refTable']->processOrderBy($sqlAlias, $map['relation']['orderBy'], true);
} else {
$orderBy = null;
}
}
} else {
$orderBy = $map['table']->getOrderByStatement($sqlAlias, true);
}
if ($orderBy) {
$e = explode(',', $orderBy);
$e = array_map('trim', $e);
foreach ($e as $v) {
if ( ! in_array($v, $this->_sqlParts['orderby'])) {
$this->_sqlParts['orderby'][] = $v;
}
}
}
}
}
$q .= ( ! empty($this->_sqlParts['groupby'])) ? ' GROUP BY ' . implode(', ', $this->_sqlParts['groupby']) : '';
$q .= ( ! empty($this->_sqlParts['having'])) ? ' HAVING ' . implode(' AND ', $this->_sqlParts['having']): '';
$q .= ( ! empty($this->_sqlParts['orderby'])) ? ' ORDER BY ' . implode(', ', $this->_sqlParts['orderby']) : '';
if ($modifyLimit) {
$q = $this->_conn->modifyLimitQuery($q, $this->_sqlParts['limit'], $this->_sqlParts['offset']);
}
$q .= $this->_sqlParts['forUpdate'] === true ? ' FOR UPDATE ' : '';
$this->_sql = $q;
$this->clear();
return $q;
}
Doctrine_Query_Abstract::calculateQueryCacheHash ( )
inherited

calculateQueryCacheHash calculate hash key for query cache

Returns
string the hash

Definition at line 867 of file Abstract.php.

{
$dql = $this->getDql();
$hash = md5($dql . var_export($this->_pendingJoinConditions, true) . 'DOCTRINE_QUERY_CACHE_SALT');
return $hash;
}
Doctrine_Query_Abstract::calculateResultCacheHash (   $params = array())
inherited

calculateResultCacheHash calculate hash key for result cache

Parameters
array$params
Returns
string the hash

Definition at line 881 of file Abstract.php.

{
$dql = $this->getDql();
$conn = $this->getConnection();
$params = $this->getFlattenedParams($params);
$hash = md5($this->_hydrator->getHydrationMode() . $conn->getName() . $conn->getOption('dsn') . $dql . var_export($this->_pendingJoinConditions, true) . var_export($params, true));
return $hash;
}
Doctrine_Query::clear ( )
protected

Clears all the sql parts.

Definition at line 198 of file Query.php.

{
$this->_preQueried = false;
$this->_pendingJoinConditions = array();
$this->_state = self::STATE_DIRTY;
}
Doctrine_Query_Abstract::clearResultCache ( )
inherited

Clear the result cache entry for this query

Returns
void

Definition at line 1873 of file Abstract.php.

{
->delete($this->getResultCacheHash());
return $this;
}
Doctrine_Query::contains (   $dql)

contains

Method to check if a arbitrary piece of dql exists

Parameters
string$dqlArbitrary piece of dql to check for
Returns
boolean

Definition at line 422 of file Query.php.

{
return stripos($this->getDql(), $dql) === false ? false : true;
}
Doctrine_Query::copy ( Doctrine_Query  $query = null)

Copies a Doctrine_Query object.

Returns
Doctrine_Query Copy of the Doctrine_Query instance.

Definition at line 2170 of file Query.php.

{
if ( ! $query) {
$query = $this;
}
$new = clone $query;
return $new;
}
Doctrine_Query_Abstract::copySubqueryInfo ( Doctrine_Query_Abstract  $query)
inherited

copySubqueryInfo copy aliases from another Hydrate object

this method is needed by DQL subqueries which need the aliases of the parent query

Parameters
Doctrine_Hydrate$querythe query object from which the aliases are copied from
Returns
Doctrine_Query this object

Definition at line 760 of file Abstract.php.

{
$this->_params =& $query->_params;
$this->_tableAliasMap =& $query->_tableAliasMap;
$this->_queryComponents =& $query->_queryComponents;
$this->_tableAliasSeeds = $query->_tableAliasSeeds;
return $this;
}
Doctrine_Query::count (   $params = array())

Fetches the count of the query.

This method executes the main query without all the selected fields, ORDER BY part, LIMIT part and OFFSET part.

Example: Main query: SELECT u.*, p.phonenumber FROM User u LEFT JOIN u.Phonenumber p WHERE p.phonenumber = '123 123' LIMIT 10

The modified DQL query: SELECT COUNT(DISTINCT u.id) FROM User u LEFT JOIN u.Phonenumber p WHERE p.phonenumber = '123 123'

Parameters
array$paramsan array of prepared statement parameters
Returns
integer the count of this query

Definition at line 2111 of file Query.php.

{
$q = $this->getCountSqlQuery();
$params = $this->getCountQueryParams($params);
$params = $this->_conn->convertBooleans($params);
if ($this->_resultCache) {
$conn = $this->getConnection();
$cacheDriver = $this->getResultCacheDriver();
$hash = $this->getResultCacheHash($params).'_count';
$cached = ($this->_expireResultCache) ? false : $cacheDriver->fetch($hash);
if ($cached === false) {
// cache miss
$results = $this->getConnection()->fetchAll($q, $params);
$cacheDriver->save($hash, serialize($results), $this->getResultCacheLifeSpan());
} else {
$results = unserialize($cached);
}
} else {
$results = $this->getConnection()->fetchAll($q, $params);
}
if (count($results) > 1) {
$count = count($results);
} else {
if (isset($results[0])) {
$results[0] = array_change_key_case($results[0], CASE_LOWER);
$count = $results[0]['num_results'];
} else {
$count = 0;
}
}
return (int) $count;
}
static Doctrine_Query::create (   $conn = null,
  $class = null 
)
static

create returns a new Doctrine_Query object

Parameters
Doctrine_Connection$connoptional connection parameter
string$classQuery class to instantiate
Returns
Doctrine_Query

Definition at line 186 of file Query.php.

{
if ( ! $class) {
->getAttribute(Doctrine_Core::ATTR_QUERY_CLASS);
}
return new $class($conn);
}
Doctrine_Query::createSubquery ( )

createSubquery creates a subquery

Returns
Doctrine_Hydrate

Definition at line 228 of file Query.php.

{
$class = get_class($this);
$obj = new $class();
// copy the aliases to the subquery
$obj->copySubqueryInfo($this);
// this prevents the 'id' being selected, re ticket #307
$obj->isSubquery(true);
return $obj;
}
Doctrine_Query_Abstract::delete (   $from = null)
inherited

delete sets the query type to DELETE

Returns
Doctrine_Query

Definition at line 1571 of file Abstract.php.

{
$this->_type = self::DELETE;
if ($from != null) {
return $this->_addDqlQueryPart('from', $from);
}
return $this;
}
Doctrine_Query_Abstract::distinct (   $flag = true)
inherited

distinct Makes the query SELECT DISTINCT. $q->distinct();

Parameters
bool$flagWhether or not the SELECT is DISTINCT (default true).
Returns
Doctrine_Query

Definition at line 1546 of file Abstract.php.

{
$this->_sqlParts['distinct'] = (bool) $flag;
return $this;
}
Doctrine_Query_Abstract::execute (   $params = array(),
  $hydrationMode = null 
)
inherited

execute executes the query and populates the data set

Parameters
array$params
Returns
Doctrine_Collection the root collection

Definition at line 990 of file Abstract.php.

{
// Clean any possible processed params
$this->_execParams = array();
if (empty($this->_dqlParts['from']) && empty($this->_sqlParts['from'])) {
throw new Doctrine_Query_Exception('You must have at least one component specified in your from.');
}
$dqlParams = $this->getFlattenedParams($params);
$this->_preQuery($dqlParams);
if ($hydrationMode !== null) {
$this->_hydrator->setHydrationMode($hydrationMode);
}
$hydrationMode = $this->_hydrator->getHydrationMode();
if ($this->_resultCache && $this->_type == self::SELECT) {
$cacheDriver = $this->getResultCacheDriver();
$hash = $this->getResultCacheHash($params);
$cached = ($this->_expireResultCache) ? false : $cacheDriver->fetch($hash);
if ($cached === false) {
// cache miss
$stmt = $this->_execute($params);
$this->_hydrator->setQueryComponents($this->_queryComponents);
$result = $this->_hydrator->hydrateResultSet($stmt, $this->_tableAliasMap);
$cached = $this->getCachedForm($result);
$cacheDriver->save($hash, $cached, $this->getResultCacheLifeSpan());
} else {
$result = $this->_constructQueryFromCache($cached);
}
} else {
$stmt = $this->_execute($params);
if (is_integer($stmt)) {
$result = $stmt;
} else {
$this->_hydrator->setQueryComponents($this->_queryComponents);
if ($this->_type == self::SELECT && $hydrationMode == Doctrine_Core::HYDRATE_ON_DEMAND) {
$hydrationDriver = $this->_hydrator->getHydratorDriver($hydrationMode, $this->_tableAliasMap);
$result = new Doctrine_Collection_OnDemand($stmt, $hydrationDriver, $this->_tableAliasMap);
} else {
$result = $this->_hydrator->hydrateResultSet($stmt, $this->_tableAliasMap);
}
}
}
if ($this->getConnection()->getAttribute(Doctrine_Core::ATTR_AUTO_FREE_QUERY_OBJECTS)) {
$this->free();
}
return $result;
}
Doctrine_Query_Abstract::expireQueryCache (   $expire = true)
inherited

expireQueryCache

Parameters
boolean$expirewhether or not to force cache expiration
Returns
Doctrine_Query this object

Definition at line 1920 of file Abstract.php.

{
$this->_expireQueryCache = $expire;
return $this;
}
Doctrine_Query_Abstract::expireResultCache (   $expire = true)
inherited

expireCache

Parameters
boolean$expirewhether or not to force cache expiration
Returns
Doctrine_Query this object

Definition at line 1908 of file Abstract.php.

{
$this->_expireResultCache = $expire;
return $this;
}
Doctrine_Query::fetchArray (   $params = array())

fetchArray Convenience method to execute using array fetching as hydration mode.

Parameters
string$params
Returns
array

Definition at line 265 of file Query.php.

{
return $this->execute($params, Doctrine_Core::HYDRATE_ARRAY);
}
Doctrine_Query::fetchOne (   $params = array(),
  $hydrationMode = null 
)

fetchOne Convenience method to execute the query and return the first item of the collection.

Parameters
string$paramsQuery parameters
int$hydrationModeHydration mode: see Doctrine_Core::HYDRATE_* constants
Returns
mixed Array or Doctrine_Collection, depending on hydration mode. False if no result.

Definition at line 279 of file Query.php.

{
$collection = $this->execute($params, $hydrationMode);
if (is_scalar($collection)) {
return $collection;
}
if (count($collection) === 0) {
return false;
}
if ($collection instanceof Doctrine_Collection) {
return $collection->getFirst();
} else if (is_array($collection)) {
return array_shift($collection);
}
return false;
}
Doctrine_Query_Abstract::fixArrayParameterValues (   $params = array())
inherited

Definition at line 555 of file Abstract.php.

{
$i = 0;
foreach ($params as $param) {
if (is_array($param)) {
$c = count($param);
array_splice($params, $i, 1, $param);
$i += $c;
} else {
$i++;
}
}
$this->_execParams = $params;
}
Doctrine_Query_Abstract::forUpdate (   $flag = true)
inherited

forUpdate Makes the query SELECT FOR UPDATE.

Parameters
bool$flagWhether or not the SELECT is FOR UPDATE (default true).
Returns
Doctrine_Query

Definition at line 1559 of file Abstract.php.

{
$this->_sqlParts['forUpdate'] = (bool) $flag;
return $this;
}
Doctrine_Query::free ( )

Frees the resources used by the query object. It especially breaks a cyclic reference between the query object and it's parsers. This enables PHP's current GC to reclaim the memory. This method can therefore be used to reduce memory usage when creating a lot of query objects during a request.

Returns
Doctrine_Query this object

Definition at line 2224 of file Query.php.

{
$this->reset();
$this->_parsers = array();
$this->_dqlParts = array();
}
Doctrine_Query_Abstract::from (   $from)
inherited

from sets the FROM part of the query $q->from('User u');

Parameters
string$fromQuery FROM part
Returns
Doctrine_Query

Definition at line 1633 of file Abstract.php.

{
return $this->_addDqlQueryPart('from', $from);
}
Doctrine_Query_Abstract::generateNewSqlTableAlias (   $oldAlias)
inherited

generateNewSqlTableAlias generates a new alias from given table alias

Parameters
string$tableAliastable alias from which to generate the new alias from
Returns
string the created table alias

Definition at line 686 of file Abstract.php.

{
if (isset($this->_tableAliasMap[$oldAlias])) {
// generate a new alias
$name = substr($oldAlias, 0, 1);
$i = ((int) substr($oldAlias, 1));
// Fix #1530: It was reaching unexistent seeds index
if ( ! isset($this->_tableAliasSeeds[$name])) {
$this->_tableAliasSeeds[$name] = 1;
}
$newIndex = ($this->_tableAliasSeeds[$name] + (($i == 0) ? 1 : $i));
return $name . $newIndex;
}
return $oldAlias;
}
Doctrine_Query_Abstract::generateSqlTableAlias (   $componentAlias,
  $tableName 
)
inherited

generateSqlTableAlias generates a table alias from given table name and associates it with given component alias

Parameters
string$componentAliasthe component alias to be associated with generated table alias
string$tableNamethe table name from which to generate the table alias
Returns
string the generated table alias

Definition at line 822 of file Abstract.php.

{
preg_match('/([^_|\d])/', $tableName, $matches);
$char = strtolower($matches[0]);
$alias = $char;
if ( ! isset($this->_tableAliasSeeds[$alias])) {
$this->_tableAliasSeeds[$alias] = 1;
}
while (isset($this->_tableAliasMap[$alias])) {
if ( ! isset($this->_tableAliasSeeds[$alias])) {
$this->_tableAliasSeeds[$alias] = 1;
}
$alias = $char . ++$this->_tableAliasSeeds[$alias];
}
$this->_tableAliasMap[$alias] = $componentAlias;
return $alias;
}
Doctrine_Query_Abstract::getCachedForm (   $customComponent = null)
inherited

getCachedForm returns the cached form of this query for given resultSet

Parameters
array$resultSet
Returns
string serialized string representation of this query

Definition at line 1208 of file Abstract.php.

{
$componentInfo = array();
foreach ($this->getQueryComponents() as $alias => $components) {
if ( ! isset($components['parent'])) {
$componentInfo[$alias]['name'] = $components['table']->getComponentName();
} else {
$componentInfo[$alias]['name'] = $components['parent'] . '.' . $components['relation']->getAlias();
}
if (isset($components['agg'])) {
$componentInfo[$alias]['agg'] = $components['agg'];
}
if (isset($components['map'])) {
$componentInfo[$alias]['map'] = $components['map'];
}
}
if ($customComponent instanceof Doctrine_Collection) {
foreach ($customComponent as $record) {
$record->serializeReferences(true);
}
}
return serialize(array($customComponent, $componentInfo, $this->getTableAliasMap()));
}
Doctrine_Query_Abstract::getComponentAlias (   $sqlTableAlias)
inherited

getComponentAlias get component alias associated with given table alias

Parameters
string$sqlTableAliasthe SQL table alias that identifies the component alias
Returns
string component alias

Definition at line 852 of file Abstract.php.

{
$sqlTableAlias = trim($sqlTableAlias, '[]`"');
if ( ! isset($this->_tableAliasMap[$sqlTableAlias])) {
throw new Doctrine_Query_Exception('Unknown table alias ' . $sqlTableAlias);
}
return $this->_tableAliasMap[$sqlTableAlias];
}
Doctrine_Query_Abstract::getConnection ( )
inherited

getConnection

Returns
Doctrine_Connection

Definition at line 2013 of file Abstract.php.

{
return $this->_conn;
}
Doctrine_Query_Abstract::getCountQueryParams (   $params = array())
inherited

getCountQueryParams Retrieves the parameters for count query

Returns
array Parameters array

Definition at line 537 of file Abstract.php.

{
if ( ! is_array($params)) {
$params = array($params);
}
$this->_params['exec'] = $params;
$params = array_merge($this->_params['join'], $this->_params['where'], $this->_params['having'], $this->_params['exec']);
$this->fixArrayParameterValues($params);
return $this->_execParams;
}
Doctrine_Query::getCountSqlQuery ( )

Get count sql query for this Doctrine_Query instance.

This method is used in Doctrine_Query::count() for returning an integer for the number of records which will be returned when executed.

Returns
string $q

Definition at line 2020 of file Query.php.

{
// triggers dql parsing/processing
$this->getSqlQuery(array(), false); // this is ugly
// initialize temporary variables
$where = $this->_sqlParts['where'];
$having = $this->_sqlParts['having'];
$groupby = $this->_sqlParts['groupby'];
$rootAlias = $this->getRootAlias();
$tableAlias = $this->getSqlTableAlias($rootAlias);
// Build the query base
$q = 'SELECT COUNT(*) AS ' . $this->_conn->quoteIdentifier('num_results') . ' FROM ';
// Build the from clause
$from = $this->_buildSqlFromPart(true);
// Build the where clause
$where = ( ! empty($where)) ? ' WHERE ' . implode(' ', $where) : '';
// Build the group by clause
$groupby = ( ! empty($groupby)) ? ' GROUP BY ' . implode(', ', $groupby) : '';
// Build the having clause
$having = ( ! empty($having)) ? ' HAVING ' . implode(' AND ', $having) : '';
// Building the from clause and finishing query
if (count($this->_queryComponents) == 1 && empty($having)) {
$q .= $from . $where . $groupby . $having;
} else {
// Subselect fields will contain only the pk of root entity
$ta = $this->_conn->quoteIdentifier($tableAlias);
$map = $this->getRootDeclaration();
$idColumnNames = $map['table']->getIdentifierColumnNames();
$pkFields = $ta . '.' . implode(', ' . $ta . '.', $this->_conn->quoteMultipleIdentifier($idColumnNames));
// We need to do some magic in select fields if the query contain anything in having clause
$selectFields = $pkFields;
if ( ! empty($having)) {
// For each field defined in select clause
foreach ($this->_sqlParts['select'] as $field) {
// We only include aggregate expressions to count query
// This is needed because HAVING clause will use field aliases
if (strpos($field, '(') !== false) {
$selectFields .= ', ' . $field;
}
}
// Add having fields that got stripped out of select
preg_match_all('/`[a-z0-9_]+`\.`[a-z0-9_]+`/i', $having, $matches, PREG_PATTERN_ORDER);
if (count($matches[0]) > 0) {
$selectFields .= ', ' . implode(', ', array_unique($matches[0]));
}
}
// If we do not have a custom group by, apply the default one
if (empty($groupby)) {
$groupby = ' GROUP BY ' . $pkFields;
}
$q .= '(SELECT ' . $selectFields . ' FROM ' . $from . $where . $groupby . $having . ') '
. $this->_conn->quoteIdentifier('dctrn_count_query');
}
return $q;
}
Doctrine_Query_Abstract::getDql ( )
inherited

getDql returns the DQL query that is represented by this query object.

the query is built from $_dqlParts

Returns
string the DQL query

Definition at line 348 of file Abstract.php.

{
$q = '';
if ($this->_type == self::SELECT) {
$q .= ( ! empty($this->_dqlParts['select'])) ? 'SELECT ' . implode(', ', $this->_dqlParts['select']) : '';
$q .= ( ! empty($this->_dqlParts['from'])) ? ' FROM ' . implode(' ', $this->_dqlParts['from']) : '';
} else if ($this->_type == self::DELETE) {
$q .= 'DELETE';
$q .= ( ! empty($this->_dqlParts['from'])) ? ' FROM ' . implode(' ', $this->_dqlParts['from']) : '';
} else if ($this->_type == self::UPDATE) {
$q .= 'UPDATE ';
$q .= ( ! empty($this->_dqlParts['from'])) ? implode(' ', $this->_dqlParts['from']) : '';
$q .= ( ! empty($this->_dqlParts['set'])) ? ' SET ' . implode(' ', $this->_dqlParts['set']) : '';
}
$q .= ( ! empty($this->_dqlParts['where'])) ? ' WHERE ' . implode(' ', $this->_dqlParts['where']) : '';
$q .= ( ! empty($this->_dqlParts['groupby'])) ? ' GROUP BY ' . implode(', ', $this->_dqlParts['groupby']) : '';
$q .= ( ! empty($this->_dqlParts['having'])) ? ' HAVING ' . implode(' AND ', $this->_dqlParts['having']) : '';
$q .= ( ! empty($this->_dqlParts['orderby'])) ? ' ORDER BY ' . implode(', ', $this->_dqlParts['orderby']) : '';
$q .= ( ! empty($this->_dqlParts['limit'])) ? ' LIMIT ' . implode(' ', $this->_dqlParts['limit']) : '';
$q .= ( ! empty($this->_dqlParts['offset'])) ? ' OFFSET ' . implode(' ', $this->_dqlParts['offset']) : '';
return $q;
}
Doctrine_Query::getDqlPart (   $queryPart)

Retrieves a specific DQL query part.

See Also
Doctrine_Query_Abstract::$_dqlParts var_dump($q->getDqlPart('where')); // array(2) { [0] => string(8) 'name = ?' [1] => string(8) 'date > ?' }
Parameters
string$queryPartthe name of the query part; can be: array from, containing strings; array select, containg string; boolean forUpdate; array set; array join; array where; array groupby; array having; array orderby, containing strings such as 'id ASC'; array limit, containing numerics; array offset, containing numerics;
Returns
array

Definition at line 405 of file Query.php.

{
if ( ! isset($this->_dqlParts[$queryPart])) {
throw new Doctrine_Query_Exception('Unknown query part ' . $queryPart);
}
return $this->_dqlParts[$queryPart];
}
Doctrine_Query::getExpressionOwner (   $expr)

getExpressionOwner returns the component alias for owner of given expression

Parameters
string$exprexpression from which to get to owner from
Returns
string the component alias
Todo:
Description: What does it mean if a component is an 'owner' of an expression? What kind of 'expression' are we talking about here?

Definition at line 570 of file Query.php.

{
if (strtoupper(substr(trim($expr, '( '), 0, 6)) !== 'SELECT') {
preg_match_all("/[a-z_][a-z0-9_]*\.[a-z_][a-z0-9_]*[\.[a-z0-9]+]*/i", $expr, $matches);
$match = current($matches);
if (isset($match[0])) {
$terms = explode('.', $match[0]);
return $terms[0];
}
}
return $this->getRootAlias();
}
Doctrine_Query_Abstract::getFlattenedParams (   $params = array())
inherited

Get flattened array of parameters for query. Used internally and used to pass flat array of params to the database.

Parameters
array$params
Returns
void

Definition at line 502 of file Abstract.php.

{
return array_merge(
(array) $params, (array) $this->_params['exec'],
$this->_params['join'], $this->_params['set'],
$this->_params['where'], $this->_params['having']
);
}
Doctrine_Query_Abstract::getInheritanceCondition (   $componentAlias)
inherited

Returns the inheritance condition for the passed componentAlias If no component alias is specified it defaults to the root component

This function is used to append a SQL condition to models which have inheritance mapping The condition is applied to the FROM component in the WHERE, but the condition is applied to JOINS in the ON condition and not the WHERE

Returns
string $str SQL condition string

Definition at line 618 of file Abstract.php.

{
$map = $this->_queryComponents[$componentAlias]['table']->inheritanceMap;
// No inheritance map so lets just return
if (empty($map)) {
return;
}
$tableAlias = $this->getSqlTableAlias($componentAlias);
if ($this->_type !== Doctrine_Query::SELECT) {
$tableAlias = '';
} else {
$tableAlias .= '.';
}
// Fix for 2015: loop through whole inheritanceMap to add all
// keyFields for inheritance (and not only the first)
$retVal = "";
$count = 0;
foreach ($map as $field => $value) {
if ($count++ > 0) {
$retVal .= ' AND ';
}
$identifier = $this->_conn->quoteIdentifier($tableAlias . $field);
$retVal .= $identifier . ' = ' . $this->_conn->quote($value);
}
return $retVal;
}
Doctrine_Query_Abstract::getInternalParams (   $params = array())
inherited

getInternalParams

Returns
array

Definition at line 516 of file Abstract.php.

{
return array_merge($params, $this->_execParams);
}
Doctrine_Query::getLimitSubquery ( )

getLimitSubquery this is method is used by the record limit algorithm

when fetching one-to-many, many-to-many associated data with LIMIT clause an additional subquery is needed for limiting the number of returned records instead of limiting the number of sql result set rows

Returns
string the limit subquery
Todo:
A little refactor to make the method easier to understand & maybe shorter?

Definition at line 1379 of file Query.php.

{
$map = reset($this->_queryComponents);
$table = $map['table'];
$componentAlias = key($this->_queryComponents);
// get short alias
$alias = $this->getSqlTableAlias($componentAlias);
// what about composite keys?
$primaryKey = $alias . '.' . $table->getColumnName($table->getIdentifier());
$driverName = $this->_conn->getAttribute(Doctrine_Core::ATTR_DRIVER_NAME);
// initialize the base of the subquery
if (($driverName == 'oracle' || $driverName == 'oci') && $this->_isOrderedByJoinedColumn()) {
$subquery = 'SELECT ';
} else {
$subquery = 'SELECT DISTINCT ';
}
$subquery .= $this->_conn->quoteIdentifier($primaryKey);
// pgsql & oracle need the order by fields to be preserved in select clause
if ($driverName == 'pgsql' || $driverName == 'oracle' || $driverName == 'oci' || $driverName == 'mssql' || $driverName == 'odbc') {
foreach ($this->_sqlParts['orderby'] as $part) {
// Remove identifier quoting if it exists
$e = $this->_tokenizer->bracketExplode($part, ' ');
foreach ($e as $f) {
if ($f == 0 || $f % 2 == 0) {
$partOriginal = str_replace(',', '', trim($f));
$callback = create_function('$e', 'return trim($e, \'[]`"\');');
$part = trim(implode('.', array_map($callback, explode('.', $partOriginal))));
if (strpos($part, '.') === false) {
continue;
}
// don't add functions
if (strpos($part, '(') !== false) {
continue;
}
// don't add primarykey column (its already in the select clause)
if ($part !== $primaryKey) {
$subquery .= ', ' . $partOriginal;
}
}
}
}
}
$orderby = $this->_sqlParts['orderby'];
$having = $this->_sqlParts['having'];
if ($driverName == 'mysql' || $driverName == 'pgsql') {
foreach ($this->_expressionMap as $dqlAlias => $expr) {
if (isset($expr[1])) {
$subquery .= ', ' . $expr[0] . ' AS ' . $this->_aggregateAliasMap[$dqlAlias];
}
}
} else {
foreach ($this->_expressionMap as $dqlAlias => $expr) {
if (isset($expr[1])) {
foreach ($having as $k => $v) {
$having[$k] = str_replace($this->_aggregateAliasMap[$dqlAlias], $expr[0], $v);
}
foreach ($orderby as $k => $v) {
$e = explode(' ', $v);
if ($e[0] == $this->_aggregateAliasMap[$dqlAlias]) {
$orderby[$k] = $expr[0];
}
}
}
}
}
// Add having fields that got stripped out of select
preg_match_all('/`[a-z0-9_]+`\.`[a-z0-9_]+`/i', implode(' ', $having), $matches, PREG_PATTERN_ORDER);
if (count($matches[0]) > 0) {
$subquery .= ', ' . implode(', ', array_unique($matches[0]));
}
$subquery .= ' FROM';
foreach ($this->_sqlParts['from'] as $part) {
// preserve LEFT JOINs only if needed
if (substr($part, 0, 9) === 'LEFT JOIN') {
$e = explode(' ', $part);
// Fix for http://www.doctrine-project.org/jira/browse/DC-706
// Fix for http://www.doctrine-project.org/jira/browse/DC-594
if (empty($this->_sqlParts['orderby']) && empty($this->_sqlParts['where']) && empty($this->_sqlParts['having']) && empty($this->_sqlParts['groupby'])) {
continue;
}
}
$subquery .= ' ' . $part;
}
// all conditions must be preserved in subquery
$subquery .= ( ! empty($this->_sqlParts['where']))? ' WHERE ' . implode(' ', $this->_sqlParts['where']) : '';
$subquery .= ( ! empty($this->_sqlParts['groupby']))? ' GROUP BY ' . implode(', ', $this->_sqlParts['groupby']) : '';
$subquery .= ( ! empty($having))? ' HAVING ' . implode(' AND ', $having) : '';
$subquery .= ( ! empty($orderby))? ' ORDER BY ' . implode(', ', $orderby) : '';
if (($driverName == 'oracle' || $driverName == 'oci') && $this->_isOrderedByJoinedColumn()) {
// When using "ORDER BY x.foo" where x.foo is a column of a joined table,
// we may get duplicate primary keys because all columns in ORDER BY must appear
// in the SELECT list when using DISTINCT. Hence we need to filter out the
// primary keys with an additional DISTINCT subquery.
// #1038
$quotedIdentifierColumnName = $this->_conn->quoteIdentifier($table->getColumnName($table->getIdentifier()));
$subquery = 'SELECT doctrine_subquery_alias.' . $quotedIdentifierColumnName
. ' FROM (' . $subquery . ') doctrine_subquery_alias'
. ' GROUP BY doctrine_subquery_alias.' . $quotedIdentifierColumnName
. ' ORDER BY MIN(ROWNUM)';
}
// add driver specific limit clause
$subquery = $this->_conn->modifyLimitSubquery($table, $subquery, $this->_sqlParts['limit'], $this->_sqlParts['offset']);
$parts = $this->_tokenizer->quoteExplode($subquery, ' ', "'", "'");
foreach ($parts as $k => $part) {
if (strpos($part, ' ') !== false) {
continue;
}
$part = str_replace(array('"', "'", '`'), "", $part);
if ($this->hasSqlTableAlias($part)) {
$parts[$k] = $this->_conn->quoteIdentifier($this->generateNewSqlTableAlias($part));
continue;
}
if (strpos($part, '.') === false) {
continue;
}
preg_match_all("/[a-zA-Z0-9_]+\.[a-z0-9_]+/i", $part, $m);
foreach ($m[0] as $match) {
$e = explode('.', $match);
// Rebuild the original part without the newly generate alias and with quoting reapplied
$e2 = array();
foreach ($e as $k2 => $v2) {
$e2[$k2] = $this->_conn->quoteIdentifier($v2);
}
$match = implode('.', $e2);
// Generate new table alias
$e[0] = $this->generateNewSqlTableAlias($e[0]);
// Requote the part with the newly generated alias
foreach ($e as $k2 => $v2) {
$e[$k2] = $this->_conn->quoteIdentifier($v2);
}
$replace = implode('.' , $e);
// Replace the original part with the new part with new sql table alias
$parts[$k] = str_replace($match, $replace, $parts[$k]);
}
}
if ($driverName == 'mysql' || $driverName == 'pgsql') {
foreach ($parts as $k => $part) {
if (strpos($part, "'") !== false) {
continue;
}
if (strpos($part, '__') == false) {
continue;
}
preg_match_all("/[a-zA-Z0-9_]+\_\_[a-z0-9_]+/i", $part, $m);
foreach ($m[0] as $match) {
$e = explode('__', $match);
$e[0] = $this->generateNewSqlTableAlias($e[0]);
$parts[$k] = str_replace($match, implode('__', $e), $parts[$k]);
}
}
}
$subquery = implode(' ', $parts);
return $subquery;
}
Doctrine_Query_Abstract::getParams ( )
inherited

Get raw array of parameters for query and all parts.

Returns
array $params

Definition at line 490 of file Abstract.php.

{
return $this->_params;
}
Doctrine_Query_Abstract::getQueryCacheDriver ( )
inherited

getQueryCacheDriver returns the cache driver used for caching queries

Returns
Doctrine_Cache_Interface|boolean|null cache driver

Definition at line 1999 of file Abstract.php.

{
if ($this->_queryCache instanceof Doctrine_Cache_Interface) {
return $this->_queryCache;
} else {
return $this->_conn->getQueryCacheDriver();
}
}
Doctrine_Query_Abstract::getQueryCacheLifeSpan ( )
inherited

Gets the life span of the query cache the Query object is using.

Returns
integer The life span in seconds.

Definition at line 1973 of file Abstract.php.

{
return $this->_queryCacheTTL;
}
Doctrine_Query_Abstract::getQueryComponent (   $componentAlias)
inherited

getQueryComponent get the declaration for given component alias

Parameters
string$componentAliasthe component alias the retrieve the declaration from
Returns
array the alias declaration

Definition at line 740 of file Abstract.php.

{
if ( ! isset($this->_queryComponents[$componentAlias])) {
throw new Doctrine_Query_Exception('Unknown component alias ' . $componentAlias);
}
return $this->_queryComponents[$componentAlias];
}
Doctrine_Query_Abstract::getQueryComponents ( )
inherited

Gets the components of this query.

Definition at line 1798 of file Abstract.php.

{
return $this->_queryComponents;
}
Doctrine_Query_Abstract::getResultCacheDriver ( )
inherited

getResultCacheDriver returns the cache driver used for caching result sets

Returns
Doctrine_Cache_Interface|boolean|null cache driver

Definition at line 1984 of file Abstract.php.

{
if ($this->_resultCache instanceof Doctrine_Cache_Interface) {
return $this->_resultCache;
} else {
return $this->_conn->getResultCacheDriver();
}
}
Doctrine_Query_Abstract::getResultCacheHash (   $params = array())
inherited

Get the result cache hash/key. Returns key set with useResultCache() or generates a unique key from the query automatically.

Parameters
array$params
Returns
string $hash

Definition at line 897 of file Abstract.php.

{
if ($this->_resultCacheHash) {
return $this->_resultCacheHash;
} else {
return $this->calculateResultCacheHash($params);
}
}
Doctrine_Query_Abstract::getResultCacheLifeSpan ( )
inherited

Gets the life span of the result cache in seconds.

Returns
integer

Definition at line 1947 of file Abstract.php.

{
return $this->_resultCacheTTL;
}
Doctrine_Query_Abstract::getRoot ( )
inherited

getRoot returns the root component for this object

Returns
Doctrine_Table root components table

Definition at line 802 of file Abstract.php.

{
$map = $this->_queryComponents[$this->_rootAlias];
if ( ! isset($map['table'])) {
throw new Doctrine_Query_Exception('Root component not initialized.');
}
return $map['table'];
}
Doctrine_Query_Abstract::getRootAlias ( )
inherited

getRootAlias returns the alias of the root component

Returns
array

Definition at line 775 of file Abstract.php.

{
if ( ! $this->_queryComponents) {
$this->getSqlQuery(array(), false);
}
return $this->_rootAlias;
}
Doctrine_Query_Abstract::getRootDeclaration ( )
inherited

getRootDeclaration returns the root declaration

Returns
array

Definition at line 790 of file Abstract.php.

{
$map = $this->_queryComponents[$this->_rootAlias];
return $map;
}
Doctrine_Query::getSqlAggregateAlias (   $dqlAlias)

getSqlAggregateAlias

Parameters
string$dqlAliasthe dql alias of an aggregate value
Returns
string

Definition at line 329 of file Query.php.

{
if (isset($this->_aggregateAliasMap[$dqlAlias])) {
// mark the expression as used
$this->_expressionMap[$dqlAlias][1] = true;
return $this->_aggregateAliasMap[$dqlAlias];
} else if ( ! empty($this->_pendingAggregates)) {
return $this->getSqlAggregateAlias($dqlAlias);
} else if( ! ($this->_conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EXPR)){
return $dqlAlias;
} else {
throw new Doctrine_Query_Exception('Unknown aggregate alias: ' . $dqlAlias);
}
}
Doctrine_Query_Abstract::getSqlParts ( )
inherited

Return the SQL parts.

Returns
array The parts

Definition at line 1808 of file Abstract.php.

{
return $this->_sqlParts;
}
Doctrine_Query::getSqlQuery (   $params = array(),
  $limitSubquery = true 
)

builds the sql query from the given parameters and applies things such as column aggregation inheritance and limit subqueries if needed

Parameters
array$paramsan array of prepared statement params (needed only in mysql driver when limit subquery algorithm is used)
bool$limitSubqueryWhether or not to try and apply the limit subquery algorithm
Returns
string the built sql query

Definition at line 1119 of file Query.php.

{
// Assign building/execution specific params
$this->_params['exec'] = $params;
// Initialize prepared parameters array
$this->_execParams = $this->getFlattenedParams();
if ($this->_state !== self::STATE_DIRTY) {
// Return compiled SQL
return $this->_sql;
}
return $this->buildSqlQuery($limitSubquery);
}
Doctrine_Query_Abstract::getSqlQuery (   $params = array())
abstractinherited

Gets the SQL query that corresponds to this query object. The returned SQL syntax depends on the connection driver that is used by this query object at the time of this method call.

Parameters
array$params
Doctrine_Query_Abstract::getSqlQueryPart (   $part)
inherited

getSqlQueryPart gets an SQL query part from the SQL query part array

Parameters
string$namethe name of the query part to be set
string$partquery part string
Exceptions
Doctrine_Query_Exceptionif trying to set unknown query part
Returns
mixed this object

Definition at line 381 of file Abstract.php.

{
if ( ! isset($this->_sqlParts[$part])) {
throw new Doctrine_Query_Exception('Unknown SQL query part ' . $part);
}
return $this->_sqlParts[$part];
}
Doctrine_Query_Abstract::getSqlTableAlias (   $componentAlias,
  $tableName = null 
)
inherited

getSqlTableAlias some database such as Oracle need the identifier lengths to be < ~30 chars hence Doctrine creates as short identifier aliases as possible

this method is used for the creation of short table aliases, its also smart enough to check if an alias already exists for given component (componentAlias)

Parameters
string$componentAliasthe alias for the query component to search table alias for
string$tableNamethe table name from which the table alias is being created
Returns
string the generated / fetched short alias

Definition at line 664 of file Abstract.php.

{
$alias = array_search($componentAlias, $this->_tableAliasMap);
if ($alias !== false) {
return $alias;
}
if ($tableName === null) {
throw new Doctrine_Query_Exception("Couldn't get short alias for " . $componentAlias);
}
return $this->generateSqlTableAlias($componentAlias, $tableName);
}
Doctrine_Query_Abstract::getSqlTableAliasSeed (   $sqlTableAlias)
inherited

getSqlTableAliasSeed returns the alias seed for given table alias

Parameters
string$tableAliastable alias that identifies the alias seed
Returns
integer table alias seed

Definition at line 713 of file Abstract.php.

{
if ( ! isset($this->_tableAliasSeeds[$sqlTableAlias])) {
return 0;
}
return $this->_tableAliasSeeds[$sqlTableAlias];
}
Doctrine_Query_Abstract::getTableAliasMap ( )
inherited

getTableAliasMap returns all table aliases

Returns
array table aliases as an array

Definition at line 335 of file Abstract.php.

{
return $this->_tableAliasMap;
}
Doctrine_Query_Abstract::getType ( )
inherited

getType

returns the type of this query object by default the type is Doctrine_Query_Abstract::SELECT but if update() or delete() are being called the type is Doctrine_Query_Abstract::UPDATE and Doctrine_Query_Abstract::DELETE, respectively

See Also
Doctrine_Query_Abstract::SELECT
Doctrine_Query_Abstract::UPDATE
Doctrine_Query_Abstract::DELETE
Returns
integer return the query type

Definition at line 1827 of file Abstract.php.

{
return $this->_type;
}
Doctrine_Query_Abstract::getView ( )
inherited

getView returns the view associated with this query object (if any)

Returns
Doctrine_View the view associated with this query object

Definition at line 593 of file Abstract.php.

{
return $this->_view;
}
Doctrine_Query_Abstract::groupBy (   $groupby)
inherited

groupBy sets the GROUP BY part of the query

Parameters
string$groupbyQuery GROUP BY part
Returns
Doctrine_Query

Definition at line 1681 of file Abstract.php.

{
return $this->_addDqlQueryPart('groupby', $groupby);
}
Doctrine_Query_Abstract::hasAliasDeclaration (   $componentAlias)
inherited

hasAliasDeclaration whether or not this object has a declaration for given component alias

Parameters
string$componentAliasthe component alias the retrieve the declaration from
Returns
boolean

Definition at line 728 of file Abstract.php.

{
return isset($this->_queryComponents[$componentAlias]);
}
Doctrine_Query::hasSqlAggregateAlias (   $dqlAlias)

Check if a dql alias has a sql aggregate alias

Parameters
string$dqlAlias
Returns
boolean

Definition at line 353 of file Query.php.

{
try {
$this->getSqlAggregateAlias($dqlAlias);
return true;
} catch (Exception $e) {
return false;
}
}
Doctrine_Query_Abstract::hasSqlTableAlias (   $sqlTableAlias)
inherited

hasSqlTableAlias whether or not this object has given tableAlias

Parameters
string$tableAliasthe table alias to be checked
Returns
boolean true if this object has given alias, otherwise false

Definition at line 324 of file Abstract.php.

{
return (isset($this->_tableAliasMap[$sqlTableAlias]));
}
Doctrine_Query_Abstract::having (   $having,
  $params = array() 
)
inherited

having sets the HAVING part of the query

Parameters
string$havingQuery HAVING part
mixed$paramsan array of parameters or a simple scalar
Returns
Doctrine_Query

Definition at line 1715 of file Abstract.php.

{
$this->_params['having'] = array();
if (is_array($params)) {
$this->_params['having'] = $params;
} else {
$this->_params['having'][] = $params;
}
return $this->_addDqlQueryPart('having', $having);
}
Doctrine_Query_Abstract::innerJoin (   $join,
  $params = array() 
)
inherited

innerJoin appends an INNER JOIN to the FROM part of the query

Parameters
string$joinQuery INNER JOIN
Returns
Doctrine_Query

Definition at line 1645 of file Abstract.php.

{
if (is_array($params)) {
$this->_params['join'] = array_merge($this->_params['join'], $params);
} else {
$this->_params['join'][] = $params;
}
return $this->_addDqlQueryPart('from', 'INNER JOIN ' . $join, true);
}
Doctrine_Query_Abstract::isLimitSubqueryUsed ( )
inherited

limitSubqueryUsed

Returns
boolean

Definition at line 603 of file Abstract.php.

{
return $this->_isLimitSubqueryUsed;
}
Doctrine_Query::isSubquery (   $bool = null)

isSubquery if $bool parameter is set this method sets the value of Doctrine_Query::$isSubquery. If this value is set to true the query object will not load the primary key fields of the selected components.

If null is given as the first parameter this method retrieves the current value of Doctrine_Query::$isSubquery.

Parameters
boolean$boolwhether or not this query acts as a subquery
Returns
Doctrine_Query|bool

Definition at line 313 of file Query.php.

{
if ($bool === null) {
}
$this->_isSubquery = (bool) $bool;
return $this;
}
Doctrine_Query_Abstract::leftJoin (   $join,
  $params = array() 
)
inherited

leftJoin appends a LEFT JOIN to the FROM part of the query

Parameters
string$joinQuery LEFT JOIN
Returns
Doctrine_Query

Definition at line 1663 of file Abstract.php.

{
if (is_array($params)) {
$this->_params['join'] = array_merge($this->_params['join'], $params);
} else {
$this->_params['join'][] = $params;
}
return $this->_addDqlQueryPart('from', 'LEFT JOIN ' . $join, true);
}
Doctrine_Query_Abstract::limit (   $limit)
inherited

limit sets the Query query limit

Parameters
integer$limitlimit to be used for limiting the query results
Returns
Doctrine_Query

Definition at line 1749 of file Abstract.php.

{
return $this->_addDqlQueryPart('limit', $limit);
}
Doctrine_Query::load (   $path,
  $loadFields = true 
)
Todo:
Describe & refactor... too long and nested.
Parameters
string$pathcomponent alias
boolean$loadFields

Definition at line 1664 of file Query.php.

{
if (isset($this->_queryComponents[$path])) {
return $this->_queryComponents[$path];
}
$e = $this->_tokenizer->quoteExplode($path, ' INDEXBY ');
$mapWith = null;
if (count($e) > 1) {
$mapWith = trim($e[1]);
$path = $e[0];
}
// parse custom join conditions
$e = explode(' ON ', str_ireplace(' on ', ' ON ', $path));
$joinCondition = '';
if (count($e) > 1) {
$joinCondition = substr($path, strlen($e[0]) + 4, strlen($e[1]));
$path = substr($path, 0, strlen($e[0]));
$overrideJoin = true;
} else {
$e = explode(' WITH ', str_ireplace(' with ', ' WITH ', $path));
if (count($e) > 1) {
$joinCondition = substr($path, strlen($e[0]) + 6, strlen($e[1]));
$path = substr($path, 0, strlen($e[0]));
}
$overrideJoin = false;
}
$tmp = explode(' ', $path);
$componentAlias = $originalAlias = (count($tmp) > 1) ? end($tmp) : null;
$e = preg_split("/[.:]/", $tmp[0], -1);
$fullPath = $tmp[0];
$prevPath = '';
$fullLength = strlen($fullPath);
if (isset($this->_queryComponents[$e[0]])) {
$table = $this->_queryComponents[$e[0]]['table'];
$componentAlias = $e[0];
$prevPath = $parent = array_shift($e);
}
foreach ($e as $key => $name) {
// get length of the previous path
$length = strlen($prevPath);
// build the current component path
$prevPath = ($prevPath) ? $prevPath . '.' . $name : $name;
$delimeter = substr($fullPath, $length, 1);
// if an alias is not given use the current path as an alias identifier
if (strlen($prevPath) === $fullLength && isset($originalAlias)) {
$componentAlias = $originalAlias;
} else {
$componentAlias = $prevPath;
}
// if the current alias already exists, skip it
if (isset($this->_queryComponents[$componentAlias])) {
throw new Doctrine_Query_Exception("Duplicate alias '$componentAlias' in query.");
}
if ( ! isset($table)) {
// process the root of the path
$table = $this->loadRoot($name, $componentAlias);
} else {
$join = ($delimeter == ':') ? 'INNER JOIN ' : 'LEFT JOIN ';
$relation = $table->getRelation($name);
$localTable = $table;
$table = $relation->getTable();
$this->_queryComponents[$componentAlias] = array('table' => $table,
'parent' => $parent,
'relation' => $relation,
'map' => null);
if ( ! $relation->isOneToOne()) {
$this->_needsSubquery = true;
}
$localAlias = $this->getSqlTableAlias($parent, $localTable->getTableName());
$foreignAlias = $this->getSqlTableAlias($componentAlias, $relation->getTable()->getTableName());
$foreignSql = $this->_conn->quoteIdentifier($relation->getTable()->getTableName())
. ' '
. $this->_conn->quoteIdentifier($foreignAlias);
$map = $relation->getTable()->inheritanceMap;
if ( ! $loadFields || ! empty($map) || $joinCondition) {
$this->_subqueryAliases[] = $foreignAlias;
}
if ($relation instanceof Doctrine_Relation_Association) {
$asf = $relation->getAssociationTable();
$assocTableName = $asf->getTableName();
if ( ! $loadFields || ! empty($map) || $joinCondition) {
$this->_subqueryAliases[] = $assocTableName;
}
$assocPath = $prevPath . '.' . $asf->getComponentName() . ' ' . $componentAlias;
$this->_queryComponents[$assocPath] = array(
'parent' => $prevPath,
'relation' => $relation,
'table' => $asf,
'ref' => true);
$assocAlias = $this->getSqlTableAlias($assocPath, $asf->getTableName());
$queryPart = $join
. $this->_conn->quoteIdentifier($assocTableName)
. ' '
. $this->_conn->quoteIdentifier($assocAlias);
$queryPart .= ' ON (' . $this->_conn->quoteIdentifier($localAlias
. '.'
. $localTable->getColumnName($localTable->getIdentifier())) // what about composite keys?
. ' = '
. $this->_conn->quoteIdentifier($assocAlias . '.' . $relation->getLocalRefColumnName());
if ($relation->isEqual()) {
// equal nest relation needs additional condition
$queryPart .= ' OR '
. $this->_conn->quoteIdentifier($localAlias
. '.'
. $table->getColumnName($table->getIdentifier()))
. ' = '
. $this->_conn->quoteIdentifier($assocAlias . '.' . $relation->getForeignRefColumnName());
}
$queryPart .= ')';
$this->_sqlParts['from'][] = $queryPart;
$queryPart = $join . $foreignSql;
if ( ! $overrideJoin) {
$queryPart .= $this->buildAssociativeRelationSql($relation, $assocAlias, $foreignAlias, $localAlias);
}
} else {
$queryPart = $this->buildSimpleRelationSql($relation, $foreignAlias, $localAlias, $overrideJoin, $join);
}
$queryPart .= $this->buildInheritanceJoinSql($table->getComponentName(), $componentAlias);
$this->_sqlParts['from'][$componentAlias] = $queryPart;
if ( ! empty($joinCondition)) {
$this->addPendingJoinCondition($componentAlias, $joinCondition);
}
}
if ($loadFields) {
$restoreState = false;
// load fields if necessary
if ($loadFields && empty($this->_dqlParts['select'])) {
$this->_pendingFields[$componentAlias] = array('*');
}
}
$parent = $prevPath;
}
$table = $this->_queryComponents[$componentAlias]['table'];
return $this->buildIndexBy($componentAlias, $mapWith);
}
Doctrine_Query::loadRoot (   $name,
  $componentAlias 
)

loadRoot

Parameters
string$name
string$componentAlias
Returns
Doctrine_Table
Todo:

DESCRIBE ME!

this method is called only in Doctrine_Query class. Shouldn't be private or protected?

Definition at line 1934 of file Query.php.

{
// get the connection for the component
if ( ! $this->_passedConn && $manager->hasConnectionForComponent($name)) {
$this->_conn = $manager->getConnectionForComponent($name);
}
$table = $this->_conn->getTable($name);
$tableName = $table->getTableName();
// get the short alias for this table
$tableAlias = $this->getSqlTableAlias($componentAlias, $tableName);
// quote table name
$queryPart = $this->_conn->quoteIdentifier($tableName);
if ($this->_type === self::SELECT) {
$queryPart .= ' ' . $this->_conn->quoteIdentifier($tableAlias);
}
$this->_tableAliasMap[$tableAlias] = $componentAlias;
$queryPart .= $this->buildInheritanceJoinSql($name, $componentAlias);
$this->_sqlParts['from'][] = $queryPart;
$this->_queryComponents[$componentAlias] = array('table' => $table, 'map' => null);
return $table;
}
Doctrine_Query_Abstract::offset (   $offset)
inherited

offset sets the Query query offset

Parameters
integer$offsetoffset to be used for paginating the query
Returns
Doctrine_Query

Definition at line 1761 of file Abstract.php.

{
return $this->_addDqlQueryPart('offset', $offset);
}
Doctrine_Query_Abstract::orderBy (   $orderby)
inherited

Sets the ORDER BY part of the query. $q->orderBy('u.name'); $query->orderBy('u.birthDate DESC');

Parameters
string$orderbyQuery ORDER BY part
Returns
Doctrine_Query

Definition at line 1737 of file Abstract.php.

{
return $this->_addDqlQueryPart('orderby', $orderby);
}
Doctrine_Query_Abstract::orWhere (   $where,
  $params = array() 
)
inherited

Adds conditions to the WHERE part of the query $q->orWhere('u.role = ?', 'admin');

Parameters
string$whereQuery WHERE part
mixed$paramsAn array of parameters or a simple scalar
Returns
Doctrine_Query

Definition at line 1321 of file Abstract.php.

{
if (is_array($params)) {
$this->_params['where'] = array_merge($this->_params['where'], $params);
} else {
$this->_params['where'][] = $params;
}
if ($this->_hasDqlQueryPart('where')) {
$this->_addDqlQueryPart('where', 'OR', true);
}
return $this->_addDqlQueryPart('where', $where, true);
}
Doctrine_Query_Abstract::orWhereIn (   $expr,
  $params = array(),
  $not = false 
)
inherited

Adds IN condition to the query WHERE part, appending it with an OR operator. $q->orWhereIn('u.id', array(10, 23)) ->orWhereIn('u.id', 44); // will select all record with id equal to 10, 23 or 44

Parameters
string$exprThe operand of the IN
mixed$paramsAn array of parameters or a simple scalar
boolean$notWhether or not to use NOT in front of IN
Returns
Doctrine_Query

Definition at line 1387 of file Abstract.php.

{
// if there's no params, return (else we'll get a WHERE IN (), invalid SQL)
if (isset($params) and (count($params) == 0)) {
return $this;
}
if ($this->_hasDqlQueryPart('where')) {
$this->_addDqlQueryPart('where', 'OR', true);
}
return $this->_addDqlQueryPart('where', $this->_processWhereIn($expr, $params, $not), true);
}
Doctrine_Query_Abstract::orWhereNotIn (   $expr,
  $params = array() 
)
inherited

Adds NOT IN condition to the query WHERE part

Parameters
string$exprThe operand of the NOT IN
mixed$paramsAn array of parameters or a simple scalar
Returns
Doctrine_Query

Definition at line 1465 of file Abstract.php.

{
return $this->orWhereIn($expr, $params, true);
}
Doctrine_Query::parseClause (   $clause)

parseClause parses given DQL clause

this method handles five tasks:

  1. Converts all DQL functions to their native SQL equivalents
  2. Converts all component references to their table alias equivalents
  3. Converts all field names to actual column names
  4. Quotes all identifiers
  5. Parses nested clauses and subqueries recursively
Returns
string SQL string
Todo:
Description: What is a 'dql clause' (and what not)? Refactor: Too long & nesting level

Definition at line 687 of file Query.php.

{
$clause = $this->_conn->dataDict->parseBoolean(trim($clause));
if (is_numeric($clause)) {
return $clause;
}
$terms = $this->_tokenizer->clauseExplode($clause, array(' ', '+', '-', '*', '/', '<', '>', '=', '>=', '<=', '&', '|'));
$str = '';
foreach ($terms as $term) {
$pos = strpos($term[0], '(');
if ($pos !== false && substr($term[0], 0, 1) !== "'") {
$name = substr($term[0], 0, $pos);
$term[0] = $this->parseFunctionExpression($term[0]);
} else {
if (substr($term[0], 0, 1) !== "'" && substr($term[0], -1) !== "'") {
if (strpos($term[0], '.') !== false) {
if ( ! is_numeric($term[0])) {
$e = explode('.', $term[0]);
$field = array_pop($e);
if ($this->getType() === Doctrine_Query::SELECT) {
$componentAlias = implode('.', $e);
if (empty($componentAlias)) {
$componentAlias = $this->getRootAlias();
}
$this->load($componentAlias);
// check the existence of the component alias
if ( ! isset($this->_queryComponents[$componentAlias])) {
throw new Doctrine_Query_Exception('Unknown component alias ' . $componentAlias);
}
$table = $this->_queryComponents[$componentAlias]['table'];
$def = $table->getDefinitionOf($field);
// get the actual field name from alias
$field = $table->getColumnName($field);
// check column existence
if ( ! $def) {
throw new Doctrine_Query_Exception('Unknown column ' . $field);
}
if (isset($def['owner'])) {
$componentAlias = $componentAlias . '.' . $def['owner'];
}
$tableAlias = $this->getSqlTableAlias($componentAlias);
// build sql expression
$term[0] = $this->_conn->quoteIdentifier($tableAlias)
. '.'
. $this->_conn->quoteIdentifier($field);
} else {
// build sql expression
$field = $this->getRoot()->getColumnName($field);
$term[0] = $this->_conn->quoteIdentifier($field);
}
}
} else {
if ( ! empty($term[0]) && ! in_array(strtoupper($term[0]), self::$_keywords) &&
! is_numeric($term[0]) && $term[0] !== '?' && substr($term[0], 0, 1) !== ':') {
$componentAlias = $this->getRootAlias();
$found = false;
if ($componentAlias !== false && $componentAlias !== null) {
$table = $this->_queryComponents[$componentAlias]['table'];
// check column existence
if ($table->hasField($term[0])) {
$found = true;
$def = $table->getDefinitionOf($term[0]);
// get the actual column name from field name
$term[0] = $table->getColumnName($term[0]);
if (isset($def['owner'])) {
$componentAlias = $componentAlias . '.' . $def['owner'];
}
$tableAlias = $this->getSqlTableAlias($componentAlias);
if ($this->getType() === Doctrine_Query::SELECT) {
// build sql expression
$term[0] = $this->_conn->quoteIdentifier($tableAlias)
. '.'
. $this->_conn->quoteIdentifier($term[0]);
} else {
// build sql expression
$term[0] = $this->_conn->quoteIdentifier($term[0]);
}
} else {
$found = false;
}
}
if ( ! $found) {
$term[0] = $this->getSqlAggregateAlias($term[0]);
}
}
}
}
}
$str .= $term[0] . $term[1];
}
return $str;
}
Doctrine_Query::parseDqlQuery (   $query,
  $clear = true 
)

DQL PARSER parses a DQL query first splits the query in parts and then uses individual parsers for each part

Parameters
string$queryDQL query
boolean$clearwhether or not to clear the aliases
Exceptions
Doctrine_Query_Exceptionif some generic parsing error occurs
Returns
Doctrine_Query

Definition at line 1606 of file Query.php.

{
if ($clear) {
$this->clear();
}
$query = trim($query);
$query = str_replace("\r", "\n", str_replace("\r\n", "\n", $query));
$query = str_replace("\n", ' ', $query);
$parts = $this->_tokenizer->tokenizeQuery($query);
foreach ($parts as $partName => $subParts) {
$subParts = trim($subParts);
$partName = strtolower($partName);
switch ($partName) {
case 'create':
$this->_type = self::CREATE;
break;
case 'insert':
$this->_type = self::INSERT;
break;
case 'delete':
$this->_type = self::DELETE;
break;
case 'select':
$this->_type = self::SELECT;
$this->_addDqlQueryPart($partName, $subParts);
break;
case 'update':
$this->_type = self::UPDATE;
$partName = 'from';
case 'from':
$this->_addDqlQueryPart($partName, $subParts);
break;
case 'set':
$this->_addDqlQueryPart($partName, $subParts, true);
break;
case 'group':
case 'order':
$partName .= 'by';
case 'where':
case 'having':
case 'limit':
case 'offset':
$this->_addDqlQueryPart($partName, $subParts);
break;
}
}
return $this;
}
Doctrine_Query_Abstract::parseDqlQuery (   $query)
abstractinherited

parseDqlQuery parses a dql query

Parameters
string$queryquery to be parsed
Returns
Doctrine_Query_Abstract this object
Doctrine_Query::parseSelect (   $dql)

parseSelect parses the query select part and adds selected fields to pendingFields array

Parameters
string$dql
Todo:
Description: What information is extracted (and then stored)?

Definition at line 595 of file Query.php.

{
$refs = $this->_tokenizer->sqlExplode($dql, ',');
$pos = strpos(trim($refs[0]), ' ');
$first = substr($refs[0], 0, $pos);
// check for DISTINCT keyword
if ($first === 'DISTINCT') {
$this->_sqlParts['distinct'] = true;
$refs[0] = substr($refs[0], ++$pos);
}
$parsedComponents = array();
foreach ($refs as $reference) {
$reference = trim($reference);
if (empty($reference)) {
continue;
}
$terms = $this->_tokenizer->sqlExplode($reference, ' ');
$pos = strpos($terms[0], '(');
if (count($terms) > 1 || $pos !== false) {
$expression = array_shift($terms);
$alias = array_pop($terms);
if ( ! $alias) {
$alias = substr($expression, 0, $pos);
}
// Fix for http://www.doctrine-project.org/jira/browse/DC-706
if ($pos !== false && substr($expression, 0, 1) !== "'" && substr($expression, 0, $pos) == '') {
$_queryComponents = $this->_queryComponents;
reset($_queryComponents);
$componentAlias = key($_queryComponents);
} else {
$componentAlias = $this->getExpressionOwner($expression);
}
$expression = $this->parseClause($expression);
$tableAlias = $this->getSqlTableAlias($componentAlias);
$index = count($this->_aggregateAliasMap);
$sqlAlias = $this->_conn->quoteIdentifier($tableAlias . '__' . $index);
$this->_sqlParts['select'][] = $expression . ' AS ' . $sqlAlias;
$this->_aggregateAliasMap[$alias] = $sqlAlias;
$this->_expressionMap[$alias][0] = $expression;
$this->_queryComponents[$componentAlias]['agg'][$index] = $alias;
$this->_neededTables[] = $tableAlias;
} else {
$e = explode('.', $terms[0]);
if (isset($e[1])) {
$componentAlias = $e[0];
$field = $e[1];
} else {
reset($this->_queryComponents);
$componentAlias = key($this->_queryComponents);
$field = $e[0];
}
$this->_pendingFields[$componentAlias][] = $field;
}
}
}
Doctrine_Query::parseSelectField (   $field)

Parses a nested field $q->parseSelectField('u.Phonenumber.value');

Parameters
string$field
Exceptions
Doctrine_Query_Exceptionif unknown component alias has been given
Returns
string SQL fragment
Todo:
Description: Explain what this method does. Is there a relation to parseSelect()? This method is not used from any class or testcase in the Doctrine package.

Definition at line 524 of file Query.php.

{
$terms = explode('.', $field);
if (isset($terms[1])) {
$componentAlias = $terms[0];
$field = $terms[1];
} else {
reset($this->_queryComponents);
$componentAlias = key($this->_queryComponents);
$fields = $terms[0];
}
$tableAlias = $this->getSqlTableAlias($componentAlias);
$table = $this->_queryComponents[$componentAlias]['table'];
// check for wildcards
if ($field === '*') {
$sql = array();
foreach ($table->getColumnNames() as $field) {
$sql[] = $this->parseSelectField($componentAlias . '.' . $field);
}
return implode(', ', $sql);
} else {
$name = $table->getColumnName($field);
$this->_neededTables[] = $tableAlias;
return $this->_conn->quoteIdentifier($tableAlias . '.' . $name)
. ' AS '
. $this->_conn->quoteIdentifier($tableAlias . '__' . $name);
}
}
Doctrine_Query_Abstract::preQuery ( )
inherited

Blank hook methods which can be implemented in Doctrine_Query child classes

Returns
void

Definition at line 1156 of file Abstract.php.

{
}
Doctrine_Query::processPendingAggregates ( )

processPendingAggregates processes pending aggregate values for given component alias

Returns
void
Todo:
Better description. i.e. What is a 'pending aggregate'? What does 'processed' mean?

Definition at line 913 of file Query.php.

{
// iterate trhough all aggregates
foreach ($this->_pendingAggregates as $aggregate) {
list ($expression, $components, $alias) = $aggregate;
$tableAliases = array();
// iterate through the component references within the aggregate function
if ( ! empty ($components)) {
foreach ($components as $component) {
if (is_numeric($component)) {
continue;
}
$e = explode('.', $component);
$field = array_pop($e);
$componentAlias = implode('.', $e);
// check the existence of the component alias
if ( ! isset($this->_queryComponents[$componentAlias])) {
throw new Doctrine_Query_Exception('Unknown component alias ' . $componentAlias);
}
$table = $this->_queryComponents[$componentAlias]['table'];
$field = $table->getColumnName($field);
// check column existence
if ( ! $table->hasColumn($field)) {
throw new Doctrine_Query_Exception('Unknown column ' . $field);
}
$sqlTableAlias = $this->getSqlTableAlias($componentAlias);
$tableAliases[$sqlTableAlias] = true;
// build sql expression
$identifier = $this->_conn->quoteIdentifier($sqlTableAlias . '.' . $field);
$expression = str_replace($component, $identifier, $expression);
}
}
if (count($tableAliases) !== 1) {
$componentAlias = reset($this->_tableAliasMap);
$tableAlias = key($this->_tableAliasMap);
}
$index = count($this->_aggregateAliasMap);
$sqlAlias = $this->_conn->quoteIdentifier($tableAlias . '__' . $index);
$this->_sqlParts['select'][] = $expression . ' AS ' . $sqlAlias;
$this->_aggregateAliasMap[$alias] = $sqlAlias;
$this->_expressionMap[$alias][0] = $expression;
$this->_queryComponents[$componentAlias]['agg'][$index] = $alias;
$this->_neededTables[] = $tableAlias;
}
// reset the state
$this->_pendingAggregates = array();
}
Doctrine_Query::processPendingFields (   $componentAlias)

processPendingFields the fields in SELECT clause cannot be parsed until the components in FROM clause are parsed, hence this method is called everytime a specific component is being parsed. For instance, the wildcard '*' is expanded in the list of columns.

Exceptions
Doctrine_Query_Exceptionif unknown component alias has been given
Parameters
string$componentAliasthe alias of the component
Returns
string SQL code
Todo:
Description: What is a 'pending field' (and are there non-pending fields, too)? What is 'processed'? (Meaning: What information is gathered & stored away)

Definition at line 440 of file Query.php.

{
$tableAlias = $this->getSqlTableAlias($componentAlias);
$table = $this->_queryComponents[$componentAlias]['table'];
if ( ! isset($this->_pendingFields[$componentAlias])) {
if ($this->_hydrator->getHydrationMode() != Doctrine_Core::HYDRATE_NONE) {
if ( ! $this->_isSubquery && $componentAlias == $this->getRootAlias()) {
throw new Doctrine_Query_Exception("The root class of the query (alias $componentAlias) "
. " must have at least one field selected.");
}
}
return;
}
// At this point we know the component is FETCHED (either it's the base class of
// the query (FROM xyz) or its a "fetch join").
// Check that the parent join (if there is one), is a "fetch join", too.
if ( ! $this->isSubquery() && isset($this->_queryComponents[$componentAlias]['parent'])) {
$parentAlias = $this->_queryComponents[$componentAlias]['parent'];
if (is_string($parentAlias) && ! isset($this->_pendingFields[$parentAlias])
&& $this->_hydrator->getHydrationMode() != Doctrine_Core::HYDRATE_NONE
&& $this->_hydrator->getHydrationMode() != Doctrine_Core::HYDRATE_SCALAR
&& $this->_hydrator->getHydrationMode() != Doctrine_Core::HYDRATE_SINGLE_SCALAR) {
throw new Doctrine_Query_Exception("The left side of the join between "
. "the aliases '$parentAlias' and '$componentAlias' must have at least"
. " the primary key field(s) selected.");
}
}
$fields = $this->_pendingFields[$componentAlias];
// check for wildcards
if (in_array('*', $fields)) {
$fields = $table->getFieldNames();
} else {
$driverClassName = $this->_hydrator->getHydratorDriverClassName();
// only auto-add the primary key fields if this query object is not
// a subquery of another query object or we're using a child of the Object Graph
// hydrator
if ( ! $this->_isSubquery && is_subclass_of($driverClassName, 'Doctrine_Hydrator_Graph')) {
$fields = array_unique(array_merge((array) $table->getIdentifier(), $fields));
}
}
$sql = array();
foreach ($fields as $fieldName) {
$columnName = $table->getColumnName($fieldName);
if (($owner = $table->getColumnOwner($columnName)) !== null &&
$owner !== $table->getComponentName()) {
$parent = $this->_conn->getTable($owner);
$columnName = $parent->getColumnName($fieldName);
$parentAlias = $this->getSqlTableAlias($componentAlias . '.' . $parent->getComponentName());
$sql[] = $this->_conn->quoteIdentifier($parentAlias) . '.' . $this->_conn->quoteIdentifier($columnName)
. ' AS '
. $this->_conn->quoteIdentifier($tableAlias . '__' . $columnName);
} else {
$columnName = $table->getColumnName($fieldName);
$sql[] = $this->_conn->quoteIdentifier($tableAlias) . '.' . $this->_conn->quoteIdentifier($columnName)
. ' AS '
. $this->_conn->quoteIdentifier($tableAlias . '__' . $columnName);
}
}
$this->_neededTables[] = $tableAlias;
return implode(', ', $sql);
}
Doctrine_Query::processPendingSubqueries ( )

processPendingSubqueries processes pending subqueries

subqueries can only be processed when the query is fully constructed since some subqueries may be correlated

Returns
void
Todo:
Better description. i.e. What is a 'pending subquery'? What does 'processed' mean? (parsed? sql is constructed? some information is gathered?)

Definition at line 882 of file Query.php.

{
foreach ($this->_pendingSubqueries as $value) {
list($dql, $alias) = $value;
$subquery = $this->createSubquery();
$sql = $subquery->parseDqlQuery($dql, false)->getQuery();
$subquery->free();
reset($this->_queryComponents);
$componentAlias = key($this->_queryComponents);
$tableAlias = $this->getSqlTableAlias($componentAlias);
$sqlAlias = $tableAlias . '__' . count($this->_aggregateAliasMap);
$this->_sqlParts['select'][] = '(' . $sql . ') AS ' . $this->_conn->quoteIdentifier($sqlAlias);
$this->_aggregateAliasMap[$alias] = $sqlAlias;
$this->_queryComponents[$componentAlias]['agg'][] = $alias;
}
$this->_pendingSubqueries = array();
}
string $_sql cached SQL Doctrine_Query::query (   $query,
  $params = array(),
  $hydrationMode = null 
)

Queries the database with DQL (Doctrine Query Language).

This methods parses a Dql query and builds the query parts.

Parameters
string$queryDql query
array$paramsprepared statement parameters
int$hydrationModeDoctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD
See Also
Doctrine_Core::FETCH_* constants
Returns
mixed

Definition at line 2159 of file Query.php.

{
$this->parseDqlQuery($query);
return $this->execute($params, $hydrationMode);
}
Doctrine_Query_Abstract::removeDqlQueryPart (   $name)
inherited

removeDqlQueryPart removes a dql query part from the dql query part array

Parameters
string$namethe name of the query part to be removed
Exceptions
Doctrine_Query_Exceptionif trying to remove unknown query part
Returns
Doctrine_Query this object

Definition at line 470 of file Abstract.php.

{
if ( ! isset($this->_dqlParts[$name])) {
throw new Doctrine_Query_Exception('Unknown query part ' . $name);
}
if ($name == 'limit' || $name == 'offset') {
$this->_dqlParts[$name] = false;
} else {
$this->_dqlParts[$name] = array();
}
return $this;
}
Doctrine_Query_Abstract::removeSqlQueryPart (   $name)
inherited

removeSqlQueryPart removes a query part from the query part array

Parameters
string$namethe name of the query part to be removed
Exceptions
Doctrine_Query_Exceptionif trying to remove unknown query part
Returns
Doctrine_Query this object

Definition at line 447 of file Abstract.php.

{
if ( ! isset($this->_sqlParts[$name])) {
throw new Doctrine_Query_Exception('Unknown query part ' . $name);
}
if ($name == 'limit' || $name == 'offset' || $name == 'forUpdate') {
$this->_sqlParts[$name] = false;
} else {
$this->_sqlParts[$name] = array();
}
return $this;
}
Doctrine_Query::reset ( )

Resets the query to the state just after it has been instantiated.

Definition at line 208 of file Query.php.

{
$this->_subqueryAliases = array();
$this->_aggregateAliasMap = array();
$this->_pendingAggregates = array();
$this->_pendingSubqueries = array();
$this->_pendingFields = array();
$this->_neededTables = array();
$this->_expressionMap = array();
$this->_subqueryAliases = array();
$this->_needsSubquery = false;
$this->_isLimitSubqueryUsed = false;
}
Doctrine_Query_Abstract::select (   $select = null)
inherited

select sets the SELECT part of the query

Parameters
string$selectQuery SELECT part
Returns
Doctrine_Query

Definition at line 1526 of file Abstract.php.

{
$this->_type = self::SELECT;
if ($select) {
return $this->_addDqlQueryPart('select', $select);
} else {
return $this;
}
}
Doctrine_Query_Abstract::set (   $key,
  $value = null,
  $params = null 
)
inherited

set sets the SET part of the query

Parameters
string$updateQuery UPDATE part
Returns
Doctrine_Query

Definition at line 1603 of file Abstract.php.

{
if (is_array($key)) {
foreach ($key as $k => $v) {
$this->set($k, '?', array($v));
}
return $this;
} else {
if ($params !== null) {
if (is_array($params)) {
$this->_params['set'] = array_merge($this->_params['set'], $params);
} else {
$this->_params['set'][] = $params;
}
}
return $this->_addDqlQueryPart('set', $key . ' = ' . $value, true);
}
}
Doctrine_Query_Abstract::setConnection ( Doctrine_Connection  $connection)
inherited

Set the connection this query object should use

Parameters
Doctrine_Connection$connection
Returns
void

Definition at line 296 of file Abstract.php.

{
$this->_passedConn = true;
$this->_conn = $connection;
}
Doctrine_Query_Abstract::setOption (   $name,
  $value 
)
inherited

setOption

Parameters
string$nameoption name
string$valueoption value
Returns
Doctrine_Query this object

Definition at line 309 of file Abstract.php.

{
if ( ! isset($this->_options[$name])) {
throw new Doctrine_Query_Exception('Unknown option ' . $name);
}
$this->_options[$name] = $value;
}
Doctrine_Query_Abstract::setParams ( array  $params = array())
inherited

setParams

Parameters
array$params

Definition at line 526 of file Abstract.php.

{
$this->_params = $params;
}
Doctrine_Query_Abstract::setQueryCacheLifeSpan (   $timeToLive)
inherited

setQueryCacheLifeSpan

Parameters
integer$timeToLivehow long the cache entry is valid
Returns
Doctrine_Query this object

Definition at line 1958 of file Abstract.php.

{
if ($timeToLive !== null) {
$timeToLive = (int) $timeToLive;
}
$this->_queryCacheTTL = $timeToLive;
return $this;
}
Doctrine_Query_Abstract::setResultCacheHash (   $resultCacheHash)
inherited

Set the result cache hash to be used for storing the results in the cache driver

Parameters
string$resultCacheHash
Returns
void

Definition at line 1861 of file Abstract.php.

{
$this->_resultCacheHash = $resultCacheHash;
return $this;
}
Doctrine_Query_Abstract::setResultCacheLifeSpan (   $timeToLive)
inherited

setResultCacheLifeSpan

Parameters
integer$timeToLivehow long the cache entry is valid (in seconds)
Returns
Doctrine_Query this object

Definition at line 1932 of file Abstract.php.

{
if ($timeToLive !== null) {
$timeToLive = (int) $timeToLive;
}
$this->_resultCacheTTL = $timeToLive;
return $this;
}
Doctrine_Query_Abstract::setSqlQueryPart (   $name,
  $part 
)
inherited

setSqlQueryPart sets an SQL query part in the SQL query part array

Parameters
string$namethe name of the query part to be set
string$partquery part string
Exceptions
Doctrine_Query_Exceptionif trying to set unknown query part
Returns
Doctrine_Query this object

Definition at line 398 of file Abstract.php.

{
if ( ! isset($this->_sqlParts[$name])) {
throw new Doctrine_Query_Exception('Unknown query part ' . $name);
}
if ($name !== 'limit' && $name !== 'offset') {
if (is_array($part)) {
$this->_sqlParts[$name] = $part;
} else {
$this->_sqlParts[$name] = array($part);
}
} else {
$this->_sqlParts[$name] = $part;
}
return $this;
}
Doctrine_Query_Abstract::setView ( Doctrine_View  $view)
inherited

setView sets a database view this query object uses this method should only be called internally by doctrine

Parameters
Doctrine_View$viewdatabase view
Returns
void

Definition at line 582 of file Abstract.php.

{
$this->_view = $view;
}
Doctrine_Query_Abstract::update (   $from = null)
inherited

update sets the UPDATE part of the query

Parameters
string$updateQuery UPDATE part
Returns
Doctrine_Query

Definition at line 1587 of file Abstract.php.

{
$this->_type = self::UPDATE;
if ($from != null) {
return $this->_addDqlQueryPart('from', $from);
}
return $this;
}
Doctrine_Query_Abstract::useQueryCache (   $driver = true,
  $timeToLive = null 
)
inherited

useQueryCache

Parameters
Doctrine_Cache_Interface | bool$drivercache driver
integer$timeToLivehow long the cache entry is valid
Returns
Doctrine_Query this object

Definition at line 1888 of file Abstract.php.

{
if ($driver !== null && $driver !== true && $driver !== false && ! ($driver instanceOf Doctrine_Cache_Interface)) {
$msg = 'First argument should be instance of Doctrine_Cache_Interface or null.';
throw new Doctrine_Query_Exception($msg);
}
$this->_queryCache = $driver;
if ($timeToLive !== null) {
$this->setQueryCacheLifeSpan($timeToLive);
}
return $this;
}
Doctrine_Query_Abstract::useResultCache (   $driver = true,
  $timeToLive = null,
  $resultCacheHash = null 
)
inherited

useResultCache

Parameters
Doctrine_Cache_Interface | bool$drivercache driver
integer$timeToLivehow long the cache entry is valid
string$resultCacheHashThe key to use for storing the queries result cache entry
Returns
Doctrine_Query this object

Definition at line 1840 of file Abstract.php.

{
if ($driver !== null && $driver !== true && ! ($driver instanceOf Doctrine_Cache_Interface)) {
$msg = 'First argument should be instance of Doctrine_Cache_Interface or null.';
throw new Doctrine_Query_Exception($msg);
}
$this->_resultCache = $driver;
$this->_resultCacheHash = $resultCacheHash;
if ($timeToLive !== null) {
$this->setResultCacheLifeSpan($timeToLive);
}
return $this;
}
Doctrine_Query_Abstract::where (   $where,
  $params = array() 
)
inherited

where sets the WHERE part of the query

Parameters
string$joinQuery WHERE part
mixed$paramsan array of parameters or a simple scalar
Returns
Doctrine_Query

Definition at line 1694 of file Abstract.php.

{
$this->_params['where'] = array();
if (is_array($params)) {
$this->_params['where'] = $params;
} else {
$this->_params['where'][] = $params;
}
return $this->_addDqlQueryPart('where', $where);
}
Doctrine_Query_Abstract::whereIn (   $expr,
  $params = array(),
  $not = false 
)
inherited

Adds IN condition to the query WHERE part. Alias to

See Also
andWhereIn().
Parameters
string$exprthe operand of the IN
mixed$paramsan array of parameters or a simple scalar
boolean$notwhether or not to use NOT in front of IN
Returns
Doctrine_Query

Definition at line 1344 of file Abstract.php.

{
return $this->andWhereIn($expr, $params, $not);
}
Doctrine_Query_Abstract::whereNotIn (   $expr,
  $params = array() 
)
inherited

Adds NOT IN condition to the query WHERE part. $q->whereNotIn('u.id', array(10, 20)); // will exclude users with id 10 and 20 from the select

Parameters
string$exprthe operand of the NOT IN
mixed$paramsan array of parameters or a simple scalar
Returns
Doctrine_Query this object

Definition at line 1440 of file Abstract.php.

{
return $this->whereIn($expr, $params, true);
}

Field Documentation

Doctrine_Query::$_isSubquery
protected
Parameters
boolean$isSubquerywhether or not this query object is a subquery of another query object

Definition at line 140 of file Query.php.

Doctrine_Query::$_needsSubquery = false
protected
Parameters
boolean$needsSubquery

Definition at line 134 of file Query.php.

const Doctrine_Query_Abstract::CREATE = 4
inherited

constant for CREATE queries

Definition at line 63 of file Abstract.php.

const Doctrine_Query_Abstract::DELETE = 1
inherited

constant for DELETE queries

Definition at line 48 of file Abstract.php.

const Doctrine_Query_Abstract::INSERT = 3
inherited

constant for INSERT queries

Definition at line 58 of file Abstract.php.

const Doctrine_Query_Abstract::SELECT = 0
inherited

QUERY TYPE CONSTANTS constant for SELECT queries

Definition at line 43 of file Abstract.php.

const Doctrine_Query_Abstract::STATE_CLEAN = 1
inherited
Todo:
document the query states (and the transitions between them).

A query object is in CLEAN state when it has NO unparsed/unprocessed DQL parts.

Definition at line 69 of file Abstract.php.

const Doctrine_Query_Abstract::STATE_DIRECT = 3
inherited

A query is in DIRECT state when ... ?

Definition at line 80 of file Abstract.php.

const Doctrine_Query_Abstract::STATE_DIRTY = 2
inherited

A query object is in state DIRTY when it has DQL parts that have not yet been parsed/processed.

Definition at line 75 of file Abstract.php.

const Doctrine_Query_Abstract::STATE_LOCKED = 4
inherited

A query object is on LOCKED state when ... ?

Definition at line 85 of file Abstract.php.

const Doctrine_Query_Abstract::UPDATE = 2
inherited

constant for UPDATE queries

Definition at line 53 of file Abstract.php.


The documentation for this class was generated from the following file: