1
0
mirror of synced 2024-12-14 07:06:04 +03:00
doctrine2/lib/Doctrine/ORM/Query/SqlWalker.php

2229 lines
78 KiB
PHP
Raw Normal View History

<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
2012-05-26 16:37:00 +04:00
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM\Query;
2012-10-12 15:53:20 +04:00
use Doctrine\DBAL\LockMode;
use Doctrine\DBAL\Types\Type;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Query;
use Doctrine\ORM\Query\QueryException;
2013-06-05 07:50:43 +04:00
use Doctrine\ORM\OptimisticLockException;
2012-10-12 15:53:20 +04:00
use Doctrine\ORM\Mapping\ClassMetadataInfo;
/**
2009-06-14 21:34:28 +04:00
* The SqlWalker is a TreeWalker that walks over a DQL AST and constructs
* the corresponding SQL.
*
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Roman Borschel <roman@code-factory.org>
* @author Benjamin Eberlei <kontakt@beberlei.de>
2011-12-06 01:05:42 +04:00
* @author Alexander <iam.asm89@gmail.com>
2012-08-11 19:56:47 +04:00
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
* @since 2.0
* @todo Rename: SQLWalker
*/
2009-06-14 21:34:28 +04:00
class SqlWalker implements TreeWalker
{
2012-01-25 02:34:20 +04:00
/**
* @var string
*/
const HINT_DISTINCT = 'doctrine.distinct';
/**
* @var ResultSetMapping
*/
2012-06-01 01:03:01 +04:00
private $rsm;
2012-06-01 01:03:01 +04:00
/**
* Counter for generating unique column aliases.
2012-06-01 01:03:01 +04:00
*
* @var integer
*/
private $aliasCounter = 0;
/**
* Counter for generating unique table aliases.
2012-06-01 01:03:01 +04:00
*
* @var integer
*/
private $tableAliasCounter = 0;
/**
* Counter for generating unique scalar result.
2012-06-01 01:03:01 +04:00
*
* @var integer
*/
private $scalarResultCounter = 1;
/**
* Counter for generating unique parameter indexes.
2012-06-01 01:03:01 +04:00
*
* @var integer
*/
private $sqlParamIndex = 0;
/**
* Counter for generating indexes.
*
* @var integer
*/
2012-07-22 01:07:56 +04:00
private $newObjectCounter = 0;
/**
* @var ParserResult
*/
2012-06-01 01:03:01 +04:00
private $parserResult;
/**
* @var \Doctrine\ORM\EntityManager
*/
2012-06-01 01:03:01 +04:00
private $em;
/**
* @var \Doctrine\DBAL\Connection
*/
2012-06-01 01:03:01 +04:00
private $conn;
/**
* @var \Doctrine\ORM\AbstractQuery
*/
2012-06-01 01:03:01 +04:00
private $query;
2012-06-01 01:03:01 +04:00
/**
* @var array
*/
private $tableAliasMap = array();
2012-06-01 01:03:01 +04:00
/**
* Map from result variable names to their SQL column alias names.
*
* @var array
*/
private $scalarResultAliasMap = array();
2013-06-05 07:50:43 +04:00
/**
* Map from Table-Alias + Column-Name to OrderBy-Direction.
*
* @var array
*/
private $orderedColumnsMap = array();
/**
* Map from DQL-Alias + Field-Name to SQL Column Alias.
*
* @var array
*/
2012-06-01 01:03:01 +04:00
private $scalarFields = array();
2012-06-01 01:03:01 +04:00
/**
* Map of all components/classes that appear in the DQL query.
*
* @var array
*/
private $queryComponents;
2012-06-01 01:03:01 +04:00
/**
* A list of classes that appear in non-scalar SelectExpressions.
*
* @var array
*/
private $selectedClasses = array();
/**
* The DQL alias of the root class of the currently traversed query.
*
2012-06-01 01:03:01 +04:00
* @var array
*/
2012-06-01 01:03:01 +04:00
private $rootAliases = array();
2009-06-14 21:34:28 +04:00
/**
* Flag that indicates whether to generate SQL table aliases in the SQL.
* These should only be generated for SELECT queries, not for UPDATE/DELETE.
2012-06-01 01:03:01 +04:00
*
* @var boolean
2009-06-14 21:34:28 +04:00
*/
2012-06-01 01:03:01 +04:00
private $useSqlTableAliases = true;
/**
* The database platform abstraction.
*
* @var \Doctrine\DBAL\Platforms\AbstractPlatform
*/
2012-06-01 01:03:01 +04:00
private $platform;
/**
* The quote strategy.
*
* @var \Doctrine\ORM\Mapping\QuoteStrategy
*/
private $quoteStrategy;
/**
* {@inheritDoc}
*/
2009-08-04 13:33:36 +04:00
public function __construct($query, $parserResult, array $queryComponents)
{
2012-06-01 01:03:01 +04:00
$this->query = $query;
$this->parserResult = $parserResult;
$this->queryComponents = $queryComponents;
$this->rsm = $parserResult->getResultSetMapping();
$this->em = $query->getEntityManager();
$this->conn = $this->em->getConnection();
$this->platform = $this->conn->getDatabasePlatform();
2012-06-12 03:14:17 +04:00
$this->quoteStrategy = $this->em->getConfiguration()->getQuoteStrategy();
}
/**
* Gets the Query instance used by the walker.
*
* @return Query.
*/
public function getQuery()
{
2012-06-01 01:03:01 +04:00
return $this->query;
}
/**
* Gets the Connection used by the walker.
*
* @return \Doctrine\DBAL\Connection
*/
public function getConnection()
{
2012-06-01 01:03:01 +04:00
return $this->conn;
}
/**
* Gets the EntityManager used by the walker.
*
* @return \Doctrine\ORM\EntityManager
*/
public function getEntityManager()
{
2012-06-01 01:03:01 +04:00
return $this->em;
}
/**
* Gets the information about a single query component.
*
* @param string $dqlAlias The DQL alias.
*
* @return array
*/
public function getQueryComponent($dqlAlias)
{
2012-06-01 01:03:01 +04:00
return $this->queryComponents[$dqlAlias];
}
/**
* {@inheritdoc}
*/
public function getQueryComponents()
{
return $this->queryComponents;
}
/**
* {@inheritdoc}
*/
public function setQueryComponent($dqlAlias, array $queryComponent)
{
$requiredKeys = array('metadata', 'parent', 'relation', 'map', 'nestingLevel', 'token');
if (array_diff($requiredKeys, array_keys($queryComponent))) {
throw QueryException::invalidQueryComponent($dqlAlias);
}
$this->queryComponents[$dqlAlias] = $queryComponent;
}
/**
* {@inheritdoc}
*/
public function getExecutor($AST)
{
switch (true) {
case ($AST instanceof AST\DeleteStatement):
2012-06-01 01:03:01 +04:00
$primaryClass = $this->em->getClassMetadata($AST->deleteClause->abstractSchemaName);
return ($primaryClass->isInheritanceTypeJoined())
? new Exec\MultiTableDeleteExecutor($AST, $this)
: new Exec\SingleTableDeleteUpdateExecutor($AST, $this);
case ($AST instanceof AST\UpdateStatement):
2012-06-01 01:03:01 +04:00
$primaryClass = $this->em->getClassMetadata($AST->updateClause->abstractSchemaName);
2011-10-30 15:12:18 +04:00
return ($primaryClass->isInheritanceTypeJoined())
? new Exec\MultiTableUpdateExecutor($AST, $this)
: new Exec\SingleTableDeleteUpdateExecutor($AST, $this);
default:
return new Exec\SingleSelectExecutor($AST, $this);
}
}
/**
* Generates a unique, short SQL table alias.
*
* @param string $tableName Table name
* @param string $dqlAlias The DQL alias.
*
* @return string Generated table alias.
*/
2011-02-20 00:50:58 +03:00
public function getSQLTableAlias($tableName, $dqlAlias = '')
{
$tableName .= ($dqlAlias) ? '@[' . $dqlAlias . ']' : '';
2012-06-01 01:03:01 +04:00
if ( ! isset($this->tableAliasMap[$tableName])) {
$this->tableAliasMap[$tableName] = strtolower(substr($tableName, 0, 1)) . $this->tableAliasCounter++ . '_';
}
2012-06-01 01:03:01 +04:00
return $this->tableAliasMap[$tableName];
}
/**
* Forces the SqlWalker to use a specific alias for a table name, rather than
* generating an alias on its own.
*
* @param string $tableName
* @param string $alias
* @param string $dqlAlias
*
* @return string
*/
2011-02-20 00:50:58 +03:00
public function setSQLTableAlias($tableName, $alias, $dqlAlias = '')
{
$tableName .= ($dqlAlias) ? '@[' . $dqlAlias . ']' : '';
2012-06-01 01:03:01 +04:00
$this->tableAliasMap[$tableName] = $alias;
return $alias;
}
/**
* Gets an SQL column alias for a column name.
*
* @param string $columnName
*
* @return string
*/
2011-02-20 00:50:58 +03:00
public function getSQLColumnAlias($columnName)
{
2012-06-12 03:14:17 +04:00
return $this->quoteStrategy->getColumnAlias($columnName, $this->aliasCounter++, $this->platform);
}
/**
* Generates the SQL JOINs that are necessary for Class Table Inheritance
* for the given class.
*
* @param ClassMetadata $class The class for which to generate the joins.
* @param string $dqlAlias The DQL alias of the class.
*
* @return string The SQL.
*/
private function _generateClassTableInheritanceJoins($class, $dqlAlias)
{
$sql = '';
$baseTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
// INNER JOIN parent class tables
foreach ($class->parentClasses as $parentClassName) {
2012-06-01 01:03:01 +04:00
$parentClass = $this->em->getClassMetadata($parentClassName);
$tableAlias = $this->getSQLTableAlias($parentClass->getTableName(), $dqlAlias);
2011-10-30 15:12:18 +04:00
2010-04-15 20:36:17 +04:00
// If this is a joined association we must use left joins to preserve the correct result.
2012-06-01 01:03:01 +04:00
$sql .= isset($this->queryComponents[$dqlAlias]['relation']) ? ' LEFT ' : ' INNER ';
2012-06-12 03:14:17 +04:00
$sql .= 'JOIN ' . $this->quoteStrategy->getTableName($parentClass, $this->platform) . ' ' . $tableAlias . ' ON ';
$sqlParts = array();
2011-10-30 15:12:18 +04:00
2012-06-12 03:14:17 +04:00
foreach ($this->quoteStrategy->getIdentifierColumnNames($class, $this->platform) as $columnName) {
$sqlParts[] = $baseTableAlias . '.' . $columnName . ' = ' . $tableAlias . '.' . $columnName;
}
// Add filters on the root class
2011-12-12 00:14:09 +04:00
if ($filterSql = $this->generateFilterConditionSQL($parentClass, $tableAlias)) {
$sqlParts[] = $filterSql;
}
$sql .= implode(' AND ', $sqlParts);
}
// Ignore subclassing inclusion if partial objects is disallowed
2012-06-01 01:03:01 +04:00
if ($this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD)) {
return $sql;
}
// LEFT JOIN child class tables
foreach ($class->subClasses as $subClassName) {
2012-06-01 01:03:01 +04:00
$subClass = $this->em->getClassMetadata($subClassName);
$tableAlias = $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias);
2011-10-30 15:12:18 +04:00
2012-06-12 03:14:17 +04:00
$sql .= ' LEFT JOIN ' . $this->quoteStrategy->getTableName($subClass, $this->platform) . ' ' . $tableAlias . ' ON ';
$sqlParts = array();
2012-06-12 03:14:17 +04:00
foreach ($this->quoteStrategy->getIdentifierColumnNames($subClass, $this->platform) as $columnName) {
$sqlParts[] = $baseTableAlias . '.' . $columnName . ' = ' . $tableAlias . '.' . $columnName;
}
$sql .= implode(' AND ', $sqlParts);
}
return $sql;
}
/**
* @return string
*/
private function _generateOrderedCollectionOrderByItems()
{
2013-06-05 07:50:43 +04:00
$orderedColumns = array();
2012-06-01 01:03:01 +04:00
foreach ($this->selectedClasses as $selectedClass) {
2013-06-05 07:50:43 +04:00
$dqlAlias = $selectedClass['dqlAlias'];
$qComp = $this->queryComponents[$dqlAlias];
$persister = $this->em->getUnitOfWork()->getEntityPersister($qComp['metadata']->name);
2011-10-30 15:12:18 +04:00
2013-06-05 07:50:43 +04:00
if ( ! isset($qComp['relation']['orderBy'])) {
continue;
}
2012-03-24 14:16:32 +04:00
foreach ($qComp['relation']['orderBy'] as $fieldName => $orientation) {
2012-06-12 03:14:17 +04:00
$columnName = $this->quoteStrategy->getColumnName($fieldName, $qComp['metadata'], $this->platform);
$tableName = ($qComp['metadata']->isInheritanceTypeJoined())
2013-06-05 07:50:43 +04:00
? $persister->getOwningTable($fieldName)
: $qComp['metadata']->getTableName();
2013-06-05 07:50:43 +04:00
$orderedColumn = $this->getSQLTableAlias($tableName, $dqlAlias) . '.' . $columnName;
// OrderByClause should replace an ordered relation. see - DDC-2475
if (isset($this->orderedColumnsMap[$orderedColumn])) {
continue;
}
$this->orderedColumnsMap[$orderedColumn] = $orientation;
$orderedColumns[] = $orderedColumn . ' ' . $orientation;
}
}
2011-10-30 15:12:18 +04:00
2013-06-05 07:50:43 +04:00
return implode(', ', $orderedColumns);
}
/**
* Generates a discriminator column SQL condition for the class with the given DQL alias.
*
* @param array $dqlAliases List of root DQL aliases to inspect for discriminator restrictions.
*
* @return string
*/
private function _generateDiscriminatorColumnConditionSQL(array $dqlAliases)
{
$sqlParts = array();
foreach ($dqlAliases as $dqlAlias) {
2012-06-01 01:03:01 +04:00
$class = $this->queryComponents[$dqlAlias]['metadata'];
if ( ! $class->isInheritanceTypeSingleTable()) continue;
2012-06-01 01:03:01 +04:00
$conn = $this->em->getConnection();
$values = array();
2013-04-06 18:11:52 +04:00
if ($class->discriminatorValue !== null) { // discriminators can be 0
$values[] = $conn->quote($class->discriminatorValue);
}
foreach ($class->subClasses as $subclassName) {
2012-06-01 01:03:01 +04:00
$values[] = $conn->quote($this->em->getClassMetadata($subclassName)->discriminatorValue);
}
2012-06-01 01:03:01 +04:00
$sqlParts[] = (($this->useSqlTableAliases) ? $this->getSQLTableAlias($class->getTableName(), $dqlAlias) . '.' : '')
. $class->discriminatorColumn['name'] . ' IN (' . implode(', ', $values) . ')';
}
$sql = implode(' AND ', $sqlParts);
return (count($sqlParts) > 1) ? '(' . $sql . ')' : $sql;
}
2011-12-06 00:14:31 +04:00
/**
* Generates the filter SQL for a given entity and table alias.
*
* @param ClassMetadata $targetEntity Metadata of the target entity.
* @param string $targetTableAlias The table alias of the joined/selected table.
2011-12-06 00:14:31 +04:00
*
* @return string The SQL query part to add to a query.
*/
2011-08-16 14:03:47 +04:00
private function generateFilterConditionSQL(ClassMetadata $targetEntity, $targetTableAlias)
{
2012-06-01 01:03:01 +04:00
if (!$this->em->hasFilters()) {
return '';
}
2011-08-16 14:03:47 +04:00
switch($targetEntity->inheritanceType) {
case ClassMetadata::INHERITANCE_TYPE_NONE:
break;
case ClassMetadata::INHERITANCE_TYPE_JOINED:
// The classes in the inheritance will be added to the query one by one,
// but only the root node is getting filtered
if ($targetEntity->name !== $targetEntity->rootEntityName) {
return '';
}
break;
case ClassMetadata::INHERITANCE_TYPE_SINGLE_TABLE:
// With STI the table will only be queried once, make sure that the filters
// are added to the root entity
2012-06-01 01:03:01 +04:00
$targetEntity = $this->em->getClassMetadata($targetEntity->rootEntityName);
break;
default:
//@todo: throw exception?
return '';
break;
}
$filterClauses = array();
2012-06-01 01:03:01 +04:00
foreach ($this->em->getFilters()->getEnabledFilters() as $filter) {
if ('' !== $filterExpr = $filter->addFilterConstraint($targetEntity, $targetTableAlias)) {
$filterClauses[] = '(' . $filterExpr . ')';
2011-08-16 14:03:47 +04:00
}
}
2011-12-06 01:05:42 +04:00
return implode(' AND ', $filterClauses);
2011-08-16 14:03:47 +04:00
}
/**
* {@inheritdoc}
*/
public function walkSelectStatement(AST\SelectStatement $AST)
{
2013-06-05 07:50:43 +04:00
$limit = $this->query->getMaxResults();
$offset = $this->query->getFirstResult();
$lockMode = $this->query->getHint(Query::HINT_LOCK_MODE);
$sql = $this->walkSelectClause($AST->selectClause)
. $this->walkFromClause($AST->fromClause)
. $this->walkWhereClause($AST->whereClause);
if ($AST->groupByClause) {
$sql .= $this->walkGroupByClause($AST->groupByClause);
}
if ($AST->havingClause) {
$sql .= $this->walkHavingClause($AST->havingClause);
}
if ($AST->orderByClause) {
$sql .= $this->walkOrderByClause($AST->orderByClause);
}
if ( ! $AST->orderByClause && ($orderBySql = $this->_generateOrderedCollectionOrderByItems())) {
$sql .= ' ORDER BY ' . $orderBySql;
}
2013-06-05 07:50:43 +04:00
if ($limit !== null || $offset !== null) {
$sql = $this->platform->modifyLimitQuery($sql, $limit, $offset);
}
if ($lockMode === false || $lockMode === LockMode::NONE) {
return $sql;
}
2013-06-05 07:50:43 +04:00
if ($lockMode === LockMode::PESSIMISTIC_READ) {
return $sql . ' ' . $this->platform->getReadLockSQL();
}
2013-06-05 07:50:43 +04:00
if ($lockMode === LockMode::PESSIMISTIC_WRITE) {
return $sql . ' ' . $this->platform->getWriteLockSQL();
}
2013-06-05 07:50:43 +04:00
if ($lockMode !== LockMode::OPTIMISTIC) {
throw QueryException::invalidLockMode();
}
2013-06-05 07:50:43 +04:00
foreach ($this->selectedClasses as $selectedClass) {
if ( ! $selectedClass['class']->isVersioned) {
throw OptimisticLockException::lockFailed($selectedClass['class']->name);
}
}
return $sql;
}
/**
* {@inheritdoc}
*/
public function walkUpdateStatement(AST\UpdateStatement $AST)
{
2012-06-01 01:03:01 +04:00
$this->useSqlTableAliases = false;
2011-10-30 15:12:18 +04:00
return $this->walkUpdateClause($AST->updateClause)
. $this->walkWhereClause($AST->whereClause);
}
/**
* {@inheritdoc}
*/
public function walkDeleteStatement(AST\DeleteStatement $AST)
{
2012-06-01 01:03:01 +04:00
$this->useSqlTableAliases = false;
2011-10-30 15:12:18 +04:00
return $this->walkDeleteClause($AST->deleteClause)
. $this->walkWhereClause($AST->whereClause);
}
/**
* Walks down an IdentificationVariable AST node, thereby generating the appropriate SQL.
* This one differs of ->walkIdentificationVariable() because it generates the entity identifiers.
*
* @param string $identVariable
*
* @return string
*/
public function walkEntityIdentificationVariable($identVariable)
{
2012-06-01 01:03:01 +04:00
$class = $this->queryComponents[$identVariable]['metadata'];
$tableAlias = $this->getSQLTableAlias($class->getTableName(), $identVariable);
$sqlParts = array();
2012-06-12 03:14:17 +04:00
foreach ($this->quoteStrategy->getIdentifierColumnNames($class, $this->platform) as $columnName) {
$sqlParts[] = $tableAlias . '.' . $columnName;
}
return implode(', ', $sqlParts);
}
/**
* Walks down an IdentificationVariable (no AST node associated), thereby generating the SQL.
*
* @param string $identificationVariable
* @param string $fieldName
*
* @return string The SQL.
*/
public function walkIdentificationVariable($identificationVariable, $fieldName = null)
{
2012-06-01 01:03:01 +04:00
$class = $this->queryComponents[$identificationVariable]['metadata'];
if (
$fieldName !== null && $class->isInheritanceTypeJoined() &&
isset($class->fieldMappings[$fieldName]['inherited'])
) {
2012-06-01 01:03:01 +04:00
$class = $this->em->getClassMetadata($class->fieldMappings[$fieldName]['inherited']);
}
return $this->getSQLTableAlias($class->getTableName(), $identificationVariable);
}
/**
* {@inheritdoc}
*/
public function walkPathExpression($pathExpr)
{
$sql = '';
switch ($pathExpr->type) {
case AST\PathExpression::TYPE_STATE_FIELD:
$fieldName = $pathExpr->field;
$dqlAlias = $pathExpr->identificationVariable;
2012-06-01 01:03:01 +04:00
$class = $this->queryComponents[$dqlAlias]['metadata'];
2012-06-01 01:03:01 +04:00
if ($this->useSqlTableAliases) {
$sql .= $this->walkIdentificationVariable($dqlAlias, $fieldName) . '.';
}
2012-06-12 03:14:17 +04:00
$sql .= $this->quoteStrategy->getColumnName($fieldName, $class, $this->platform);
break;
case AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION:
// 1- the owning side:
// Just use the foreign key, i.e. u.group_id
$fieldName = $pathExpr->field;
$dqlAlias = $pathExpr->identificationVariable;
2012-06-01 01:03:01 +04:00
$class = $this->queryComponents[$dqlAlias]['metadata'];
if (isset($class->associationMappings[$fieldName]['inherited'])) {
2012-06-01 01:03:01 +04:00
$class = $this->em->getClassMetadata($class->associationMappings[$fieldName]['inherited']);
}
$assoc = $class->associationMappings[$fieldName];
if ( ! $assoc['isOwningSide']) {
throw QueryException::associationPathInverseSideNotSupported();
}
2011-10-30 15:12:18 +04:00
// COMPOSITE KEYS NOT (YET?) SUPPORTED
if (count($assoc['sourceToTargetKeyColumns']) > 1) {
throw QueryException::associationPathCompositeKeyNotSupported();
}
2012-06-01 01:03:01 +04:00
if ($this->useSqlTableAliases) {
$sql .= $this->getSQLTableAlias($class->getTableName(), $dqlAlias) . '.';
}
$sql .= reset($assoc['targetToSourceKeyColumns']);
break;
2011-10-30 15:12:18 +04:00
default:
throw QueryException::invalidPathExpression($pathExpr);
}
return $sql;
}
/**
* {@inheritdoc}
*/
public function walkSelectClause($selectClause)
{
$sql = 'SELECT ' . (($selectClause->isDistinct) ? 'DISTINCT ' : '');
$sqlSelectExpressions = array_filter(array_map(array($this, 'walkSelectExpression'), $selectClause->selectExpressions));
2010-02-20 21:27:05 +03:00
2012-06-01 01:03:01 +04:00
if ($this->query->getHint(Query::HINT_INTERNAL_ITERATION) == true && $selectClause->isDistinct) {
$this->query->setHint(self::HINT_DISTINCT, true);
}
2012-06-01 01:03:01 +04:00
$addMetaColumns = ! $this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD) &&
$this->query->getHydrationMode() == Query::HYDRATE_OBJECT
||
2012-06-01 01:03:01 +04:00
$this->query->getHydrationMode() != Query::HYDRATE_OBJECT &&
$this->query->getHint(Query::HINT_INCLUDE_META_COLUMNS);
2012-06-01 01:03:01 +04:00
foreach ($this->selectedClasses as $selectedClass) {
$class = $selectedClass['class'];
$dqlAlias = $selectedClass['dqlAlias'];
$resultAlias = $selectedClass['resultAlias'];
// Register as entity or joined entity result
2012-06-01 01:03:01 +04:00
if ($this->queryComponents[$dqlAlias]['relation'] === null) {
$this->rsm->addEntityResult($class->name, $dqlAlias, $resultAlias);
} else {
2012-06-01 01:03:01 +04:00
$this->rsm->addJoinedEntityResult(
$class->name,
$dqlAlias,
2012-06-01 01:03:01 +04:00
$this->queryComponents[$dqlAlias]['parent'],
$this->queryComponents[$dqlAlias]['relation']['fieldName']
);
}
if ($class->isInheritanceTypeSingleTable() || $class->isInheritanceTypeJoined()) {
// Add discriminator columns to SQL
2012-06-01 01:03:01 +04:00
$rootClass = $this->em->getClassMetadata($class->rootEntityName);
$tblAlias = $this->getSQLTableAlias($rootClass->getTableName(), $dqlAlias);
$discrColumn = $rootClass->discriminatorColumn;
2011-02-20 00:50:58 +03:00
$columnAlias = $this->getSQLColumnAlias($discrColumn['name']);
2011-10-30 15:12:18 +04:00
$sqlSelectExpressions[] = $tblAlias . '.' . $discrColumn['name'] . ' AS ' . $columnAlias;
2012-06-01 01:03:01 +04:00
$this->rsm->setDiscriminatorColumn($dqlAlias, $columnAlias);
$this->rsm->addMetaResult($dqlAlias, $columnAlias, $discrColumn['fieldName']);
}
// Add foreign key columns to SQL, if necessary
if ( ! $addMetaColumns && ! $class->containsForeignIdentifier) {
continue;
}
// Add foreign key columns of class and also parent classes
foreach ($class->associationMappings as $assoc) {
if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) {
continue;
} else if ( !$addMetaColumns && !isset($assoc['id'])) {
continue;
}
2012-06-01 01:03:01 +04:00
$owningClass = (isset($assoc['inherited'])) ? $this->em->getClassMetadata($assoc['inherited']) : $class;
$sqlTableAlias = $this->getSQLTableAlias($owningClass->getTableName(), $dqlAlias);
2011-10-30 15:12:18 +04:00
foreach ($assoc['targetToSourceKeyColumns'] as $srcColumn) {
$columnAlias = $this->getSQLColumnAlias($srcColumn);
2011-10-30 15:12:18 +04:00
$sqlSelectExpressions[] = $sqlTableAlias . '.' . $srcColumn . ' AS ' . $columnAlias;
2011-10-30 15:12:18 +04:00
2012-06-01 01:03:01 +04:00
$this->rsm->addMetaResult($dqlAlias, $columnAlias, $srcColumn, (isset($assoc['id']) && $assoc['id'] === true));
}
}
// Add foreign key columns to SQL, if necessary
if ( ! $addMetaColumns) {
continue;
}
// Add foreign key columns of subclasses
foreach ($class->subClasses as $subClassName) {
2012-06-01 01:03:01 +04:00
$subClass = $this->em->getClassMetadata($subClassName);
$sqlTableAlias = $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias);
foreach ($subClass->associationMappings as $assoc) {
// Skip if association is inherited
if (isset($assoc['inherited'])) continue;
if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) continue;
foreach ($assoc['targetToSourceKeyColumns'] as $srcColumn) {
$columnAlias = $this->getSQLColumnAlias($srcColumn);
$sqlSelectExpressions[] = $sqlTableAlias . '.' . $srcColumn . ' AS ' . $columnAlias;
2012-06-01 01:03:01 +04:00
$this->rsm->addMetaResult($dqlAlias, $columnAlias, $srcColumn);
}
}
}
}
2011-10-30 15:12:18 +04:00
$sql .= implode(', ', $sqlSelectExpressions);
return $sql;
}
/**
* {@inheritdoc}
*/
public function walkFromClause($fromClause)
{
$identificationVarDecls = $fromClause->identificationVariableDeclarations;
$sqlParts = array();
foreach ($identificationVarDecls as $identificationVariableDecl) {
$sql = $this->platform->appendLockHint(
$this->walkRangeVariableDeclaration($identificationVariableDecl->rangeVariableDeclaration),
$this->query->getHint(Query::HINT_LOCK_MODE)
);
foreach ($identificationVariableDecl->joins as $join) {
$sql .= $this->walkJoin($join);
}
if ($identificationVariableDecl->indexBy) {
$alias = $identificationVariableDecl->indexBy->simpleStateFieldPathExpression->identificationVariable;
$field = $identificationVariableDecl->indexBy->simpleStateFieldPathExpression->field;
2012-06-01 01:03:01 +04:00
if (isset($this->scalarFields[$alias][$field])) {
$this->rsm->addIndexByScalar($this->scalarFields[$alias][$field]);
} else {
2012-06-01 01:03:01 +04:00
$this->rsm->addIndexBy(
$identificationVariableDecl->indexBy->simpleStateFieldPathExpression->identificationVariable,
$identificationVariableDecl->indexBy->simpleStateFieldPathExpression->field
);
}
}
$sqlParts[] = $sql;
}
return ' FROM ' . implode(', ', $sqlParts);
}
/**
* Walks down a RangeVariableDeclaration AST node, thereby generating the appropriate SQL.
*
* @param AST\RangeVariableDeclaration $rangeVariableDeclaration
*
* @return string
*/
public function walkRangeVariableDeclaration($rangeVariableDeclaration)
{
2012-06-01 01:03:01 +04:00
$class = $this->em->getClassMetadata($rangeVariableDeclaration->abstractSchemaName);
$dqlAlias = $rangeVariableDeclaration->aliasIdentificationVariable;
2012-06-01 01:03:01 +04:00
$this->rootAliases[] = $dqlAlias;
2012-06-01 01:03:01 +04:00
$sql = $class->getQuotedTableName($this->platform) . ' '
. $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
if ($class->isInheritanceTypeJoined()) {
$sql .= $this->_generateClassTableInheritanceJoins($class, $dqlAlias);
}
return $sql;
}
/**
* Walks down a JoinAssociationDeclaration AST node, thereby generating the appropriate SQL.
*
* @param AST\JoinAssociationDeclaration $joinAssociationDeclaration
* @param int $joinType
*
* @return string
*
* @throws QueryException
*/
public function walkJoinAssociationDeclaration($joinAssociationDeclaration, $joinType = AST\Join::JOIN_TYPE_INNER)
{
$sql = '';
$associationPathExpression = $joinAssociationDeclaration->joinAssociationPathExpression;
$joinedDqlAlias = $joinAssociationDeclaration->aliasIdentificationVariable;
$indexBy = $joinAssociationDeclaration->indexBy;
2012-06-01 01:03:01 +04:00
$relation = $this->queryComponents[$joinedDqlAlias]['relation'];
$targetClass = $this->em->getClassMetadata($relation['targetEntity']);
$sourceClass = $this->em->getClassMetadata($relation['sourceEntity']);
$targetTableName = $targetClass->getQuotedTableName($this->platform);
$targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName(), $joinedDqlAlias);
$sourceTableAlias = $this->getSQLTableAlias($sourceClass->getTableName(), $associationPathExpression->identificationVariable);
// Ensure we got the owning side, since it has all mapping info
$assoc = ( ! $relation['isOwningSide']) ? $targetClass->associationMappings[$relation['mappedBy']] : $relation;
2012-06-01 01:03:01 +04:00
if ($this->query->getHint(Query::HINT_INTERNAL_ITERATION) == true && (!$this->query->getHint(self::HINT_DISTINCT) || isset($this->selectedClasses[$joinedDqlAlias]))) {
if ($relation['type'] == ClassMetadata::ONE_TO_MANY || $relation['type'] == ClassMetadata::MANY_TO_MANY) {
throw QueryException::iterateWithFetchJoinNotAllowed($assoc);
}
}
// This condition is not checking ClassMetadata::MANY_TO_ONE, because by definition it cannot
// be the owning side and previously we ensured that $assoc is always the owning side of the associations.
// The owning side is necessary at this point because only it contains the JoinColumn information.
switch (true) {
case ($assoc['type'] & ClassMetadata::TO_ONE):
$conditions = array();
2012-06-12 02:10:38 +04:00
foreach ($assoc['joinColumns'] as $joinColumn) {
$quotedSourceColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform);
$quotedTargetColumn = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $targetClass, $this->platform);
2012-06-12 02:10:38 +04:00
if ($relation['isOwningSide']) {
$conditions[] = $sourceTableAlias . '.' . $quotedSourceColumn . ' = ' . $targetTableAlias . '.' . $quotedTargetColumn;
continue;
}
2012-06-12 02:10:38 +04:00
$conditions[] = $sourceTableAlias . '.' . $quotedTargetColumn . ' = ' . $targetTableAlias . '.' . $quotedSourceColumn;
}
// Apply remaining inheritance restrictions
$discrSql = $this->_generateDiscriminatorColumnConditionSQL(array($joinedDqlAlias));
if ($discrSql) {
$conditions[] = $discrSql;
}
// Apply the filters
$filterExpr = $this->generateFilterConditionSQL($targetClass, $targetTableAlias);
if ($filterExpr) {
$conditions[] = $filterExpr;
}
$sql .= $targetTableName . ' ' . $targetTableAlias . ' ON ' . implode(' AND ', $conditions);
break;
case ($assoc['type'] == ClassMetadata::MANY_TO_MANY):
// Join relation table
$joinTable = $assoc['joinTable'];
$joinTableAlias = $this->getSQLTableAlias($joinTable['name'], $joinedDqlAlias);
2012-06-01 01:03:01 +04:00
$joinTableName = $sourceClass->getQuotedJoinTableName($assoc, $this->platform);
$conditions = array();
$relationColumns = ($relation['isOwningSide'])
2012-06-12 02:10:38 +04:00
? $assoc['joinTable']['joinColumns']
: $assoc['joinTable']['inverseJoinColumns'];
2012-06-12 02:10:38 +04:00
foreach ($relationColumns as $joinColumn) {
$quotedSourceColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform);
$quotedTargetColumn = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $targetClass, $this->platform);
2012-06-12 02:10:38 +04:00
$conditions[] = $sourceTableAlias . '.' . $quotedTargetColumn . ' = ' . $joinTableAlias . '.' . $quotedSourceColumn;
}
$sql .= $joinTableName . ' ' . $joinTableAlias . ' ON ' . implode(' AND ', $conditions);
// Join target table
$sql .= ($joinType == AST\Join::JOIN_TYPE_LEFT || $joinType == AST\Join::JOIN_TYPE_LEFTOUTER) ? ' LEFT JOIN ' : ' INNER JOIN ';
$conditions = array();
$relationColumns = ($relation['isOwningSide'])
2012-06-12 02:10:38 +04:00
? $assoc['joinTable']['inverseJoinColumns']
: $assoc['joinTable']['joinColumns'];
2012-06-12 02:10:38 +04:00
foreach ($relationColumns as $joinColumn) {
$quotedSourceColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform);
$quotedTargetColumn = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $targetClass, $this->platform);
2012-06-12 02:10:38 +04:00
$conditions[] = $targetTableAlias . '.' . $quotedTargetColumn . ' = ' . $joinTableAlias . '.' . $quotedSourceColumn;
}
// Apply remaining inheritance restrictions
$discrSql = $this->_generateDiscriminatorColumnConditionSQL(array($joinedDqlAlias));
if ($discrSql) {
$conditions[] = $discrSql;
}
// Apply the filters
$filterExpr = $this->generateFilterConditionSQL($targetClass, $targetTableAlias);
if ($filterExpr) {
$conditions[] = $filterExpr;
}
$sql .= $targetTableName . ' ' . $targetTableAlias . ' ON ' . implode(' AND ', $conditions);
break;
}
// FIXME: these should either be nested or all forced to be left joins (DDC-XXX)
if ($targetClass->isInheritanceTypeJoined()) {
$sql .= $this->_generateClassTableInheritanceJoins($targetClass, $joinedDqlAlias);
}
// Apply the indexes
if ($indexBy) {
// For Many-To-One or One-To-One associations this obviously makes no sense, but is ignored silently.
2012-06-01 01:03:01 +04:00
$this->rsm->addIndexBy(
$indexBy->simpleStateFieldPathExpression->identificationVariable,
$indexBy->simpleStateFieldPathExpression->field
);
} else if (isset($relation['indexBy'])) {
2012-06-01 01:03:01 +04:00
$this->rsm->addIndexBy($joinedDqlAlias, $relation['indexBy']);
}
return $sql;
}
/**
* {@inheritdoc}
*/
public function walkFunction($function)
{
return $function->getSql($this);
}
/**
* {@inheritdoc}
*/
public function walkOrderByClause($orderByClause)
{
$orderByItems = array_map(array($this, 'walkOrderByItem'), $orderByClause->orderByItems);
if (($collectionOrderByItems = $this->_generateOrderedCollectionOrderByItems()) !== '') {
$orderByItems = array_merge($orderByItems, (array) $collectionOrderByItems);
}
return ' ORDER BY ' . implode(', ', $orderByItems);
}
/**
* {@inheritdoc}
*/
public function walkOrderByItem($orderByItem)
{
2013-06-05 07:50:43 +04:00
$type = strtoupper($orderByItem->type);
$expr = $orderByItem->expression;
2012-02-16 03:16:58 +04:00
$sql = ($expr instanceof AST\Node)
? $expr->dispatch($this)
2012-06-01 01:03:01 +04:00
: $this->walkResultVariable($this->queryComponents[$expr]['token']['value']);
2013-06-05 07:50:43 +04:00
$this->orderedColumnsMap[$sql] = $type;
return $sql . ' ' . $type;
}
/**
* {@inheritdoc}
*/
public function walkHavingClause($havingClause)
{
return ' HAVING ' . $this->walkConditionalExpression($havingClause->conditionalExpression);
}
/**
* {@inheritdoc}
*/
public function walkJoin($join)
{
$joinType = $join->joinType;
$joinDeclaration = $join->joinAssociationDeclaration;
$sql = ($joinType == AST\Join::JOIN_TYPE_LEFT || $joinType == AST\Join::JOIN_TYPE_LEFTOUTER)
? ' LEFT JOIN '
: ' INNER JOIN ';
switch (true) {
case ($joinDeclaration instanceof \Doctrine\ORM\Query\AST\RangeVariableDeclaration):
$class = $this->em->getClassMetadata($joinDeclaration->abstractSchemaName);
2012-11-22 16:59:44 +04:00
$condExprConjunction = $class->isInheritanceTypeJoined() && $joinType != AST\Join::JOIN_TYPE_LEFT && $joinType != AST\Join::JOIN_TYPE_LEFTOUTER
? ' AND '
: ' ON ';
$sql .= $this->walkRangeVariableDeclaration($joinDeclaration)
. $condExprConjunction . '(' . $this->walkConditionalExpression($join->conditionalExpression) . ')';
break;
case ($joinDeclaration instanceof \Doctrine\ORM\Query\AST\JoinAssociationDeclaration):
$sql .= $this->walkJoinAssociationDeclaration($joinDeclaration, $joinType);
// Handle WITH clause
if (($condExpr = $join->conditionalExpression) !== null) {
2013-03-11 04:08:58 +04:00
// Phase 2 AST optimization: Skip processing of ConditionalExpression
// if only one ConditionalTerm is defined
$sql .= ' AND (' . $this->walkConditionalExpression($condExpr) . ')';
}
break;
2012-06-18 22:31:20 +04:00
}
return $sql;
}
2011-10-30 15:12:18 +04:00
/**
* Walks down a CaseExpression AST node and generates the corresponding SQL.
*
* @param AST\CoalesceExpression|AST\NullIfExpression|AST\GeneralCaseExpression|AST\SimpleCaseExpression $expression
*
* @return string The SQL.
*/
public function walkCaseExpression($expression)
{
switch (true) {
case ($expression instanceof AST\CoalesceExpression):
return $this->walkCoalesceExpression($expression);
2011-10-30 15:12:18 +04:00
case ($expression instanceof AST\NullIfExpression):
return $this->walkNullIfExpression($expression);
2011-10-30 15:12:18 +04:00
case ($expression instanceof AST\GeneralCaseExpression):
return $this->walkGeneralCaseExpression($expression);
2011-10-30 15:12:18 +04:00
case ($expression instanceof AST\SimpleCaseExpression):
return $this->walkSimpleCaseExpression($expression);
2011-10-30 15:12:18 +04:00
default:
return '';
}
}
2011-10-30 15:12:18 +04:00
/**
* Walks down a CoalesceExpression AST node and generates the corresponding SQL.
*
* @param AST\CoalesceExpression $coalesceExpression
*
* @return string The SQL.
*/
public function walkCoalesceExpression($coalesceExpression)
{
$sql = 'COALESCE(';
$scalarExpressions = array();
2011-10-30 15:12:18 +04:00
foreach ($coalesceExpression->scalarExpressions as $scalarExpression) {
$scalarExpressions[] = $this->walkSimpleArithmeticExpression($scalarExpression);
}
2011-10-30 15:12:18 +04:00
$sql .= implode(', ', $scalarExpressions) . ')';
return $sql;
}
2011-10-30 15:12:18 +04:00
/**
* Walks down a NullIfExpression AST node and generates the corresponding SQL.
*
* @param AST\NullIfExpression $nullIfExpression
*
* @return string The SQL.
*/
public function walkNullIfExpression($nullIfExpression)
{
2011-10-30 15:12:18 +04:00
$firstExpression = is_string($nullIfExpression->firstExpression)
2012-06-01 01:03:01 +04:00
? $this->conn->quote($nullIfExpression->firstExpression)
: $this->walkSimpleArithmeticExpression($nullIfExpression->firstExpression);
2011-10-30 15:12:18 +04:00
$secondExpression = is_string($nullIfExpression->secondExpression)
2012-06-01 01:03:01 +04:00
? $this->conn->quote($nullIfExpression->secondExpression)
: $this->walkSimpleArithmeticExpression($nullIfExpression->secondExpression);
2011-10-30 15:12:18 +04:00
return 'NULLIF(' . $firstExpression . ', ' . $secondExpression . ')';
}
2011-10-30 15:12:18 +04:00
/**
* Walks down a GeneralCaseExpression AST node and generates the corresponding SQL.
*
* @param AST\GeneralCaseExpression $generalCaseExpression
*
* @return string The SQL.
*/
public function walkGeneralCaseExpression(AST\GeneralCaseExpression $generalCaseExpression)
{
$sql = 'CASE';
2011-10-30 15:12:18 +04:00
foreach ($generalCaseExpression->whenClauses as $whenClause) {
$sql .= ' WHEN ' . $this->walkConditionalExpression($whenClause->caseConditionExpression);
$sql .= ' THEN ' . $this->walkSimpleArithmeticExpression($whenClause->thenScalarExpression);
}
2011-10-30 15:12:18 +04:00
$sql .= ' ELSE ' . $this->walkSimpleArithmeticExpression($generalCaseExpression->elseScalarExpression) . ' END';
2011-10-30 15:12:18 +04:00
return $sql;
}
2011-10-30 15:12:18 +04:00
/**
* Walks down a SimpleCaseExpression AST node and generates the corresponding SQL.
*
* @param AST\SimpleCaseExpression $simpleCaseExpression
*
* @return string The SQL.
*/
public function walkSimpleCaseExpression($simpleCaseExpression)
{
$sql = 'CASE ' . $this->walkStateFieldPathExpression($simpleCaseExpression->caseOperand);
2011-10-30 15:12:18 +04:00
foreach ($simpleCaseExpression->simpleWhenClauses as $simpleWhenClause) {
$sql .= ' WHEN ' . $this->walkSimpleArithmeticExpression($simpleWhenClause->caseScalarExpression);
$sql .= ' THEN ' . $this->walkSimpleArithmeticExpression($simpleWhenClause->thenScalarExpression);
}
2011-10-30 15:12:18 +04:00
$sql .= ' ELSE ' . $this->walkSimpleArithmeticExpression($simpleCaseExpression->elseScalarExpression) . ' END';
2011-10-30 15:12:18 +04:00
return $sql;
}
/**
* {@inheritdoc}
*/
public function walkSelectExpression($selectExpression)
{
$sql = '';
$expr = $selectExpression->expression;
$hidden = $selectExpression->hiddenAliasResultVariable;
switch (true) {
case ($expr instanceof AST\PathExpression):
if ($expr->type !== AST\PathExpression::TYPE_STATE_FIELD) {
throw QueryException::invalidPathExpression($expr);
}
$fieldName = $expr->field;
$dqlAlias = $expr->identificationVariable;
2012-06-01 01:03:01 +04:00
$qComp = $this->queryComponents[$dqlAlias];
$class = $qComp['metadata'];
$resultAlias = $selectExpression->fieldIdentificationVariable ?: $fieldName;
$tableName = ($class->isInheritanceTypeJoined())
2012-06-01 01:03:01 +04:00
? $this->em->getUnitOfWork()->getEntityPersister($class->name)->getOwningTable($fieldName)
: $class->getTableName();
$sqlTableAlias = $this->getSQLTableAlias($tableName, $dqlAlias);
2012-06-12 03:14:17 +04:00
$columnName = $this->quoteStrategy->getColumnName($fieldName, $class, $this->platform);
$columnAlias = $this->getSQLColumnAlias($class->fieldMappings[$fieldName]['columnName']);
$col = $sqlTableAlias . '.' . $columnName;
$fieldType = $class->getTypeOfField($fieldName);
if (isset($class->fieldMappings[$fieldName]['requireSQLConversion'])) {
$type = Type::getType($fieldType);
2012-06-01 01:03:01 +04:00
$col = $type->convertToPHPValueSQL($col, $this->conn->getDatabasePlatform());
}
$sql .= $col . ' AS ' . $columnAlias;
2012-06-01 01:03:01 +04:00
$this->scalarResultAliasMap[$resultAlias] = $columnAlias;
if ( ! $hidden) {
2012-06-01 01:03:01 +04:00
$this->rsm->addScalarResult($columnAlias, $resultAlias, $fieldType);
$this->scalarFields[$dqlAlias][$fieldName] = $columnAlias;
}
break;
case ($expr instanceof AST\AggregateExpression):
case ($expr instanceof AST\Functions\FunctionNode):
case ($expr instanceof AST\SimpleArithmeticExpression):
case ($expr instanceof AST\ArithmeticTerm):
case ($expr instanceof AST\ArithmeticFactor):
2013-03-16 21:33:19 +04:00
case ($expr instanceof AST\ParenthesisExpression):
case ($expr instanceof AST\Literal):
case ($expr instanceof AST\NullIfExpression):
case ($expr instanceof AST\CoalesceExpression):
case ($expr instanceof AST\GeneralCaseExpression):
case ($expr instanceof AST\SimpleCaseExpression):
$columnAlias = $this->getSQLColumnAlias('sclr');
2012-06-01 01:03:01 +04:00
$resultAlias = $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
$sql .= $expr->dispatch($this) . ' AS ' . $columnAlias;
2012-06-01 01:03:01 +04:00
$this->scalarResultAliasMap[$resultAlias] = $columnAlias;
if ( ! $hidden) {
// We cannot resolve field type here; assume 'string'.
2012-06-01 01:03:01 +04:00
$this->rsm->addScalarResult($columnAlias, $resultAlias, 'string');
}
break;
case ($expr instanceof AST\Subselect):
$columnAlias = $this->getSQLColumnAlias('sclr');
2012-06-01 01:03:01 +04:00
$resultAlias = $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
$sql .= '(' . $this->walkSubselect($expr) . ') AS ' . $columnAlias;
2012-06-01 01:03:01 +04:00
$this->scalarResultAliasMap[$resultAlias] = $columnAlias;
if ( ! $hidden) {
// We cannot resolve field type here; assume 'string'.
2012-06-01 01:03:01 +04:00
$this->rsm->addScalarResult($columnAlias, $resultAlias, 'string');
}
break;
2012-01-03 16:31:54 +04:00
case ($expr instanceof AST\NewObjectExpression):
2012-07-01 02:25:54 +04:00
$sql .= $this->walkNewObject($expr);
2012-01-03 16:31:54 +04:00
break;
default:
// IdentificationVariable or PartialObjectExpression
if ($expr instanceof AST\PartialObjectExpression) {
$dqlAlias = $expr->identificationVariable;
$partialFieldSet = $expr->partialFieldSet;
} else {
$dqlAlias = $expr;
$partialFieldSet = array();
}
2011-10-30 15:12:18 +04:00
2012-06-01 01:03:01 +04:00
$queryComp = $this->queryComponents[$dqlAlias];
$class = $queryComp['metadata'];
$resultAlias = $selectExpression->fieldIdentificationVariable ?: null;
2011-10-30 15:12:18 +04:00
2012-06-01 01:03:01 +04:00
if ( ! isset($this->selectedClasses[$dqlAlias])) {
$this->selectedClasses[$dqlAlias] = array(
'class' => $class,
'dqlAlias' => $dqlAlias,
'resultAlias' => $resultAlias
);
}
$sqlParts = array();
// Select all fields from the queried class
foreach ($class->fieldMappings as $fieldName => $mapping) {
if ($partialFieldSet && ! in_array($fieldName, $partialFieldSet)) {
continue;
}
$tableName = (isset($mapping['inherited']))
2012-06-01 01:03:01 +04:00
? $this->em->getClassMetadata($mapping['inherited'])->getTableName()
: $class->getTableName();
$sqlTableAlias = $this->getSQLTableAlias($tableName, $dqlAlias);
$columnAlias = $this->getSQLColumnAlias($mapping['columnName']);
2012-06-12 03:14:17 +04:00
$quotedColumnName = $this->quoteStrategy->getColumnName($fieldName, $class, $this->platform);
$col = $sqlTableAlias . '.' . $quotedColumnName;
if (isset($class->fieldMappings[$fieldName]['requireSQLConversion'])) {
$type = Type::getType($class->getTypeOfField($fieldName));
2012-06-01 01:03:01 +04:00
$col = $type->convertToPHPValueSQL($col, $this->platform);
}
$sqlParts[] = $col . ' AS '. $columnAlias;
2012-06-01 01:03:01 +04:00
$this->scalarResultAliasMap[$resultAlias][] = $columnAlias;
2012-06-01 01:03:01 +04:00
$this->rsm->addFieldResult($dqlAlias, $columnAlias, $fieldName, $class->name);
}
// Add any additional fields of subclasses (excluding inherited fields)
// 1) on Single Table Inheritance: always, since its marginal overhead
// 2) on Class Table Inheritance only if partial objects are disallowed,
// since it requires outer joining subtables.
2012-06-01 01:03:01 +04:00
if ($class->isInheritanceTypeSingleTable() || ! $this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD)) {
foreach ($class->subClasses as $subClassName) {
2012-06-01 01:03:01 +04:00
$subClass = $this->em->getClassMetadata($subClassName);
$sqlTableAlias = $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias);
foreach ($subClass->fieldMappings as $fieldName => $mapping) {
if (isset($mapping['inherited']) || $partialFieldSet && !in_array($fieldName, $partialFieldSet)) {
continue;
}
$columnAlias = $this->getSQLColumnAlias($mapping['columnName']);
2012-06-12 03:14:17 +04:00
$quotedColumnName = $this->quoteStrategy->getColumnName($fieldName, $subClass, $this->platform);
2011-10-30 15:12:18 +04:00
$col = $sqlTableAlias . '.' . $quotedColumnName;
if (isset($subClass->fieldMappings[$fieldName]['requireSQLConversion'])) {
$type = Type::getType($subClass->getTypeOfField($fieldName));
2012-06-01 01:03:01 +04:00
$col = $type->convertToPHPValueSQL($col, $this->platform);
}
$sqlParts[] = $col . ' AS ' . $columnAlias;
2011-10-30 15:12:18 +04:00
2012-06-01 01:03:01 +04:00
$this->scalarResultAliasMap[$resultAlias][] = $columnAlias;
2012-06-01 01:03:01 +04:00
$this->rsm->addFieldResult($dqlAlias, $columnAlias, $fieldName, $subClassName);
}
}
}
$sql .= implode(', ', $sqlParts);
}
return $sql;
}
/**
* {@inheritdoc}
*/
public function walkQuantifiedExpression($qExpr)
{
return ' ' . strtoupper($qExpr->type) . '(' . $this->walkSubselect($qExpr->subselect) . ')';
}
/**
* {@inheritdoc}
*/
2009-03-19 15:43:48 +03:00
public function walkSubselect($subselect)
{
2012-06-01 01:03:01 +04:00
$useAliasesBefore = $this->useSqlTableAliases;
$rootAliasesBefore = $this->rootAliases;
2012-06-01 01:03:01 +04:00
$this->rootAliases = array(); // reset the rootAliases for the subselect
$this->useSqlTableAliases = true;
$sql = $this->walkSimpleSelectClause($subselect->simpleSelectClause);
$sql .= $this->walkSubselectFromClause($subselect->subselectFromClause);
$sql .= $this->walkWhereClause($subselect->whereClause);
$sql .= $subselect->groupByClause ? $this->walkGroupByClause($subselect->groupByClause) : '';
$sql .= $subselect->havingClause ? $this->walkHavingClause($subselect->havingClause) : '';
$sql .= $subselect->orderByClause ? $this->walkOrderByClause($subselect->orderByClause) : '';
2012-06-01 01:03:01 +04:00
$this->rootAliases = $rootAliasesBefore; // put the main aliases back
$this->useSqlTableAliases = $useAliasesBefore;
2009-03-19 15:43:48 +03:00
return $sql;
}
/**
* {@inheritdoc}
*/
2009-03-19 15:43:48 +03:00
public function walkSubselectFromClause($subselectFromClause)
{
$identificationVarDecls = $subselectFromClause->identificationVariableDeclarations;
$sqlParts = array ();
foreach ($identificationVarDecls as $subselectIdVarDecl) {
$sql = $this->platform->appendLockHint(
$this->walkRangeVariableDeclaration($subselectIdVarDecl->rangeVariableDeclaration),
$this->query->getHint(Query::HINT_LOCK_MODE)
);
foreach ($subselectIdVarDecl->joins as $join) {
$sql .= $this->walkJoin($join);
}
$sqlParts[] = $sql;
2009-03-19 15:43:48 +03:00
}
return ' FROM ' . implode(', ', $sqlParts);
2009-03-19 15:43:48 +03:00
}
/**
* {@inheritdoc}
*/
2009-03-19 15:43:48 +03:00
public function walkSimpleSelectClause($simpleSelectClause)
{
return 'SELECT' . ($simpleSelectClause->isDistinct ? ' DISTINCT' : '')
. $this->walkSimpleSelectExpression($simpleSelectClause->simpleSelectExpression);
2009-03-19 15:43:48 +03:00
}
2013-03-16 21:33:19 +04:00
/**
* @param \Doctrine\ORM\Query\AST\ParenthesisExpression $parenthesisExpression
*
* @return string.
*/
public function walkParenthesisExpression(AST\ParenthesisExpression $parenthesisExpression)
{
return sprintf('(%s)', $parenthesisExpression->expression->dispatch($this));
}
2012-07-01 02:25:54 +04:00
/**
* @param AST\NewObjectExpression $newObjectExpression
*
2012-07-01 02:25:54 +04:00
* @return string The SQL.
*/
public function walkNewObject($newObjectExpression)
{
$sqlSelectExpressions = array();
2012-08-12 21:40:26 +04:00
$objIndex = $this->newObjectCounter++;
2012-08-11 21:01:57 +04:00
2012-07-01 02:25:54 +04:00
foreach ($newObjectExpression->args as $argIndex => $e) {
2012-07-22 01:07:56 +04:00
$resultAlias = $this->scalarResultCounter++;
2012-08-11 19:56:47 +04:00
$columnAlias = $this->getSQLColumnAlias('sclr');
2012-07-01 02:25:54 +04:00
switch (true) {
2012-08-12 21:40:26 +04:00
case ($e instanceof AST\NewObjectExpression):
2012-07-01 02:25:54 +04:00
$sqlSelectExpressions[] = $e->dispatch($this);
break;
default:
2012-08-11 19:56:47 +04:00
$sqlSelectExpressions[] = trim($e->dispatch($this)) . ' AS ' . $columnAlias;
2012-07-01 02:25:54 +04:00
break;
}
2012-08-11 21:01:57 +04:00
switch (true) {
case ($e instanceof AST\PathExpression):
$fieldName = $e->field;
$dqlAlias = $e->identificationVariable;
$qComp = $this->queryComponents[$dqlAlias];
$class = $qComp['metadata'];
$fieldType = $class->getTypeOfField($fieldName);
break;
case ($e instanceof AST\Literal):
switch ($e->type) {
case AST\Literal::BOOLEAN:
$fieldType = 'boolean';
break;
case AST\Literal::NUMERIC:
$fieldType = is_float($e->value) ? 'float' : 'integer';
break;
}
break;
default:
$fieldType = 'string';
break;
}
2012-07-01 02:25:54 +04:00
$this->scalarResultAliasMap[$resultAlias] = $columnAlias;
2012-08-11 21:01:57 +04:00
$this->rsm->addScalarResult($columnAlias, $resultAlias, $fieldType);
2012-07-01 02:25:54 +04:00
$this->rsm->newObjectMappings[$columnAlias] = array(
'className' => $newObjectExpression->className,
'objIndex' => $objIndex,
'argIndex' => $argIndex
);
}
2012-08-11 19:56:47 +04:00
return implode(', ', $sqlSelectExpressions);
2012-07-01 02:25:54 +04:00
}
/**
* {@inheritdoc}
*/
2009-03-19 15:43:48 +03:00
public function walkSimpleSelectExpression($simpleSelectExpression)
{
$expr = $simpleSelectExpression->expression;
$sql = ' ';
switch (true) {
case ($expr instanceof AST\PathExpression):
$sql .= $this->walkPathExpression($expr);
break;
case ($expr instanceof AST\AggregateExpression):
2012-06-01 01:03:01 +04:00
$alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
$sql .= $this->walkAggregateExpression($expr) . ' AS dctrn__' . $alias;
break;
case ($expr instanceof AST\Subselect):
2012-06-01 01:03:01 +04:00
$alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
2012-06-01 01:03:01 +04:00
$columnAlias = 'sclr' . $this->aliasCounter++;
$this->scalarResultAliasMap[$alias] = $columnAlias;
$sql .= '(' . $this->walkSubselect($expr) . ') AS ' . $columnAlias;
break;
case ($expr instanceof AST\Functions\FunctionNode):
case ($expr instanceof AST\SimpleArithmeticExpression):
case ($expr instanceof AST\ArithmeticTerm):
case ($expr instanceof AST\ArithmeticFactor):
case ($expr instanceof AST\Literal):
case ($expr instanceof AST\NullIfExpression):
case ($expr instanceof AST\CoalesceExpression):
case ($expr instanceof AST\GeneralCaseExpression):
case ($expr instanceof AST\SimpleCaseExpression):
2012-06-01 01:03:01 +04:00
$alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
2011-10-30 15:12:18 +04:00
$columnAlias = $this->getSQLColumnAlias('sclr');
2012-06-01 01:03:01 +04:00
$this->scalarResultAliasMap[$alias] = $columnAlias;
2011-10-30 15:12:18 +04:00
$sql .= $expr->dispatch($this) . ' AS ' . $columnAlias;
break;
2011-10-30 15:12:18 +04:00
default: // IdentificationVariable
$sql .= $this->walkEntityIdentificationVariable($expr);
break;
2009-03-19 15:43:48 +03:00
}
return $sql;
2009-03-19 15:43:48 +03:00
}
/**
* {@inheritdoc}
*/
2009-03-19 15:43:48 +03:00
public function walkAggregateExpression($aggExpression)
{
return $aggExpression->functionName . '(' . ($aggExpression->isDistinct ? 'DISTINCT ' : '')
. $this->walkSimpleArithmeticExpression($aggExpression->pathExpression) . ')';
2009-03-19 15:43:48 +03:00
}
/**
* {@inheritdoc}
*/
public function walkGroupByClause($groupByClause)
{
$sqlParts = array();
2011-10-30 15:12:18 +04:00
2012-03-24 14:16:32 +04:00
foreach ($groupByClause->groupByItems as $groupByItem) {
$sqlParts[] = $this->walkGroupByItem($groupByItem);
}
2011-10-30 15:12:18 +04:00
return ' GROUP BY ' . implode(', ', $sqlParts);
}
/**
* {@inheritdoc}
*/
public function walkGroupByItem($groupByItem)
{
// StateFieldPathExpression
if ( ! is_string($groupByItem)) {
return $this->walkPathExpression($groupByItem);
}
// ResultVariable
2012-06-01 01:03:01 +04:00
if (isset($this->queryComponents[$groupByItem]['resultVariable'])) {
return $this->walkResultVariable($groupByItem);
}
// IdentificationVariable
$sqlParts = array();
2012-06-01 01:03:01 +04:00
foreach ($this->queryComponents[$groupByItem]['metadata']->fieldNames as $field) {
$item = new AST\PathExpression(AST\PathExpression::TYPE_STATE_FIELD, $groupByItem, $field);
$item->type = AST\PathExpression::TYPE_STATE_FIELD;
$sqlParts[] = $this->walkPathExpression($item);
}
2012-06-01 01:03:01 +04:00
foreach ($this->queryComponents[$groupByItem]['metadata']->associationMappings as $mapping) {
if ($mapping['isOwningSide'] && $mapping['type'] & ClassMetadataInfo::TO_ONE) {
$item = new AST\PathExpression(AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, $groupByItem, $mapping['fieldName']);
$item->type = AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION;
$sqlParts[] = $this->walkPathExpression($item);
}
}
return implode(', ', $sqlParts);
}
/**
* {@inheritdoc}
*/
2009-03-21 00:28:19 +03:00
public function walkDeleteClause(AST\DeleteClause $deleteClause)
{
2012-06-01 01:03:01 +04:00
$class = $this->em->getClassMetadata($deleteClause->abstractSchemaName);
$tableName = $class->getTableName();
2012-06-12 03:14:17 +04:00
$sql = 'DELETE FROM ' . $this->quoteStrategy->getTableName($class, $this->platform);
$this->setSQLTableAlias($tableName, $tableName, $deleteClause->aliasIdentificationVariable);
2012-06-01 01:03:01 +04:00
$this->rootAliases[] = $deleteClause->aliasIdentificationVariable;
2009-03-21 00:28:19 +03:00
return $sql;
}
/**
* {@inheritdoc}
*/
2009-03-21 22:58:52 +03:00
public function walkUpdateClause($updateClause)
{
2012-06-01 01:03:01 +04:00
$class = $this->em->getClassMetadata($updateClause->abstractSchemaName);
$tableName = $class->getTableName();
2012-06-12 03:14:17 +04:00
$sql = 'UPDATE ' . $this->quoteStrategy->getTableName($class, $this->platform);
$this->setSQLTableAlias($tableName, $tableName, $updateClause->aliasIdentificationVariable);
2012-06-01 01:03:01 +04:00
$this->rootAliases[] = $updateClause->aliasIdentificationVariable;
$sql .= ' SET ' . implode(', ', array_map(array($this, 'walkUpdateItem'), $updateClause->updateItems));
2009-03-21 22:58:52 +03:00
return $sql;
}
/**
* {@inheritdoc}
*/
2009-03-21 22:58:52 +03:00
public function walkUpdateItem($updateItem)
{
2012-06-01 01:03:01 +04:00
$useTableAliasesBefore = $this->useSqlTableAliases;
$this->useSqlTableAliases = false;
$sql = $this->walkPathExpression($updateItem->pathExpression) . ' = ';
$newValue = $updateItem->newValue;
switch (true) {
case ($newValue instanceof AST\Node):
$sql .= $newValue->dispatch($this);
break;
2011-10-30 15:12:18 +04:00
case ($newValue === null):
$sql .= 'NULL';
break;
2011-10-30 15:12:18 +04:00
default:
2012-06-01 01:03:01 +04:00
$sql .= $this->conn->quote($newValue);
break;
}
2012-06-01 01:03:01 +04:00
$this->useSqlTableAliases = $useTableAliasesBefore;
2009-03-21 22:58:52 +03:00
return $sql;
}
/**
* {@inheritdoc}
*/
public function walkWhereClause($whereClause)
{
$condSql = null !== $whereClause ? $this->walkConditionalExpression($whereClause->conditionalExpression) : '';
2012-06-01 01:03:01 +04:00
$discrSql = $this->_generateDiscriminatorColumnConditionSql($this->rootAliases);
2012-06-01 01:03:01 +04:00
if ($this->em->hasFilters()) {
2011-12-12 00:14:09 +04:00
$filterClauses = array();
2012-06-01 01:03:01 +04:00
foreach ($this->rootAliases as $dqlAlias) {
$class = $this->queryComponents[$dqlAlias]['metadata'];
2011-12-12 00:14:09 +04:00
$tableAlias = $this->getSQLTableAlias($class->table['name'], $dqlAlias);
2011-08-16 14:03:47 +04:00
2011-12-12 00:14:09 +04:00
if ($filterExpr = $this->generateFilterConditionSQL($class, $tableAlias)) {
$filterClauses[] = $filterExpr;
}
2011-08-16 14:03:47 +04:00
}
2011-12-12 00:14:09 +04:00
if (count($filterClauses)) {
if ($condSql) {
$condSql = '(' . $condSql . ') AND ';
2011-12-12 00:14:09 +04:00
}
2011-08-16 14:03:47 +04:00
2011-12-12 00:14:09 +04:00
$condSql .= implode(' AND ', $filterClauses);
}
2011-08-16 14:03:47 +04:00
}
if ($condSql) {
return ' WHERE ' . (( ! $discrSql) ? $condSql : '(' . $condSql . ') AND ' . $discrSql);
2011-10-30 15:12:18 +04:00
}
if ($discrSql) {
return ' WHERE ' . $discrSql;
}
return '';
}
/**
* {@inheritdoc}
*/
public function walkConditionalExpression($condExpr)
{
2013-03-11 04:08:58 +04:00
// Phase 2 AST optimization: Skip processing of ConditionalExpression
// if only one ConditionalTerm is defined
if ( ! ($condExpr instanceof AST\ConditionalExpression)) {
return $this->walkConditionalTerm($condExpr);
}
2011-10-30 15:12:18 +04:00
return implode(' OR ', array_map(array($this, 'walkConditionalTerm'), $condExpr->conditionalTerms));
}
/**
* {@inheritdoc}
*/
public function walkConditionalTerm($condTerm)
{
2013-03-11 04:08:58 +04:00
// Phase 2 AST optimization: Skip processing of ConditionalTerm
// if only one ConditionalFactor is defined
if ( ! ($condTerm instanceof AST\ConditionalTerm)) {
return $this->walkConditionalFactor($condTerm);
}
2011-10-30 15:12:18 +04:00
return implode(' AND ', array_map(array($this, 'walkConditionalFactor'), $condTerm->conditionalFactors));
}
/**
* {@inheritdoc}
*/
public function walkConditionalFactor($factor)
{
2013-03-11 04:08:58 +04:00
// Phase 2 AST optimization: Skip processing of ConditionalFactor
// if only one ConditionalPrimary is defined
return ( ! ($factor instanceof AST\ConditionalFactor))
? $this->walkConditionalPrimary($factor)
: ($factor->not ? 'NOT ' : '') . $this->walkConditionalPrimary($factor->conditionalPrimary);
}
/**
* {@inheritdoc}
*/
public function walkConditionalPrimary($primary)
{
if ($primary->isSimpleConditionalExpression()) {
return $primary->simpleConditionalExpression->dispatch($this);
2011-10-30 15:12:18 +04:00
}
if ($primary->isConditionalExpression()) {
$condExpr = $primary->conditionalExpression;
return '(' . $this->walkConditionalExpression($condExpr) . ')';
}
}
/**
* {@inheritdoc}
*/
public function walkExistsExpression($existsExpr)
{
$sql = ($existsExpr->not) ? 'NOT ' : '';
$sql .= 'EXISTS (' . $this->walkSubselect($existsExpr->subselect) . ')';
return $sql;
}
2009-06-14 21:34:28 +04:00
/**
* {@inheritdoc}
2009-06-14 21:34:28 +04:00
*/
public function walkCollectionMemberExpression($collMemberExpr)
{
$sql = $collMemberExpr->not ? 'NOT ' : '';
2009-06-14 21:34:28 +04:00
$sql .= 'EXISTS (SELECT 1 FROM ';
$entityExpr = $collMemberExpr->entityExpression;
2009-06-14 21:34:28 +04:00
$collPathExpr = $collMemberExpr->collectionValuedPathExpression;
2011-10-30 15:12:18 +04:00
$fieldName = $collPathExpr->field;
$dqlAlias = $collPathExpr->identificationVariable;
2011-10-30 15:12:18 +04:00
2012-06-01 01:03:01 +04:00
$class = $this->queryComponents[$dqlAlias]['metadata'];
2011-10-30 15:12:18 +04:00
switch (true) {
// InputParameter
case ($entityExpr instanceof AST\InputParameter):
$dqlParamKey = $entityExpr->name;
$entitySql = '?';
break;
// SingleValuedAssociationPathExpression | IdentificationVariable
case ($entityExpr instanceof AST\PathExpression):
$entitySql = $this->walkPathExpression($entityExpr);
break;
default:
throw new \BadMethodCallException("Not implemented");
2009-06-14 21:34:28 +04:00
}
2011-10-30 15:12:18 +04:00
$assoc = $class->associationMappings[$fieldName];
2011-10-30 15:12:18 +04:00
if ($assoc['type'] == ClassMetadata::ONE_TO_MANY) {
2012-06-01 01:03:01 +04:00
$targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
$targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName());
$sourceTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
2011-10-30 15:12:18 +04:00
2012-06-12 03:14:17 +04:00
$sql .= $this->quoteStrategy->getTableName($targetClass, $this->platform) . ' ' . $targetTableAlias . ' WHERE ';
2011-10-30 15:12:18 +04:00
$owningAssoc = $targetClass->associationMappings[$assoc['mappedBy']];
$sqlParts = array();
2011-10-30 15:12:18 +04:00
foreach ($owningAssoc['targetToSourceKeyColumns'] as $targetColumn => $sourceColumn) {
2012-06-12 03:14:17 +04:00
$targetColumn = $this->quoteStrategy->getColumnName($class->fieldNames[$targetColumn], $class, $this->platform);
2011-10-30 15:12:18 +04:00
$sqlParts[] = $sourceTableAlias . '.' . $targetColumn . ' = ' . $targetTableAlias . '.' . $sourceColumn;
2009-06-14 21:34:28 +04:00
}
2011-10-30 15:12:18 +04:00
2012-06-12 03:14:17 +04:00
foreach ($this->quoteStrategy->getIdentifierColumnNames($targetClass, $this->platform) as $targetColumnName) {
if (isset($dqlParamKey)) {
2012-06-01 01:03:01 +04:00
$this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++);
}
2011-10-30 15:12:18 +04:00
$sqlParts[] = $targetTableAlias . '.' . $targetColumnName . ' = ' . $entitySql;
2009-06-14 21:34:28 +04:00
}
$sql .= implode(' AND ', $sqlParts);
2009-06-14 21:34:28 +04:00
} else { // many-to-many
2012-06-01 01:03:01 +04:00
$targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
2011-10-30 15:12:18 +04:00
$owningAssoc = $assoc['isOwningSide'] ? $assoc : $targetClass->associationMappings[$assoc['mappedBy']];
$joinTable = $owningAssoc['joinTable'];
// SQL table aliases
$joinTableAlias = $this->getSQLTableAlias($joinTable['name']);
$targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName());
$sourceTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
2011-10-30 15:12:18 +04:00
2009-06-14 21:34:28 +04:00
// join to target table
2012-06-12 03:14:17 +04:00
$sql .= $this->quoteStrategy->getJoinTableName($owningAssoc, $targetClass, $this->platform) . ' ' . $joinTableAlias
. ' INNER JOIN ' . $this->quoteStrategy->getTableName($targetClass, $this->platform) . ' ' . $targetTableAlias . ' ON ';
2011-10-30 15:12:18 +04:00
2009-06-14 21:34:28 +04:00
// join conditions
$joinColumns = $assoc['isOwningSide'] ? $joinTable['inverseJoinColumns'] : $joinTable['joinColumns'];
$joinSqlParts = array();
2009-06-14 21:34:28 +04:00
foreach ($joinColumns as $joinColumn) {
2012-06-12 03:14:17 +04:00
$targetColumn = $this->quoteStrategy->getColumnName($targetClass->fieldNames[$joinColumn['referencedColumnName']], $targetClass, $this->platform);
$joinSqlParts[] = $joinTableAlias . '.' . $joinColumn['name'] . ' = ' . $targetTableAlias . '.' . $targetColumn;
2009-06-14 21:34:28 +04:00
}
$sql .= implode(' AND ', $joinSqlParts);
2009-06-14 21:34:28 +04:00
$sql .= ' WHERE ';
$joinColumns = $assoc['isOwningSide'] ? $joinTable['joinColumns'] : $joinTable['inverseJoinColumns'];
$sqlParts = array();
2011-10-30 15:12:18 +04:00
2009-06-14 21:34:28 +04:00
foreach ($joinColumns as $joinColumn) {
2012-06-12 03:14:17 +04:00
$targetColumn = $this->quoteStrategy->getColumnName($class->fieldNames[$joinColumn['referencedColumnName']], $class, $this->platform);
2010-03-27 01:07:31 +03:00
$sqlParts[] = $joinTableAlias . '.' . $joinColumn['name'] . ' = ' . $sourceTableAlias . '.' . $targetColumn;
2009-06-14 21:34:28 +04:00
}
2011-10-30 15:12:18 +04:00
2012-06-12 03:14:17 +04:00
foreach ($this->quoteStrategy->getIdentifierColumnNames($targetClass, $this->platform) as $targetColumnName) {
if (isset($dqlParamKey)) {
2012-06-01 01:03:01 +04:00
$this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++);
}
2011-10-30 15:12:18 +04:00
$sqlParts[] = $targetTableAlias . '.' . $targetColumnName . ' = ' . $entitySql;
2009-06-14 21:34:28 +04:00
}
$sql .= implode(' AND ', $sqlParts);
2009-06-14 21:34:28 +04:00
}
2010-07-30 19:44:33 +04:00
2009-06-14 21:34:28 +04:00
return $sql . ')';
}
2011-10-30 15:12:18 +04:00
/**
* {@inheritdoc}
*/
public function walkEmptyCollectionComparisonExpression($emptyCollCompExpr)
{
$sizeFunc = new AST\Functions\SizeFunction('size');
$sizeFunc->collectionPathExpression = $emptyCollCompExpr->expression;
return $sizeFunc->getSql($this) . ($emptyCollCompExpr->not ? ' > 0' : ' = 0');
}
/**
* {@inheritdoc}
*/
public function walkNullComparisonExpression($nullCompExpr)
{
2013-01-19 05:18:50 +04:00
$expression = $nullCompExpr->expression;
$comparison = ' IS' . ($nullCompExpr->not ? ' NOT' : '') . ' NULL';
2013-01-19 05:18:50 +04:00
if ($expression instanceof AST\InputParameter) {
$this->parserResult->addParameterMapping($expression->name, $this->sqlParamIndex++);
2013-01-19 05:18:50 +04:00
return '?' . $comparison;
}
return $expression->dispatch($this) . $comparison;
}
/**
* {@inheritdoc}
*/
public function walkInExpression($inExpr)
{
$sql = $this->walkArithmeticExpression($inExpr->expression) . ($inExpr->not ? ' NOT' : '') . ' IN (';
2011-10-30 15:12:18 +04:00
$sql .= ($inExpr->subselect)
? $this->walkSubselect($inExpr->subselect)
: implode(', ', array_map(array($this, 'walkInParameter'), $inExpr->literals));
$sql .= ')';
return $sql;
}
/**
* {@inheritdoc}
*/
2010-07-30 19:44:33 +04:00
public function walkInstanceOfExpression($instanceOfExpr)
{
$sql = '';
$dqlAlias = $instanceOfExpr->identificationVariable;
2012-06-01 01:03:01 +04:00
$discrClass = $class = $this->queryComponents[$dqlAlias]['metadata'];
2010-07-30 19:44:33 +04:00
if ($class->discriminatorColumn) {
2012-06-01 01:03:01 +04:00
$discrClass = $this->em->getClassMetadata($class->rootEntityName);
}
2012-06-01 01:03:01 +04:00
if ($this->useSqlTableAliases) {
$sql .= $this->getSQLTableAlias($discrClass->getTableName(), $dqlAlias) . '.';
}
2011-10-30 15:12:18 +04:00
$sql .= $class->discriminatorColumn['name'] . ($instanceOfExpr->not ? ' NOT IN ' : ' IN ');
2011-10-30 15:12:18 +04:00
$sqlParameterList = array();
2011-10-30 15:12:18 +04:00
foreach ($instanceOfExpr->value as $parameter) {
2013-06-08 01:01:52 +04:00
if ($parameter instanceof AST\InputParameter) {
2013-06-08 01:01:52 +04:00
$this->rsm->addMetadataParameterMapping($parameter->name, 'discriminatorValue');
$sqlParameterList[] = $this->walkInputParameter($parameter);
2013-06-08 01:01:52 +04:00
continue;
}
2011-10-30 15:12:18 +04:00
2013-06-08 01:01:52 +04:00
// Get name from ClassMetadata to resolve aliases.
$entityClassName = $this->em->getClassMetadata($parameter)->name;
$discriminatorValue = $class->discriminatorValue;
if ($entityClassName !== $class->name) {
$discrMap = array_flip($class->discriminatorMap);
2013-06-08 01:01:52 +04:00
if ( ! isset($discrMap[$entityClassName])) {
throw QueryException::instanceOfUnrelatedClass($entityClassName, $class->rootEntityName);
}
2013-06-08 01:01:52 +04:00
$discriminatorValue = $discrMap[$entityClassName];
}
2013-06-08 01:01:52 +04:00
$sqlParameterList[] = $this->conn->quote($discriminatorValue);
}
2011-10-30 15:12:18 +04:00
$sql .= '(' . implode(', ', $sqlParameterList) . ')';
return $sql;
}
/**
* {@inheritdoc}
*/
2009-10-13 14:48:46 +04:00
public function walkInParameter($inParam)
{
2011-10-30 15:12:18 +04:00
return $inParam instanceof AST\InputParameter
? $this->walkInputParameter($inParam)
: $this->walkLiteral($inParam);
2009-10-13 14:48:46 +04:00
}
/**
* {@inheritdoc}
*/
2009-03-21 22:58:52 +03:00
public function walkLiteral($literal)
{
2009-10-13 14:48:46 +04:00
switch ($literal->type) {
case AST\Literal::STRING:
2012-06-01 01:03:01 +04:00
return $this->conn->quote($literal->value);
2011-10-30 15:12:18 +04:00
2009-10-13 14:48:46 +04:00
case AST\Literal::BOOLEAN:
$bool = strtolower($literal->value) == 'true' ? true : false;
2012-06-01 01:03:01 +04:00
$boolVal = $this->conn->getDatabasePlatform()->convertBooleans($bool);
2011-10-30 15:12:18 +04:00
return $boolVal;
2011-10-30 15:12:18 +04:00
2009-10-13 14:48:46 +04:00
case AST\Literal::NUMERIC:
return $literal->value;
2011-10-30 15:12:18 +04:00
2009-10-13 14:48:46 +04:00
default:
throw QueryException::invalidLiteral($literal);
2009-03-21 22:58:52 +03:00
}
}
/**
* {@inheritdoc}
*/
public function walkBetweenExpression($betweenExpr)
{
$sql = $this->walkArithmeticExpression($betweenExpr->expression);
if ($betweenExpr->not) $sql .= ' NOT';
$sql .= ' BETWEEN ' . $this->walkArithmeticExpression($betweenExpr->leftBetweenExpression)
. ' AND ' . $this->walkArithmeticExpression($betweenExpr->rightBetweenExpression);
return $sql;
}
/**
* {@inheritdoc}
*/
public function walkLikeExpression($likeExpr)
{
$stringExpr = $likeExpr->stringExpression;
$sql = $stringExpr->dispatch($this) . ($likeExpr->not ? ' NOT' : '') . ' LIKE ';
if ($likeExpr->stringPattern instanceof AST\InputParameter) {
$inputParam = $likeExpr->stringPattern;
$dqlParamKey = $inputParam->name;
2012-06-01 01:03:01 +04:00
$this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++);
2009-06-14 21:34:28 +04:00
$sql .= '?';
} elseif ($likeExpr->stringPattern instanceof AST\Functions\FunctionNode ) {
$sql .= $this->walkFunction($likeExpr->stringPattern);
} elseif ($likeExpr->stringPattern instanceof AST\PathExpression) {
$sql .= $this->walkPathExpression($likeExpr->stringPattern);
} else {
$sql .= $this->walkLiteral($likeExpr->stringPattern);
}
if ($likeExpr->escapeChar) {
$sql .= ' ESCAPE ' . $this->walkLiteral($likeExpr->escapeChar);
}
return $sql;
}
/**
* {@inheritdoc}
*/
public function walkStateFieldPathExpression($stateFieldPathExpression)
{
return $this->walkPathExpression($stateFieldPathExpression);
}
/**
* {@inheritdoc}
*/
public function walkComparisonExpression($compExpr)
{
$leftExpr = $compExpr->leftExpression;
$rightExpr = $compExpr->rightExpression;
$sql = '';
2011-10-30 15:12:18 +04:00
$sql .= ($leftExpr instanceof AST\Node)
? $leftExpr->dispatch($this)
2012-06-01 01:03:01 +04:00
: (is_numeric($leftExpr) ? $leftExpr : $this->conn->quote($leftExpr));
$sql .= ' ' . $compExpr->operator . ' ';
2011-10-30 15:12:18 +04:00
$sql .= ($rightExpr instanceof AST\Node)
? $rightExpr->dispatch($this)
2012-06-01 01:03:01 +04:00
: (is_numeric($rightExpr) ? $rightExpr : $this->conn->quote($rightExpr));
return $sql;
}
/**
* {@inheritdoc}
*/
public function walkInputParameter($inputParam)
{
2012-06-01 01:03:01 +04:00
$this->parserResult->addParameterMapping($inputParam->name, $this->sqlParamIndex++);
2009-06-14 21:34:28 +04:00
return '?';
}
/**
* {@inheritdoc}
*/
public function walkArithmeticExpression($arithmeticExpr)
{
return ($arithmeticExpr->isSimpleArithmeticExpression())
2012-06-05 23:32:53 +04:00
? $this->walkSimpleArithmeticExpression($arithmeticExpr->simpleArithmeticExpression)
: '(' . $this->walkSubselect($arithmeticExpr->subselect) . ')';
}
/**
* {@inheritdoc}
*/
public function walkSimpleArithmeticExpression($simpleArithmeticExpr)
{
if ( ! ($simpleArithmeticExpr instanceof AST\SimpleArithmeticExpression)) {
return $this->walkArithmeticTerm($simpleArithmeticExpr);
}
2011-10-30 15:12:18 +04:00
return implode(' ', array_map(array($this, 'walkArithmeticTerm'), $simpleArithmeticExpr->arithmeticTerms));
}
/**
* {@inheritdoc}
*/
public function walkArithmeticTerm($term)
{
if (is_string($term)) {
2012-06-01 01:03:01 +04:00
return (isset($this->queryComponents[$term]))
? $this->walkResultVariable($this->queryComponents[$term]['token']['value'])
: $term;
}
2013-03-11 04:08:58 +04:00
// Phase 2 AST optimization: Skip processing of ArithmeticTerm
// if only one ArithmeticFactor is defined
if ( ! ($term instanceof AST\ArithmeticTerm)) {
return $this->walkArithmeticFactor($term);
}
2011-10-30 15:12:18 +04:00
return implode(' ', array_map(array($this, 'walkArithmeticFactor'), $term->arithmeticFactors));
}
/**
* {@inheritdoc}
*/
public function walkArithmeticFactor($factor)
{
if (is_string($factor)) {
return $factor;
}
2011-10-30 15:12:18 +04:00
2013-03-11 04:08:58 +04:00
// Phase 2 AST optimization: Skip processing of ArithmeticFactor
// if only one ArithmeticPrimary is defined
if ( ! ($factor instanceof AST\ArithmeticFactor)) {
return $this->walkArithmeticPrimary($factor);
}
2011-10-30 15:12:18 +04:00
$sign = $factor->isNegativeSigned() ? '-' : ($factor->isPositiveSigned() ? '+' : '');
2011-10-30 15:12:18 +04:00
return $sign . $this->walkArithmeticPrimary($factor->arithmeticPrimary);
}
/**
* Walks down an ArithmeticPrimary that represents an AST node, thereby generating the appropriate SQL.
*
* @param mixed $primary
*
* @return string The SQL.
*/
public function walkArithmeticPrimary($primary)
{
2009-10-13 14:48:46 +04:00
if ($primary instanceof AST\SimpleArithmeticExpression) {
return '(' . $this->walkSimpleArithmeticExpression($primary) . ')';
2011-10-30 15:12:18 +04:00
}
if ($primary instanceof AST\Node) {
return $primary->dispatch($this);
}
return $this->walkEntityIdentificationVariable($primary);
}
/**
* {@inheritdoc}
*/
public function walkStringPrimary($stringPrimary)
{
return (is_string($stringPrimary))
2012-06-01 01:03:01 +04:00
? $this->conn->quote($stringPrimary)
: $stringPrimary->dispatch($this);
}
/**
* {@inheritdoc}
*/
public function walkResultVariable($resultVariable)
{
2012-06-01 01:03:01 +04:00
$resultAlias = $this->scalarResultAliasMap[$resultVariable];
if (is_array($resultAlias)) {
return implode(', ', $resultAlias);
}
return $resultAlias;
}
}