vendor/doctrine/orm/lib/Doctrine/ORM/Query/SqlWalker.php line 2248

Open in your IDE?
  1. <?php
  2. /*
  3.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4.  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5.  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6.  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7.  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8.  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9.  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10.  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11.  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12.  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13.  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14.  *
  15.  * This software consists of voluntary contributions made by many individuals
  16.  * and is licensed under the MIT license. For more information, see
  17.  * <http://www.doctrine-project.org>.
  18.  */
  19. namespace Doctrine\ORM\Query;
  20. use BadMethodCallException;
  21. use Doctrine\DBAL\Connection;
  22. use Doctrine\DBAL\LockMode;
  23. use Doctrine\DBAL\Platforms\AbstractPlatform;
  24. use Doctrine\DBAL\Types\Type;
  25. use Doctrine\ORM\EntityManagerInterface;
  26. use Doctrine\ORM\Mapping\ClassMetadata;
  27. use Doctrine\ORM\Mapping\ClassMetadataInfo;
  28. use Doctrine\ORM\Mapping\QuoteStrategy;
  29. use Doctrine\ORM\OptimisticLockException;
  30. use Doctrine\ORM\Query;
  31. use Doctrine\ORM\Utility\HierarchyDiscriminatorResolver;
  32. use Doctrine\ORM\Utility\PersisterHelper;
  33. use function array_diff;
  34. use function array_filter;
  35. use function array_keys;
  36. use function array_map;
  37. use function array_merge;
  38. use function count;
  39. use function implode;
  40. use function in_array;
  41. use function is_array;
  42. use function is_float;
  43. use function is_numeric;
  44. use function is_string;
  45. use function preg_match;
  46. use function reset;
  47. use function sprintf;
  48. use function strtolower;
  49. use function strtoupper;
  50. use function trim;
  51. /**
  52.  * The SqlWalker is a TreeWalker that walks over a DQL AST and constructs
  53.  * the corresponding SQL.
  54.  */
  55. class SqlWalker implements TreeWalker
  56. {
  57.     public const HINT_DISTINCT 'doctrine.distinct';
  58.     /**
  59.      * Used to mark a query as containing a PARTIAL expression, which needs to be known by SLC.
  60.      */
  61.     public const HINT_PARTIAL 'doctrine.partial';
  62.     /** @var ResultSetMapping */
  63.     private $rsm;
  64.     /**
  65.      * Counter for generating unique column aliases.
  66.      *
  67.      * @var int
  68.      */
  69.     private $aliasCounter 0;
  70.     /**
  71.      * Counter for generating unique table aliases.
  72.      *
  73.      * @var int
  74.      */
  75.     private $tableAliasCounter 0;
  76.     /**
  77.      * Counter for generating unique scalar result.
  78.      *
  79.      * @var int
  80.      */
  81.     private $scalarResultCounter 1;
  82.     /**
  83.      * Counter for generating unique parameter indexes.
  84.      *
  85.      * @var int
  86.      */
  87.     private $sqlParamIndex 0;
  88.     /**
  89.      * Counter for generating indexes.
  90.      *
  91.      * @var int
  92.      */
  93.     private $newObjectCounter 0;
  94.     /** @var ParserResult */
  95.     private $parserResult;
  96.     /** @var EntityManagerInterface */
  97.     private $em;
  98.     /** @var Connection */
  99.     private $conn;
  100.     /** @var Query */
  101.     private $query;
  102.     /** @var mixed[] */
  103.     private $tableAliasMap = [];
  104.     /**
  105.      * Map from result variable names to their SQL column alias names.
  106.      *
  107.      * @psalm-var array<string, string|list<string>>
  108.      */
  109.     private $scalarResultAliasMap = [];
  110.     /**
  111.      * Map from Table-Alias + Column-Name to OrderBy-Direction.
  112.      *
  113.      * @var array<string, string>
  114.      */
  115.     private $orderedColumnsMap = [];
  116.     /**
  117.      * Map from DQL-Alias + Field-Name to SQL Column Alias.
  118.      *
  119.      * @var array<string, array<string, string>>
  120.      */
  121.     private $scalarFields = [];
  122.     /**
  123.      * Map of all components/classes that appear in the DQL query.
  124.      *
  125.      * @psalm-var array<string, array{
  126.      *                metadata: ClassMetadata,
  127.      *                parent: string,
  128.      *                relation: mixed[],
  129.      *                map: mixed,
  130.      *                nestingLevel: int,
  131.      *                token: array
  132.      *            }>
  133.      */
  134.     private $queryComponents;
  135.     /**
  136.      * A list of classes that appear in non-scalar SelectExpressions.
  137.      *
  138.      * @psalm-var list<array{class: ClassMetadata, dqlAlias: string, resultAlias: string}>
  139.      */
  140.     private $selectedClasses = [];
  141.     /**
  142.      * The DQL alias of the root class of the currently traversed query.
  143.      *
  144.      * @psalm-var list<string>
  145.      */
  146.     private $rootAliases = [];
  147.     /**
  148.      * Flag that indicates whether to generate SQL table aliases in the SQL.
  149.      * These should only be generated for SELECT queries, not for UPDATE/DELETE.
  150.      *
  151.      * @var bool
  152.      */
  153.     private $useSqlTableAliases true;
  154.     /**
  155.      * The database platform abstraction.
  156.      *
  157.      * @var AbstractPlatform
  158.      */
  159.     private $platform;
  160.     /**
  161.      * The quote strategy.
  162.      *
  163.      * @var QuoteStrategy
  164.      */
  165.     private $quoteStrategy;
  166.     /**
  167.      * {@inheritDoc}
  168.      */
  169.     public function __construct($query$parserResult, array $queryComponents)
  170.     {
  171.         $this->query           $query;
  172.         $this->parserResult    $parserResult;
  173.         $this->queryComponents $queryComponents;
  174.         $this->rsm             $parserResult->getResultSetMapping();
  175.         $this->em              $query->getEntityManager();
  176.         $this->conn            $this->em->getConnection();
  177.         $this->platform        $this->conn->getDatabasePlatform();
  178.         $this->quoteStrategy   $this->em->getConfiguration()->getQuoteStrategy();
  179.     }
  180.     /**
  181.      * Gets the Query instance used by the walker.
  182.      *
  183.      * @return Query
  184.      */
  185.     public function getQuery()
  186.     {
  187.         return $this->query;
  188.     }
  189.     /**
  190.      * Gets the Connection used by the walker.
  191.      *
  192.      * @return Connection
  193.      */
  194.     public function getConnection()
  195.     {
  196.         return $this->conn;
  197.     }
  198.     /**
  199.      * Gets the EntityManager used by the walker.
  200.      *
  201.      * @return EntityManagerInterface
  202.      */
  203.     public function getEntityManager()
  204.     {
  205.         return $this->em;
  206.     }
  207.     /**
  208.      * Gets the information about a single query component.
  209.      *
  210.      * @param string $dqlAlias The DQL alias.
  211.      *
  212.      * @psalm-return array{
  213.      *                   metadata: ClassMetadata,
  214.      *                   parent: string,
  215.      *                   relation: mixed[],
  216.      *                   map: mixed,
  217.      *                   nestingLevel: int,
  218.      *                   token: array
  219.      *               }
  220.      */
  221.     public function getQueryComponent($dqlAlias)
  222.     {
  223.         return $this->queryComponents[$dqlAlias];
  224.     }
  225.     /**
  226.      * {@inheritdoc}
  227.      */
  228.     public function getQueryComponents()
  229.     {
  230.         return $this->queryComponents;
  231.     }
  232.     /**
  233.      * {@inheritdoc}
  234.      */
  235.     public function setQueryComponent($dqlAlias, array $queryComponent)
  236.     {
  237.         $requiredKeys = ['metadata''parent''relation''map''nestingLevel''token'];
  238.         if (array_diff($requiredKeysarray_keys($queryComponent))) {
  239.             throw QueryException::invalidQueryComponent($dqlAlias);
  240.         }
  241.         $this->queryComponents[$dqlAlias] = $queryComponent;
  242.     }
  243.     /**
  244.      * {@inheritdoc}
  245.      */
  246.     public function getExecutor($AST)
  247.     {
  248.         switch (true) {
  249.             case $AST instanceof AST\DeleteStatement:
  250.                 $primaryClass $this->em->getClassMetadata($AST->deleteClause->abstractSchemaName);
  251.                 return $primaryClass->isInheritanceTypeJoined()
  252.                     ? new Exec\MultiTableDeleteExecutor($AST$this)
  253.                     : new Exec\SingleTableDeleteUpdateExecutor($AST$this);
  254.             case $AST instanceof AST\UpdateStatement:
  255.                 $primaryClass $this->em->getClassMetadata($AST->updateClause->abstractSchemaName);
  256.                 return $primaryClass->isInheritanceTypeJoined()
  257.                     ? new Exec\MultiTableUpdateExecutor($AST$this)
  258.                     : new Exec\SingleTableDeleteUpdateExecutor($AST$this);
  259.             default:
  260.                 return new Exec\SingleSelectExecutor($AST$this);
  261.         }
  262.     }
  263.     /**
  264.      * Generates a unique, short SQL table alias.
  265.      *
  266.      * @param string $tableName Table name
  267.      * @param string $dqlAlias  The DQL alias.
  268.      *
  269.      * @return string Generated table alias.
  270.      */
  271.     public function getSQLTableAlias($tableName$dqlAlias '')
  272.     {
  273.         $tableName .= $dqlAlias '@[' $dqlAlias ']' '';
  274.         if (! isset($this->tableAliasMap[$tableName])) {
  275.             $this->tableAliasMap[$tableName] = (preg_match('/[a-z]/i'$tableName[0]) ? strtolower($tableName[0]) : 't')
  276.                 . $this->tableAliasCounter++ . '_';
  277.         }
  278.         return $this->tableAliasMap[$tableName];
  279.     }
  280.     /**
  281.      * Forces the SqlWalker to use a specific alias for a table name, rather than
  282.      * generating an alias on its own.
  283.      *
  284.      * @param string $tableName
  285.      * @param string $alias
  286.      * @param string $dqlAlias
  287.      *
  288.      * @return string
  289.      */
  290.     public function setSQLTableAlias($tableName$alias$dqlAlias '')
  291.     {
  292.         $tableName .= $dqlAlias '@[' $dqlAlias ']' '';
  293.         $this->tableAliasMap[$tableName] = $alias;
  294.         return $alias;
  295.     }
  296.     /**
  297.      * Gets an SQL column alias for a column name.
  298.      *
  299.      * @param string $columnName
  300.      *
  301.      * @return string
  302.      */
  303.     public function getSQLColumnAlias($columnName)
  304.     {
  305.         return $this->quoteStrategy->getColumnAlias($columnName$this->aliasCounter++, $this->platform);
  306.     }
  307.     /**
  308.      * Generates the SQL JOINs that are necessary for Class Table Inheritance
  309.      * for the given class.
  310.      *
  311.      * @param ClassMetadata $class    The class for which to generate the joins.
  312.      * @param string        $dqlAlias The DQL alias of the class.
  313.      *
  314.      * @return string The SQL.
  315.      */
  316.     private function generateClassTableInheritanceJoins(
  317.         ClassMetadata $class,
  318.         string $dqlAlias
  319.     ): string {
  320.         $sql '';
  321.         $baseTableAlias $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
  322.         // INNER JOIN parent class tables
  323.         foreach ($class->parentClasses as $parentClassName) {
  324.             $parentClass $this->em->getClassMetadata($parentClassName);
  325.             $tableAlias  $this->getSQLTableAlias($parentClass->getTableName(), $dqlAlias);
  326.             // If this is a joined association we must use left joins to preserve the correct result.
  327.             $sql .= isset($this->queryComponents[$dqlAlias]['relation']) ? ' LEFT ' ' INNER ';
  328.             $sql .= 'JOIN ' $this->quoteStrategy->getTableName($parentClass$this->platform) . ' ' $tableAlias ' ON ';
  329.             $sqlParts = [];
  330.             foreach ($this->quoteStrategy->getIdentifierColumnNames($class$this->platform) as $columnName) {
  331.                 $sqlParts[] = $baseTableAlias '.' $columnName ' = ' $tableAlias '.' $columnName;
  332.             }
  333.             // Add filters on the root class
  334.             $sqlParts[] = $this->generateFilterConditionSQL($parentClass$tableAlias);
  335.             $sql .= implode(' AND 'array_filter($sqlParts));
  336.         }
  337.         // Ignore subclassing inclusion if partial objects is disallowed
  338.         if ($this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD)) {
  339.             return $sql;
  340.         }
  341.         // LEFT JOIN child class tables
  342.         foreach ($class->subClasses as $subClassName) {
  343.             $subClass   $this->em->getClassMetadata($subClassName);
  344.             $tableAlias $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias);
  345.             $sql .= ' LEFT JOIN ' $this->quoteStrategy->getTableName($subClass$this->platform) . ' ' $tableAlias ' ON ';
  346.             $sqlParts = [];
  347.             foreach ($this->quoteStrategy->getIdentifierColumnNames($subClass$this->platform) as $columnName) {
  348.                 $sqlParts[] = $baseTableAlias '.' $columnName ' = ' $tableAlias '.' $columnName;
  349.             }
  350.             $sql .= implode(' AND '$sqlParts);
  351.         }
  352.         return $sql;
  353.     }
  354.     private function generateOrderedCollectionOrderByItems(): string
  355.     {
  356.         $orderedColumns = [];
  357.         foreach ($this->selectedClasses as $selectedClass) {
  358.             $dqlAlias $selectedClass['dqlAlias'];
  359.             $qComp    $this->queryComponents[$dqlAlias];
  360.             if (! isset($qComp['relation']['orderBy'])) {
  361.                 continue;
  362.             }
  363.             $persister $this->em->getUnitOfWork()->getEntityPersister($qComp['metadata']->name);
  364.             foreach ($qComp['relation']['orderBy'] as $fieldName => $orientation) {
  365.                 $columnName $this->quoteStrategy->getColumnName($fieldName$qComp['metadata'], $this->platform);
  366.                 $tableName  $qComp['metadata']->isInheritanceTypeJoined()
  367.                     ? $persister->getOwningTable($fieldName)
  368.                     : $qComp['metadata']->getTableName();
  369.                 $orderedColumn $this->getSQLTableAlias($tableName$dqlAlias) . '.' $columnName;
  370.                 // OrderByClause should replace an ordered relation. see - DDC-2475
  371.                 if (isset($this->orderedColumnsMap[$orderedColumn])) {
  372.                     continue;
  373.                 }
  374.                 $this->orderedColumnsMap[$orderedColumn] = $orientation;
  375.                 $orderedColumns[]                        = $orderedColumn ' ' $orientation;
  376.             }
  377.         }
  378.         return implode(', '$orderedColumns);
  379.     }
  380.     /**
  381.      * Generates a discriminator column SQL condition for the class with the given DQL alias.
  382.      *
  383.      * @psalm-param list<string> $dqlAliases List of root DQL aliases to inspect for discriminator restrictions.
  384.      */
  385.     private function generateDiscriminatorColumnConditionSQL(array $dqlAliases): string
  386.     {
  387.         $sqlParts = [];
  388.         foreach ($dqlAliases as $dqlAlias) {
  389.             $class $this->queryComponents[$dqlAlias]['metadata'];
  390.             if (! $class->isInheritanceTypeSingleTable()) {
  391.                 continue;
  392.             }
  393.             $conn   $this->em->getConnection();
  394.             $values = [];
  395.             if ($class->discriminatorValue !== null) { // discriminators can be 0
  396.                 $values[] = $conn->quote($class->discriminatorValue);
  397.             }
  398.             foreach ($class->subClasses as $subclassName) {
  399.                 $values[] = $conn->quote($this->em->getClassMetadata($subclassName)->discriminatorValue);
  400.             }
  401.             $sqlTableAlias $this->useSqlTableAliases
  402.                 $this->getSQLTableAlias($class->getTableName(), $dqlAlias) . '.'
  403.                 '';
  404.             $sqlParts[] = $sqlTableAlias $class->discriminatorColumn['name'] . ' IN (' implode(', '$values) . ')';
  405.         }
  406.         $sql implode(' AND '$sqlParts);
  407.         return count($sqlParts) > '(' $sql ')' $sql;
  408.     }
  409.     /**
  410.      * Generates the filter SQL for a given entity and table alias.
  411.      *
  412.      * @param ClassMetadata $targetEntity     Metadata of the target entity.
  413.      * @param string        $targetTableAlias The table alias of the joined/selected table.
  414.      *
  415.      * @return string The SQL query part to add to a query.
  416.      */
  417.     private function generateFilterConditionSQL(
  418.         ClassMetadata $targetEntity,
  419.         string $targetTableAlias
  420.     ): string {
  421.         if (! $this->em->hasFilters()) {
  422.             return '';
  423.         }
  424.         switch ($targetEntity->inheritanceType) {
  425.             case ClassMetadata::INHERITANCE_TYPE_NONE:
  426.                 break;
  427.             case ClassMetadata::INHERITANCE_TYPE_JOINED:
  428.                 // The classes in the inheritance will be added to the query one by one,
  429.                 // but only the root node is getting filtered
  430.                 if ($targetEntity->name !== $targetEntity->rootEntityName) {
  431.                     return '';
  432.                 }
  433.                 break;
  434.             case ClassMetadata::INHERITANCE_TYPE_SINGLE_TABLE:
  435.                 // With STI the table will only be queried once, make sure that the filters
  436.                 // are added to the root entity
  437.                 $targetEntity $this->em->getClassMetadata($targetEntity->rootEntityName);
  438.                 break;
  439.             default:
  440.                 //@todo: throw exception?
  441.                 return '';
  442.         }
  443.         $filterClauses = [];
  444.         foreach ($this->em->getFilters()->getEnabledFilters() as $filter) {
  445.             $filterExpr $filter->addFilterConstraint($targetEntity$targetTableAlias);
  446.             if ($filterExpr !== '') {
  447.                 $filterClauses[] = '(' $filterExpr ')';
  448.             }
  449.         }
  450.         return implode(' AND '$filterClauses);
  451.     }
  452.     /**
  453.      * {@inheritdoc}
  454.      */
  455.     public function walkSelectStatement(AST\SelectStatement $AST)
  456.     {
  457.         $limit    $this->query->getMaxResults();
  458.         $offset   $this->query->getFirstResult();
  459.         $lockMode $this->query->getHint(Query::HINT_LOCK_MODE);
  460.         $sql      $this->walkSelectClause($AST->selectClause)
  461.             . $this->walkFromClause($AST->fromClause)
  462.             . $this->walkWhereClause($AST->whereClause);
  463.         if ($AST->groupByClause) {
  464.             $sql .= $this->walkGroupByClause($AST->groupByClause);
  465.         }
  466.         if ($AST->havingClause) {
  467.             $sql .= $this->walkHavingClause($AST->havingClause);
  468.         }
  469.         if ($AST->orderByClause) {
  470.             $sql .= $this->walkOrderByClause($AST->orderByClause);
  471.         }
  472.         $orderBySql $this->generateOrderedCollectionOrderByItems();
  473.         if (! $AST->orderByClause && $orderBySql) {
  474.             $sql .= ' ORDER BY ' $orderBySql;
  475.         }
  476.         if ($limit !== null || $offset !== null) {
  477.             $sql $this->platform->modifyLimitQuery($sql$limit$offset);
  478.         }
  479.         if ($lockMode === null || $lockMode === false || $lockMode === LockMode::NONE) {
  480.             return $sql;
  481.         }
  482.         if ($lockMode === LockMode::PESSIMISTIC_READ) {
  483.             return $sql ' ' $this->platform->getReadLockSQL();
  484.         }
  485.         if ($lockMode === LockMode::PESSIMISTIC_WRITE) {
  486.             return $sql ' ' $this->platform->getWriteLockSQL();
  487.         }
  488.         if ($lockMode !== LockMode::OPTIMISTIC) {
  489.             throw QueryException::invalidLockMode();
  490.         }
  491.         foreach ($this->selectedClasses as $selectedClass) {
  492.             if (! $selectedClass['class']->isVersioned) {
  493.                 throw OptimisticLockException::lockFailed($selectedClass['class']->name);
  494.             }
  495.         }
  496.         return $sql;
  497.     }
  498.     /**
  499.      * {@inheritdoc}
  500.      */
  501.     public function walkUpdateStatement(AST\UpdateStatement $AST)
  502.     {
  503.         $this->useSqlTableAliases false;
  504.         $this->rsm->isSelect      false;
  505.         return $this->walkUpdateClause($AST->updateClause)
  506.             . $this->walkWhereClause($AST->whereClause);
  507.     }
  508.     /**
  509.      * {@inheritdoc}
  510.      */
  511.     public function walkDeleteStatement(AST\DeleteStatement $AST)
  512.     {
  513.         $this->useSqlTableAliases false;
  514.         $this->rsm->isSelect      false;
  515.         return $this->walkDeleteClause($AST->deleteClause)
  516.             . $this->walkWhereClause($AST->whereClause);
  517.     }
  518.     /**
  519.      * Walks down an IdentificationVariable AST node, thereby generating the appropriate SQL.
  520.      * This one differs of ->walkIdentificationVariable() because it generates the entity identifiers.
  521.      *
  522.      * @param string $identVariable
  523.      *
  524.      * @return string
  525.      */
  526.     public function walkEntityIdentificationVariable($identVariable)
  527.     {
  528.         $class      $this->queryComponents[$identVariable]['metadata'];
  529.         $tableAlias $this->getSQLTableAlias($class->getTableName(), $identVariable);
  530.         $sqlParts   = [];
  531.         foreach ($this->quoteStrategy->getIdentifierColumnNames($class$this->platform) as $columnName) {
  532.             $sqlParts[] = $tableAlias '.' $columnName;
  533.         }
  534.         return implode(', '$sqlParts);
  535.     }
  536.     /**
  537.      * Walks down an IdentificationVariable (no AST node associated), thereby generating the SQL.
  538.      *
  539.      * @param string $identificationVariable
  540.      * @param string $fieldName
  541.      *
  542.      * @return string The SQL.
  543.      */
  544.     public function walkIdentificationVariable($identificationVariable$fieldName null)
  545.     {
  546.         $class $this->queryComponents[$identificationVariable]['metadata'];
  547.         if (
  548.             $fieldName !== null && $class->isInheritanceTypeJoined() &&
  549.             isset($class->fieldMappings[$fieldName]['inherited'])
  550.         ) {
  551.             $class $this->em->getClassMetadata($class->fieldMappings[$fieldName]['inherited']);
  552.         }
  553.         return $this->getSQLTableAlias($class->getTableName(), $identificationVariable);
  554.     }
  555.     /**
  556.      * {@inheritdoc}
  557.      */
  558.     public function walkPathExpression($pathExpr)
  559.     {
  560.         $sql '';
  561.         switch ($pathExpr->type) {
  562.             case AST\PathExpression::TYPE_STATE_FIELD:
  563.                 $fieldName $pathExpr->field;
  564.                 $dqlAlias  $pathExpr->identificationVariable;
  565.                 $class     $this->queryComponents[$dqlAlias]['metadata'];
  566.                 if ($this->useSqlTableAliases) {
  567.                     $sql .= $this->walkIdentificationVariable($dqlAlias$fieldName) . '.';
  568.                 }
  569.                 $sql .= $this->quoteStrategy->getColumnName($fieldName$class$this->platform);
  570.                 break;
  571.             case AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION:
  572.                 // 1- the owning side:
  573.                 //    Just use the foreign key, i.e. u.group_id
  574.                 $fieldName $pathExpr->field;
  575.                 $dqlAlias  $pathExpr->identificationVariable;
  576.                 $class     $this->queryComponents[$dqlAlias]['metadata'];
  577.                 if (isset($class->associationMappings[$fieldName]['inherited'])) {
  578.                     $class $this->em->getClassMetadata($class->associationMappings[$fieldName]['inherited']);
  579.                 }
  580.                 $assoc $class->associationMappings[$fieldName];
  581.                 if (! $assoc['isOwningSide']) {
  582.                     throw QueryException::associationPathInverseSideNotSupported($pathExpr);
  583.                 }
  584.                 // COMPOSITE KEYS NOT (YET?) SUPPORTED
  585.                 if (count($assoc['sourceToTargetKeyColumns']) > 1) {
  586.                     throw QueryException::associationPathCompositeKeyNotSupported();
  587.                 }
  588.                 if ($this->useSqlTableAliases) {
  589.                     $sql .= $this->getSQLTableAlias($class->getTableName(), $dqlAlias) . '.';
  590.                 }
  591.                 $sql .= reset($assoc['targetToSourceKeyColumns']);
  592.                 break;
  593.             default:
  594.                 throw QueryException::invalidPathExpression($pathExpr);
  595.         }
  596.         return $sql;
  597.     }
  598.     /**
  599.      * {@inheritdoc}
  600.      */
  601.     public function walkSelectClause($selectClause)
  602.     {
  603.         $sql                  'SELECT ' . ($selectClause->isDistinct 'DISTINCT ' '');
  604.         $sqlSelectExpressions array_filter(array_map([$this'walkSelectExpression'], $selectClause->selectExpressions));
  605.         if ($this->query->getHint(Query::HINT_INTERNAL_ITERATION) === true && $selectClause->isDistinct) {
  606.             $this->query->setHint(self::HINT_DISTINCTtrue);
  607.         }
  608.         $addMetaColumns = ! $this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD) &&
  609.             $this->query->getHydrationMode() === Query::HYDRATE_OBJECT
  610.             || $this->query->getHint(Query::HINT_INCLUDE_META_COLUMNS);
  611.         foreach ($this->selectedClasses as $selectedClass) {
  612.             $class       $selectedClass['class'];
  613.             $dqlAlias    $selectedClass['dqlAlias'];
  614.             $resultAlias $selectedClass['resultAlias'];
  615.             // Register as entity or joined entity result
  616.             if ($this->queryComponents[$dqlAlias]['relation'] === null) {
  617.                 $this->rsm->addEntityResult($class->name$dqlAlias$resultAlias);
  618.             } else {
  619.                 $this->rsm->addJoinedEntityResult(
  620.                     $class->name,
  621.                     $dqlAlias,
  622.                     $this->queryComponents[$dqlAlias]['parent'],
  623.                     $this->queryComponents[$dqlAlias]['relation']['fieldName']
  624.                 );
  625.             }
  626.             if ($class->isInheritanceTypeSingleTable() || $class->isInheritanceTypeJoined()) {
  627.                 // Add discriminator columns to SQL
  628.                 $rootClass   $this->em->getClassMetadata($class->rootEntityName);
  629.                 $tblAlias    $this->getSQLTableAlias($rootClass->getTableName(), $dqlAlias);
  630.                 $discrColumn $rootClass->discriminatorColumn;
  631.                 $columnAlias $this->getSQLColumnAlias($discrColumn['name']);
  632.                 $sqlSelectExpressions[] = $tblAlias '.' $discrColumn['name'] . ' AS ' $columnAlias;
  633.                 $this->rsm->setDiscriminatorColumn($dqlAlias$columnAlias);
  634.                 $this->rsm->addMetaResult($dqlAlias$columnAlias$discrColumn['fieldName'], false$discrColumn['type']);
  635.             }
  636.             // Add foreign key columns to SQL, if necessary
  637.             if (! $addMetaColumns && ! $class->containsForeignIdentifier) {
  638.                 continue;
  639.             }
  640.             // Add foreign key columns of class and also parent classes
  641.             foreach ($class->associationMappings as $assoc) {
  642.                 if (
  643.                     ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)
  644.                     || ( ! $addMetaColumns && ! isset($assoc['id']))
  645.                 ) {
  646.                     continue;
  647.                 }
  648.                 $targetClass   $this->em->getClassMetadata($assoc['targetEntity']);
  649.                 $isIdentifier  = (isset($assoc['id']) && $assoc['id'] === true);
  650.                 $owningClass   = isset($assoc['inherited']) ? $this->em->getClassMetadata($assoc['inherited']) : $class;
  651.                 $sqlTableAlias $this->getSQLTableAlias($owningClass->getTableName(), $dqlAlias);
  652.                 foreach ($assoc['joinColumns'] as $joinColumn) {
  653.                     $columnName  $joinColumn['name'];
  654.                     $columnAlias $this->getSQLColumnAlias($columnName);
  655.                     $columnType  PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass$this->em);
  656.                     $quotedColumnName       $this->quoteStrategy->getJoinColumnName($joinColumn$class$this->platform);
  657.                     $sqlSelectExpressions[] = $sqlTableAlias '.' $quotedColumnName ' AS ' $columnAlias;
  658.                     $this->rsm->addMetaResult($dqlAlias$columnAlias$columnName$isIdentifier$columnType);
  659.                 }
  660.             }
  661.             // Add foreign key columns to SQL, if necessary
  662.             if (! $addMetaColumns) {
  663.                 continue;
  664.             }
  665.             // Add foreign key columns of subclasses
  666.             foreach ($class->subClasses as $subClassName) {
  667.                 $subClass      $this->em->getClassMetadata($subClassName);
  668.                 $sqlTableAlias $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias);
  669.                 foreach ($subClass->associationMappings as $assoc) {
  670.                     // Skip if association is inherited
  671.                     if (isset($assoc['inherited'])) {
  672.                         continue;
  673.                     }
  674.                     if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) {
  675.                         $targetClass $this->em->getClassMetadata($assoc['targetEntity']);
  676.                         foreach ($assoc['joinColumns'] as $joinColumn) {
  677.                             $columnName  $joinColumn['name'];
  678.                             $columnAlias $this->getSQLColumnAlias($columnName);
  679.                             $columnType  PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass$this->em);
  680.                             $quotedColumnName       $this->quoteStrategy->getJoinColumnName($joinColumn$subClass$this->platform);
  681.                             $sqlSelectExpressions[] = $sqlTableAlias '.' $quotedColumnName ' AS ' $columnAlias;
  682.                             $this->rsm->addMetaResult($dqlAlias$columnAlias$columnName$subClass->isIdentifier($columnName), $columnType);
  683.                         }
  684.                     }
  685.                 }
  686.             }
  687.         }
  688.         return $sql implode(', '$sqlSelectExpressions);
  689.     }
  690.     /**
  691.      * {@inheritdoc}
  692.      */
  693.     public function walkFromClause($fromClause)
  694.     {
  695.         $identificationVarDecls $fromClause->identificationVariableDeclarations;
  696.         $sqlParts               = [];
  697.         foreach ($identificationVarDecls as $identificationVariableDecl) {
  698.             $sqlParts[] = $this->walkIdentificationVariableDeclaration($identificationVariableDecl);
  699.         }
  700.         return ' FROM ' implode(', '$sqlParts);
  701.     }
  702.     /**
  703.      * Walks down a IdentificationVariableDeclaration AST node, thereby generating the appropriate SQL.
  704.      *
  705.      * @param AST\IdentificationVariableDeclaration $identificationVariableDecl
  706.      *
  707.      * @return string
  708.      */
  709.     public function walkIdentificationVariableDeclaration($identificationVariableDecl)
  710.     {
  711.         $sql $this->walkRangeVariableDeclaration($identificationVariableDecl->rangeVariableDeclaration);
  712.         if ($identificationVariableDecl->indexBy) {
  713.             $this->walkIndexBy($identificationVariableDecl->indexBy);
  714.         }
  715.         foreach ($identificationVariableDecl->joins as $join) {
  716.             $sql .= $this->walkJoin($join);
  717.         }
  718.         return $sql;
  719.     }
  720.     /**
  721.      * Walks down a IndexBy AST node.
  722.      *
  723.      * @param AST\IndexBy $indexBy
  724.      *
  725.      * @return void
  726.      */
  727.     public function walkIndexBy($indexBy)
  728.     {
  729.         $pathExpression $indexBy->singleValuedPathExpression;
  730.         $alias          $pathExpression->identificationVariable;
  731.         switch ($pathExpression->type) {
  732.             case AST\PathExpression::TYPE_STATE_FIELD:
  733.                 $field $pathExpression->field;
  734.                 break;
  735.             case AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION:
  736.                 // Just use the foreign key, i.e. u.group_id
  737.                 $fieldName $pathExpression->field;
  738.                 $class     $this->queryComponents[$alias]['metadata'];
  739.                 if (isset($class->associationMappings[$fieldName]['inherited'])) {
  740.                     $class $this->em->getClassMetadata($class->associationMappings[$fieldName]['inherited']);
  741.                 }
  742.                 $association $class->associationMappings[$fieldName];
  743.                 if (! $association['isOwningSide']) {
  744.                     throw QueryException::associationPathInverseSideNotSupported($pathExpression);
  745.                 }
  746.                 if (count($association['sourceToTargetKeyColumns']) > 1) {
  747.                     throw QueryException::associationPathCompositeKeyNotSupported();
  748.                 }
  749.                 $field reset($association['targetToSourceKeyColumns']);
  750.                 break;
  751.             default:
  752.                 throw QueryException::invalidPathExpression($pathExpression);
  753.         }
  754.         if (isset($this->scalarFields[$alias][$field])) {
  755.             $this->rsm->addIndexByScalar($this->scalarFields[$alias][$field]);
  756.             return;
  757.         }
  758.         $this->rsm->addIndexBy($alias$field);
  759.     }
  760.     /**
  761.      * Walks down a RangeVariableDeclaration AST node, thereby generating the appropriate SQL.
  762.      *
  763.      * @param AST\RangeVariableDeclaration $rangeVariableDeclaration
  764.      *
  765.      * @return string
  766.      */
  767.     public function walkRangeVariableDeclaration($rangeVariableDeclaration)
  768.     {
  769.         return $this->generateRangeVariableDeclarationSQL($rangeVariableDeclarationfalse);
  770.     }
  771.     /**
  772.      * Generate appropriate SQL for RangeVariableDeclaration AST node
  773.      */
  774.     private function generateRangeVariableDeclarationSQL(
  775.         AST\RangeVariableDeclaration $rangeVariableDeclaration,
  776.         bool $buildNestedJoins
  777.     ): string {
  778.         $class    $this->em->getClassMetadata($rangeVariableDeclaration->abstractSchemaName);
  779.         $dqlAlias $rangeVariableDeclaration->aliasIdentificationVariable;
  780.         if ($rangeVariableDeclaration->isRoot) {
  781.             $this->rootAliases[] = $dqlAlias;
  782.         }
  783.         $sql $this->platform->appendLockHint(
  784.             $this->quoteStrategy->getTableName($class$this->platform) . ' ' .
  785.             $this->getSQLTableAlias($class->getTableName(), $dqlAlias),
  786.             $this->query->getHint(Query::HINT_LOCK_MODE)
  787.         );
  788.         if (! $class->isInheritanceTypeJoined()) {
  789.             return $sql;
  790.         }
  791.         $classTableInheritanceJoins $this->generateClassTableInheritanceJoins($class$dqlAlias);
  792.         if (! $buildNestedJoins) {
  793.             return $sql $classTableInheritanceJoins;
  794.         }
  795.         return $classTableInheritanceJoins === '' $sql '(' $sql $classTableInheritanceJoins ')';
  796.     }
  797.     /**
  798.      * Walks down a JoinAssociationDeclaration AST node, thereby generating the appropriate SQL.
  799.      *
  800.      * @param AST\JoinAssociationDeclaration $joinAssociationDeclaration
  801.      * @param int                            $joinType
  802.      * @param AST\ConditionalExpression      $condExpr
  803.      *
  804.      * @return string
  805.      *
  806.      * @throws QueryException
  807.      */
  808.     public function walkJoinAssociationDeclaration($joinAssociationDeclaration$joinType AST\Join::JOIN_TYPE_INNER$condExpr null)
  809.     {
  810.         $sql '';
  811.         $associationPathExpression $joinAssociationDeclaration->joinAssociationPathExpression;
  812.         $joinedDqlAlias            $joinAssociationDeclaration->aliasIdentificationVariable;
  813.         $indexBy                   $joinAssociationDeclaration->indexBy;
  814.         $relation        $this->queryComponents[$joinedDqlAlias]['relation'];
  815.         $targetClass     $this->em->getClassMetadata($relation['targetEntity']);
  816.         $sourceClass     $this->em->getClassMetadata($relation['sourceEntity']);
  817.         $targetTableName $this->quoteStrategy->getTableName($targetClass$this->platform);
  818.         $targetTableAlias $this->getSQLTableAlias($targetClass->getTableName(), $joinedDqlAlias);
  819.         $sourceTableAlias $this->getSQLTableAlias($sourceClass->getTableName(), $associationPathExpression->identificationVariable);
  820.         // Ensure we got the owning side, since it has all mapping info
  821.         $assoc = ! $relation['isOwningSide'] ? $targetClass->associationMappings[$relation['mappedBy']] : $relation;
  822.         if ($this->query->getHint(Query::HINT_INTERNAL_ITERATION) === true && (! $this->query->getHint(self::HINT_DISTINCT) || isset($this->selectedClasses[$joinedDqlAlias]))) {
  823.             if ($relation['type'] === ClassMetadata::ONE_TO_MANY || $relation['type'] === ClassMetadata::MANY_TO_MANY) {
  824.                 throw QueryException::iterateWithFetchJoinNotAllowed($assoc);
  825.             }
  826.         }
  827.         $targetTableJoin null;
  828.         // This condition is not checking ClassMetadata::MANY_TO_ONE, because by definition it cannot
  829.         // be the owning side and previously we ensured that $assoc is always the owning side of the associations.
  830.         // The owning side is necessary at this point because only it contains the JoinColumn information.
  831.         switch (true) {
  832.             case $assoc['type'] & ClassMetadata::TO_ONE:
  833.                 $conditions = [];
  834.                 foreach ($assoc['joinColumns'] as $joinColumn) {
  835.                     $quotedSourceColumn $this->quoteStrategy->getJoinColumnName($joinColumn$targetClass$this->platform);
  836.                     $quotedTargetColumn $this->quoteStrategy->getReferencedJoinColumnName($joinColumn$targetClass$this->platform);
  837.                     if ($relation['isOwningSide']) {
  838.                         $conditions[] = $sourceTableAlias '.' $quotedSourceColumn ' = ' $targetTableAlias '.' $quotedTargetColumn;
  839.                         continue;
  840.                     }
  841.                     $conditions[] = $sourceTableAlias '.' $quotedTargetColumn ' = ' $targetTableAlias '.' $quotedSourceColumn;
  842.                 }
  843.                 // Apply remaining inheritance restrictions
  844.                 $discrSql $this->generateDiscriminatorColumnConditionSQL([$joinedDqlAlias]);
  845.                 if ($discrSql) {
  846.                     $conditions[] = $discrSql;
  847.                 }
  848.                 // Apply the filters
  849.                 $filterExpr $this->generateFilterConditionSQL($targetClass$targetTableAlias);
  850.                 if ($filterExpr) {
  851.                     $conditions[] = $filterExpr;
  852.                 }
  853.                 $targetTableJoin = [
  854.                     'table' => $targetTableName ' ' $targetTableAlias,
  855.                     'condition' => implode(' AND '$conditions),
  856.                 ];
  857.                 break;
  858.             case $assoc['type'] === ClassMetadata::MANY_TO_MANY:
  859.                 // Join relation table
  860.                 $joinTable      $assoc['joinTable'];
  861.                 $joinTableAlias $this->getSQLTableAlias($joinTable['name'], $joinedDqlAlias);
  862.                 $joinTableName  $this->quoteStrategy->getJoinTableName($assoc$sourceClass$this->platform);
  863.                 $conditions      = [];
  864.                 $relationColumns $relation['isOwningSide']
  865.                     ? $assoc['joinTable']['joinColumns']
  866.                     : $assoc['joinTable']['inverseJoinColumns'];
  867.                 foreach ($relationColumns as $joinColumn) {
  868.                     $quotedSourceColumn $this->quoteStrategy->getJoinColumnName($joinColumn$targetClass$this->platform);
  869.                     $quotedTargetColumn $this->quoteStrategy->getReferencedJoinColumnName($joinColumn$targetClass$this->platform);
  870.                     $conditions[] = $sourceTableAlias '.' $quotedTargetColumn ' = ' $joinTableAlias '.' $quotedSourceColumn;
  871.                 }
  872.                 $sql .= $joinTableName ' ' $joinTableAlias ' ON ' implode(' AND '$conditions);
  873.                 // Join target table
  874.                 $sql .= $joinType === AST\Join::JOIN_TYPE_LEFT || $joinType === AST\Join::JOIN_TYPE_LEFTOUTER ' LEFT JOIN ' ' INNER JOIN ';
  875.                 $conditions      = [];
  876.                 $relationColumns $relation['isOwningSide']
  877.                     ? $assoc['joinTable']['inverseJoinColumns']
  878.                     : $assoc['joinTable']['joinColumns'];
  879.                 foreach ($relationColumns as $joinColumn) {
  880.                     $quotedSourceColumn $this->quoteStrategy->getJoinColumnName($joinColumn$targetClass$this->platform);
  881.                     $quotedTargetColumn $this->quoteStrategy->getReferencedJoinColumnName($joinColumn$targetClass$this->platform);
  882.                     $conditions[] = $targetTableAlias '.' $quotedTargetColumn ' = ' $joinTableAlias '.' $quotedSourceColumn;
  883.                 }
  884.                 // Apply remaining inheritance restrictions
  885.                 $discrSql $this->generateDiscriminatorColumnConditionSQL([$joinedDqlAlias]);
  886.                 if ($discrSql) {
  887.                     $conditions[] = $discrSql;
  888.                 }
  889.                 // Apply the filters
  890.                 $filterExpr $this->generateFilterConditionSQL($targetClass$targetTableAlias);
  891.                 if ($filterExpr) {
  892.                     $conditions[] = $filterExpr;
  893.                 }
  894.                 $targetTableJoin = [
  895.                     'table' => $targetTableName ' ' $targetTableAlias,
  896.                     'condition' => implode(' AND '$conditions),
  897.                 ];
  898.                 break;
  899.             default:
  900.                 throw new BadMethodCallException('Type of association must be one of *_TO_ONE or MANY_TO_MANY');
  901.         }
  902.         // Handle WITH clause
  903.         $withCondition $condExpr === null '' : ('(' $this->walkConditionalExpression($condExpr) . ')');
  904.         if ($targetClass->isInheritanceTypeJoined()) {
  905.             $ctiJoins $this->generateClassTableInheritanceJoins($targetClass$joinedDqlAlias);
  906.             // If we have WITH condition, we need to build nested joins for target class table and cti joins
  907.             if ($withCondition) {
  908.                 $sql .= '(' $targetTableJoin['table'] . $ctiJoins ') ON ' $targetTableJoin['condition'];
  909.             } else {
  910.                 $sql .= $targetTableJoin['table'] . ' ON ' $targetTableJoin['condition'] . $ctiJoins;
  911.             }
  912.         } else {
  913.             $sql .= $targetTableJoin['table'] . ' ON ' $targetTableJoin['condition'];
  914.         }
  915.         if ($withCondition) {
  916.             $sql .= ' AND ' $withCondition;
  917.         }
  918.         // Apply the indexes
  919.         if ($indexBy) {
  920.             // For Many-To-One or One-To-One associations this obviously makes no sense, but is ignored silently.
  921.             $this->walkIndexBy($indexBy);
  922.         } elseif (isset($relation['indexBy'])) {
  923.             $this->rsm->addIndexBy($joinedDqlAlias$relation['indexBy']);
  924.         }
  925.         return $sql;
  926.     }
  927.     /**
  928.      * {@inheritdoc}
  929.      */
  930.     public function walkFunction($function)
  931.     {
  932.         return $function->getSql($this);
  933.     }
  934.     /**
  935.      * {@inheritdoc}
  936.      */
  937.     public function walkOrderByClause($orderByClause)
  938.     {
  939.         $orderByItems array_map([$this'walkOrderByItem'], $orderByClause->orderByItems);
  940.         $collectionOrderByItems $this->generateOrderedCollectionOrderByItems();
  941.         if ($collectionOrderByItems !== '') {
  942.             $orderByItems array_merge($orderByItems, (array) $collectionOrderByItems);
  943.         }
  944.         return ' ORDER BY ' implode(', '$orderByItems);
  945.     }
  946.     /**
  947.      * {@inheritdoc}
  948.      */
  949.     public function walkOrderByItem($orderByItem)
  950.     {
  951.         $type strtoupper($orderByItem->type);
  952.         $expr $orderByItem->expression;
  953.         $sql  $expr instanceof AST\Node
  954.             $expr->dispatch($this)
  955.             : $this->walkResultVariable($this->queryComponents[$expr]['token']['value']);
  956.         $this->orderedColumnsMap[$sql] = $type;
  957.         if ($expr instanceof AST\Subselect) {
  958.             return '(' $sql ') ' $type;
  959.         }
  960.         return $sql ' ' $type;
  961.     }
  962.     /**
  963.      * {@inheritdoc}
  964.      */
  965.     public function walkHavingClause($havingClause)
  966.     {
  967.         return ' HAVING ' $this->walkConditionalExpression($havingClause->conditionalExpression);
  968.     }
  969.     /**
  970.      * {@inheritdoc}
  971.      */
  972.     public function walkJoin($join)
  973.     {
  974.         $joinType        $join->joinType;
  975.         $joinDeclaration $join->joinAssociationDeclaration;
  976.         $sql $joinType === AST\Join::JOIN_TYPE_LEFT || $joinType === AST\Join::JOIN_TYPE_LEFTOUTER
  977.             ' LEFT JOIN '
  978.             ' INNER JOIN ';
  979.         switch (true) {
  980.             case $joinDeclaration instanceof AST\RangeVariableDeclaration:
  981.                 $class      $this->em->getClassMetadata($joinDeclaration->abstractSchemaName);
  982.                 $dqlAlias   $joinDeclaration->aliasIdentificationVariable;
  983.                 $tableAlias $this->getSQLTableAlias($class->table['name'], $dqlAlias);
  984.                 $conditions = [];
  985.                 if ($join->conditionalExpression) {
  986.                     $conditions[] = '(' $this->walkConditionalExpression($join->conditionalExpression) . ')';
  987.                 }
  988.                 $isUnconditionalJoin $conditions === [];
  989.                 $condExprConjunction $class->isInheritanceTypeJoined() && $joinType !== AST\Join::JOIN_TYPE_LEFT && $joinType !== AST\Join::JOIN_TYPE_LEFTOUTER && $isUnconditionalJoin
  990.                     ' AND '
  991.                     ' ON ';
  992.                 $sql .= $this->generateRangeVariableDeclarationSQL($joinDeclaration, ! $isUnconditionalJoin);
  993.                 // Apply remaining inheritance restrictions
  994.                 $discrSql $this->generateDiscriminatorColumnConditionSQL([$dqlAlias]);
  995.                 if ($discrSql) {
  996.                     $conditions[] = $discrSql;
  997.                 }
  998.                 // Apply the filters
  999.                 $filterExpr $this->generateFilterConditionSQL($class$tableAlias);
  1000.                 if ($filterExpr) {
  1001.                     $conditions[] = $filterExpr;
  1002.                 }
  1003.                 if ($conditions) {
  1004.                     $sql .= $condExprConjunction implode(' AND '$conditions);
  1005.                 }
  1006.                 break;
  1007.             case $joinDeclaration instanceof AST\JoinAssociationDeclaration:
  1008.                 $sql .= $this->walkJoinAssociationDeclaration($joinDeclaration$joinType$join->conditionalExpression);
  1009.                 break;
  1010.         }
  1011.         return $sql;
  1012.     }
  1013.     /**
  1014.      * Walks down a CoalesceExpression AST node and generates the corresponding SQL.
  1015.      *
  1016.      * @param AST\CoalesceExpression $coalesceExpression
  1017.      *
  1018.      * @return string The SQL.
  1019.      */
  1020.     public function walkCoalesceExpression($coalesceExpression)
  1021.     {
  1022.         $sql 'COALESCE(';
  1023.         $scalarExpressions = [];
  1024.         foreach ($coalesceExpression->scalarExpressions as $scalarExpression) {
  1025.             $scalarExpressions[] = $this->walkSimpleArithmeticExpression($scalarExpression);
  1026.         }
  1027.         return $sql implode(', '$scalarExpressions) . ')';
  1028.     }
  1029.     /**
  1030.      * Walks down a NullIfExpression AST node and generates the corresponding SQL.
  1031.      *
  1032.      * @param AST\NullIfExpression $nullIfExpression
  1033.      *
  1034.      * @return string The SQL.
  1035.      */
  1036.     public function walkNullIfExpression($nullIfExpression)
  1037.     {
  1038.         $firstExpression is_string($nullIfExpression->firstExpression)
  1039.             ? $this->conn->quote($nullIfExpression->firstExpression)
  1040.             : $this->walkSimpleArithmeticExpression($nullIfExpression->firstExpression);
  1041.         $secondExpression is_string($nullIfExpression->secondExpression)
  1042.             ? $this->conn->quote($nullIfExpression->secondExpression)
  1043.             : $this->walkSimpleArithmeticExpression($nullIfExpression->secondExpression);
  1044.         return 'NULLIF(' $firstExpression ', ' $secondExpression ')';
  1045.     }
  1046.     /**
  1047.      * Walks down a GeneralCaseExpression AST node and generates the corresponding SQL.
  1048.      *
  1049.      * @return string The SQL.
  1050.      */
  1051.     public function walkGeneralCaseExpression(AST\GeneralCaseExpression $generalCaseExpression)
  1052.     {
  1053.         $sql 'CASE';
  1054.         foreach ($generalCaseExpression->whenClauses as $whenClause) {
  1055.             $sql .= ' WHEN ' $this->walkConditionalExpression($whenClause->caseConditionExpression);
  1056.             $sql .= ' THEN ' $this->walkSimpleArithmeticExpression($whenClause->thenScalarExpression);
  1057.         }
  1058.         $sql .= ' ELSE ' $this->walkSimpleArithmeticExpression($generalCaseExpression->elseScalarExpression) . ' END';
  1059.         return $sql;
  1060.     }
  1061.     /**
  1062.      * Walks down a SimpleCaseExpression AST node and generates the corresponding SQL.
  1063.      *
  1064.      * @param AST\SimpleCaseExpression $simpleCaseExpression
  1065.      *
  1066.      * @return string The SQL.
  1067.      */
  1068.     public function walkSimpleCaseExpression($simpleCaseExpression)
  1069.     {
  1070.         $sql 'CASE ' $this->walkStateFieldPathExpression($simpleCaseExpression->caseOperand);
  1071.         foreach ($simpleCaseExpression->simpleWhenClauses as $simpleWhenClause) {
  1072.             $sql .= ' WHEN ' $this->walkSimpleArithmeticExpression($simpleWhenClause->caseScalarExpression);
  1073.             $sql .= ' THEN ' $this->walkSimpleArithmeticExpression($simpleWhenClause->thenScalarExpression);
  1074.         }
  1075.         $sql .= ' ELSE ' $this->walkSimpleArithmeticExpression($simpleCaseExpression->elseScalarExpression) . ' END';
  1076.         return $sql;
  1077.     }
  1078.     /**
  1079.      * {@inheritdoc}
  1080.      */
  1081.     public function walkSelectExpression($selectExpression)
  1082.     {
  1083.         $sql    '';
  1084.         $expr   $selectExpression->expression;
  1085.         $hidden $selectExpression->hiddenAliasResultVariable;
  1086.         switch (true) {
  1087.             case $expr instanceof AST\PathExpression:
  1088.                 if ($expr->type !== AST\PathExpression::TYPE_STATE_FIELD) {
  1089.                     throw QueryException::invalidPathExpression($expr);
  1090.                 }
  1091.                 $fieldName $expr->field;
  1092.                 $dqlAlias  $expr->identificationVariable;
  1093.                 $qComp     $this->queryComponents[$dqlAlias];
  1094.                 $class     $qComp['metadata'];
  1095.                 $resultAlias $selectExpression->fieldIdentificationVariable ?: $fieldName;
  1096.                 $tableName   $class->isInheritanceTypeJoined()
  1097.                     ? $this->em->getUnitOfWork()->getEntityPersister($class->name)->getOwningTable($fieldName)
  1098.                     : $class->getTableName();
  1099.                 $sqlTableAlias $this->getSQLTableAlias($tableName$dqlAlias);
  1100.                 $fieldMapping  $class->fieldMappings[$fieldName];
  1101.                 $columnName    $this->quoteStrategy->getColumnName($fieldName$class$this->platform);
  1102.                 $columnAlias   $this->getSQLColumnAlias($fieldMapping['columnName']);
  1103.                 $col           $sqlTableAlias '.' $columnName;
  1104.                 if (isset($fieldMapping['requireSQLConversion'])) {
  1105.                     $type Type::getType($fieldMapping['type']);
  1106.                     $col  $type->convertToPHPValueSQL($col$this->conn->getDatabasePlatform());
  1107.                 }
  1108.                 $sql .= $col ' AS ' $columnAlias;
  1109.                 $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
  1110.                 if (! $hidden) {
  1111.                     $this->rsm->addScalarResult($columnAlias$resultAlias$fieldMapping['type']);
  1112.                     $this->scalarFields[$dqlAlias][$fieldName] = $columnAlias;
  1113.                 }
  1114.                 break;
  1115.             case $expr instanceof AST\AggregateExpression:
  1116.             case $expr instanceof AST\Functions\FunctionNode:
  1117.             case $expr instanceof AST\SimpleArithmeticExpression:
  1118.             case $expr instanceof AST\ArithmeticTerm:
  1119.             case $expr instanceof AST\ArithmeticFactor:
  1120.             case $expr instanceof AST\ParenthesisExpression:
  1121.             case $expr instanceof AST\Literal:
  1122.             case $expr instanceof AST\NullIfExpression:
  1123.             case $expr instanceof AST\CoalesceExpression:
  1124.             case $expr instanceof AST\GeneralCaseExpression:
  1125.             case $expr instanceof AST\SimpleCaseExpression:
  1126.                 $columnAlias $this->getSQLColumnAlias('sclr');
  1127.                 $resultAlias $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
  1128.                 $sql .= $expr->dispatch($this) . ' AS ' $columnAlias;
  1129.                 $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
  1130.                 if ($hidden) {
  1131.                     break;
  1132.                 }
  1133.                 if (! $expr instanceof Query\AST\TypedExpression) {
  1134.                     // Conceptually we could resolve field type here by traverse through AST to retrieve field type,
  1135.                     // but this is not a feasible solution; assume 'string'.
  1136.                     $this->rsm->addScalarResult($columnAlias$resultAlias'string');
  1137.                     break;
  1138.                 }
  1139.                 $this->rsm->addScalarResult($columnAlias$resultAlias$expr->getReturnType()->getName());
  1140.                 break;
  1141.             case $expr instanceof AST\Subselect:
  1142.                 $columnAlias $this->getSQLColumnAlias('sclr');
  1143.                 $resultAlias $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
  1144.                 $sql .= '(' $this->walkSubselect($expr) . ') AS ' $columnAlias;
  1145.                 $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
  1146.                 if (! $hidden) {
  1147.                     // We cannot resolve field type here; assume 'string'.
  1148.                     $this->rsm->addScalarResult($columnAlias$resultAlias'string');
  1149.                 }
  1150.                 break;
  1151.             case $expr instanceof AST\NewObjectExpression:
  1152.                 $sql .= $this->walkNewObject($expr$selectExpression->fieldIdentificationVariable);
  1153.                 break;
  1154.             default:
  1155.                 // IdentificationVariable or PartialObjectExpression
  1156.                 if ($expr instanceof AST\PartialObjectExpression) {
  1157.                     $this->query->setHint(self::HINT_PARTIALtrue);
  1158.                     $dqlAlias        $expr->identificationVariable;
  1159.                     $partialFieldSet $expr->partialFieldSet;
  1160.                 } else {
  1161.                     $dqlAlias        $expr;
  1162.                     $partialFieldSet = [];
  1163.                 }
  1164.                 $queryComp   $this->queryComponents[$dqlAlias];
  1165.                 $class       $queryComp['metadata'];
  1166.                 $resultAlias $selectExpression->fieldIdentificationVariable ?: null;
  1167.                 if (! isset($this->selectedClasses[$dqlAlias])) {
  1168.                     $this->selectedClasses[$dqlAlias] = [
  1169.                         'class'       => $class,
  1170.                         'dqlAlias'    => $dqlAlias,
  1171.                         'resultAlias' => $resultAlias,
  1172.                     ];
  1173.                 }
  1174.                 $sqlParts = [];
  1175.                 // Select all fields from the queried class
  1176.                 foreach ($class->fieldMappings as $fieldName => $mapping) {
  1177.                     if ($partialFieldSet && ! in_array($fieldName$partialFieldSet)) {
  1178.                         continue;
  1179.                     }
  1180.                     $tableName = isset($mapping['inherited'])
  1181.                         ? $this->em->getClassMetadata($mapping['inherited'])->getTableName()
  1182.                         : $class->getTableName();
  1183.                     $sqlTableAlias    $this->getSQLTableAlias($tableName$dqlAlias);
  1184.                     $columnAlias      $this->getSQLColumnAlias($mapping['columnName']);
  1185.                     $quotedColumnName $this->quoteStrategy->getColumnName($fieldName$class$this->platform);
  1186.                     $col $sqlTableAlias '.' $quotedColumnName;
  1187.                     if (isset($mapping['requireSQLConversion'])) {
  1188.                         $type Type::getType($mapping['type']);
  1189.                         $col  $type->convertToPHPValueSQL($col$this->platform);
  1190.                     }
  1191.                     $sqlParts[] = $col ' AS ' $columnAlias;
  1192.                     $this->scalarResultAliasMap[$resultAlias][] = $columnAlias;
  1193.                     $this->rsm->addFieldResult($dqlAlias$columnAlias$fieldName$class->name);
  1194.                 }
  1195.                 // Add any additional fields of subclasses (excluding inherited fields)
  1196.                 // 1) on Single Table Inheritance: always, since its marginal overhead
  1197.                 // 2) on Class Table Inheritance only if partial objects are disallowed,
  1198.                 //    since it requires outer joining subtables.
  1199.                 if ($class->isInheritanceTypeSingleTable() || ! $this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD)) {
  1200.                     foreach ($class->subClasses as $subClassName) {
  1201.                         $subClass      $this->em->getClassMetadata($subClassName);
  1202.                         $sqlTableAlias $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias);
  1203.                         foreach ($subClass->fieldMappings as $fieldName => $mapping) {
  1204.                             if (isset($mapping['inherited']) || ($partialFieldSet && ! in_array($fieldName$partialFieldSet))) {
  1205.                                 continue;
  1206.                             }
  1207.                             $columnAlias      $this->getSQLColumnAlias($mapping['columnName']);
  1208.                             $quotedColumnName $this->quoteStrategy->getColumnName($fieldName$subClass$this->platform);
  1209.                             $col $sqlTableAlias '.' $quotedColumnName;
  1210.                             if (isset($mapping['requireSQLConversion'])) {
  1211.                                 $type Type::getType($mapping['type']);
  1212.                                 $col  $type->convertToPHPValueSQL($col$this->platform);
  1213.                             }
  1214.                             $sqlParts[] = $col ' AS ' $columnAlias;
  1215.                             $this->scalarResultAliasMap[$resultAlias][] = $columnAlias;
  1216.                             $this->rsm->addFieldResult($dqlAlias$columnAlias$fieldName$subClassName);
  1217.                         }
  1218.                     }
  1219.                 }
  1220.                 $sql .= implode(', '$sqlParts);
  1221.         }
  1222.         return $sql;
  1223.     }
  1224.     /**
  1225.      * {@inheritdoc}
  1226.      */
  1227.     public function walkQuantifiedExpression($qExpr)
  1228.     {
  1229.         return ' ' strtoupper($qExpr->type) . '(' $this->walkSubselect($qExpr->subselect) . ')';
  1230.     }
  1231.     /**
  1232.      * {@inheritdoc}
  1233.      */
  1234.     public function walkSubselect($subselect)
  1235.     {
  1236.         $useAliasesBefore  $this->useSqlTableAliases;
  1237.         $rootAliasesBefore $this->rootAliases;
  1238.         $this->rootAliases        = []; // reset the rootAliases for the subselect
  1239.         $this->useSqlTableAliases true;
  1240.         $sql  $this->walkSimpleSelectClause($subselect->simpleSelectClause);
  1241.         $sql .= $this->walkSubselectFromClause($subselect->subselectFromClause);
  1242.         $sql .= $this->walkWhereClause($subselect->whereClause);
  1243.         $sql .= $subselect->groupByClause $this->walkGroupByClause($subselect->groupByClause) : '';
  1244.         $sql .= $subselect->havingClause $this->walkHavingClause($subselect->havingClause) : '';
  1245.         $sql .= $subselect->orderByClause $this->walkOrderByClause($subselect->orderByClause) : '';
  1246.         $this->rootAliases        $rootAliasesBefore// put the main aliases back
  1247.         $this->useSqlTableAliases $useAliasesBefore;
  1248.         return $sql;
  1249.     }
  1250.     /**
  1251.      * {@inheritdoc}
  1252.      */
  1253.     public function walkSubselectFromClause($subselectFromClause)
  1254.     {
  1255.         $identificationVarDecls $subselectFromClause->identificationVariableDeclarations;
  1256.         $sqlParts               = [];
  1257.         foreach ($identificationVarDecls as $subselectIdVarDecl) {
  1258.             $sqlParts[] = $this->walkIdentificationVariableDeclaration($subselectIdVarDecl);
  1259.         }
  1260.         return ' FROM ' implode(', '$sqlParts);
  1261.     }
  1262.     /**
  1263.      * {@inheritdoc}
  1264.      */
  1265.     public function walkSimpleSelectClause($simpleSelectClause)
  1266.     {
  1267.         return 'SELECT' . ($simpleSelectClause->isDistinct ' DISTINCT' '')
  1268.             . $this->walkSimpleSelectExpression($simpleSelectClause->simpleSelectExpression);
  1269.     }
  1270.     /**
  1271.      * @return string
  1272.      */
  1273.     public function walkParenthesisExpression(AST\ParenthesisExpression $parenthesisExpression)
  1274.     {
  1275.         return sprintf('(%s)'$parenthesisExpression->expression->dispatch($this));
  1276.     }
  1277.     /**
  1278.      * @param AST\NewObjectExpression $newObjectExpression
  1279.      * @param string|null             $newObjectResultAlias
  1280.      *
  1281.      * @return string The SQL.
  1282.      */
  1283.     public function walkNewObject($newObjectExpression$newObjectResultAlias null)
  1284.     {
  1285.         $sqlSelectExpressions = [];
  1286.         $objIndex             $newObjectResultAlias ?: $this->newObjectCounter++;
  1287.         foreach ($newObjectExpression->args as $argIndex => $e) {
  1288.             $resultAlias $this->scalarResultCounter++;
  1289.             $columnAlias $this->getSQLColumnAlias('sclr');
  1290.             $fieldType   'string';
  1291.             switch (true) {
  1292.                 case $e instanceof AST\NewObjectExpression:
  1293.                     $sqlSelectExpressions[] = $e->dispatch($this);
  1294.                     break;
  1295.                 case $e instanceof AST\Subselect:
  1296.                     $sqlSelectExpressions[] = '(' $e->dispatch($this) . ') AS ' $columnAlias;
  1297.                     break;
  1298.                 case $e instanceof AST\PathExpression:
  1299.                     $dqlAlias     $e->identificationVariable;
  1300.                     $qComp        $this->queryComponents[$dqlAlias];
  1301.                     $class        $qComp['metadata'];
  1302.                     $fieldType    $class->fieldMappings[$e->field]['type'];
  1303.                     $fieldName    $e->field;
  1304.                     $fieldMapping $class->fieldMappings[$fieldName];
  1305.                     $col          trim($e->dispatch($this));
  1306.                     if (isset($fieldMapping['requireSQLConversion'])) {
  1307.                         $type Type::getType($fieldType);
  1308.                         $col  $type->convertToPHPValueSQL($col$this->platform);
  1309.                     }
  1310.                     $sqlSelectExpressions[] = $col ' AS ' $columnAlias;
  1311.                     break;
  1312.                 case $e instanceof AST\Literal:
  1313.                     switch ($e->type) {
  1314.                         case AST\Literal::BOOLEAN:
  1315.                             $fieldType 'boolean';
  1316.                             break;
  1317.                         case AST\Literal::NUMERIC:
  1318.                             $fieldType is_float($e->value) ? 'float' 'integer';
  1319.                             break;
  1320.                     }
  1321.                     $sqlSelectExpressions[] = trim($e->dispatch($this)) . ' AS ' $columnAlias;
  1322.                     break;
  1323.                 default:
  1324.                     $sqlSelectExpressions[] = trim($e->dispatch($this)) . ' AS ' $columnAlias;
  1325.                     break;
  1326.             }
  1327.             $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
  1328.             $this->rsm->addScalarResult($columnAlias$resultAlias$fieldType);
  1329.             $this->rsm->newObjectMappings[$columnAlias] = [
  1330.                 'className' => $newObjectExpression->className,
  1331.                 'objIndex'  => $objIndex,
  1332.                 'argIndex'  => $argIndex,
  1333.             ];
  1334.         }
  1335.         return implode(', '$sqlSelectExpressions);
  1336.     }
  1337.     /**
  1338.      * {@inheritdoc}
  1339.      */
  1340.     public function walkSimpleSelectExpression($simpleSelectExpression)
  1341.     {
  1342.         $expr $simpleSelectExpression->expression;
  1343.         $sql  ' ';
  1344.         switch (true) {
  1345.             case $expr instanceof AST\PathExpression:
  1346.                 $sql .= $this->walkPathExpression($expr);
  1347.                 break;
  1348.             case $expr instanceof AST\Subselect:
  1349.                 $alias $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
  1350.                 $columnAlias                        'sclr' $this->aliasCounter++;
  1351.                 $this->scalarResultAliasMap[$alias] = $columnAlias;
  1352.                 $sql .= '(' $this->walkSubselect($expr) . ') AS ' $columnAlias;
  1353.                 break;
  1354.             case $expr instanceof AST\Functions\FunctionNode:
  1355.             case $expr instanceof AST\SimpleArithmeticExpression:
  1356.             case $expr instanceof AST\ArithmeticTerm:
  1357.             case $expr instanceof AST\ArithmeticFactor:
  1358.             case $expr instanceof AST\Literal:
  1359.             case $expr instanceof AST\NullIfExpression:
  1360.             case $expr instanceof AST\CoalesceExpression:
  1361.             case $expr instanceof AST\GeneralCaseExpression:
  1362.             case $expr instanceof AST\SimpleCaseExpression:
  1363.                 $alias $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
  1364.                 $columnAlias                        $this->getSQLColumnAlias('sclr');
  1365.                 $this->scalarResultAliasMap[$alias] = $columnAlias;
  1366.                 $sql .= $expr->dispatch($this) . ' AS ' $columnAlias;
  1367.                 break;
  1368.             case $expr instanceof AST\ParenthesisExpression:
  1369.                 $sql .= $this->walkParenthesisExpression($expr);
  1370.                 break;
  1371.             default: // IdentificationVariable
  1372.                 $sql .= $this->walkEntityIdentificationVariable($expr);
  1373.                 break;
  1374.         }
  1375.         return $sql;
  1376.     }
  1377.     /**
  1378.      * {@inheritdoc}
  1379.      */
  1380.     public function walkAggregateExpression($aggExpression)
  1381.     {
  1382.         return $aggExpression->functionName '(' . ($aggExpression->isDistinct 'DISTINCT ' '')
  1383.             . $this->walkSimpleArithmeticExpression($aggExpression->pathExpression) . ')';
  1384.     }
  1385.     /**
  1386.      * {@inheritdoc}
  1387.      */
  1388.     public function walkGroupByClause($groupByClause)
  1389.     {
  1390.         $sqlParts = [];
  1391.         foreach ($groupByClause->groupByItems as $groupByItem) {
  1392.             $sqlParts[] = $this->walkGroupByItem($groupByItem);
  1393.         }
  1394.         return ' GROUP BY ' implode(', '$sqlParts);
  1395.     }
  1396.     /**
  1397.      * {@inheritdoc}
  1398.      */
  1399.     public function walkGroupByItem($groupByItem)
  1400.     {
  1401.         // StateFieldPathExpression
  1402.         if (! is_string($groupByItem)) {
  1403.             return $this->walkPathExpression($groupByItem);
  1404.         }
  1405.         // ResultVariable
  1406.         if (isset($this->queryComponents[$groupByItem]['resultVariable'])) {
  1407.             $resultVariable $this->queryComponents[$groupByItem]['resultVariable'];
  1408.             if ($resultVariable instanceof AST\PathExpression) {
  1409.                 return $this->walkPathExpression($resultVariable);
  1410.             }
  1411.             if (isset($resultVariable->pathExpression)) {
  1412.                 return $this->walkPathExpression($resultVariable->pathExpression);
  1413.             }
  1414.             return $this->walkResultVariable($groupByItem);
  1415.         }
  1416.         // IdentificationVariable
  1417.         $sqlParts = [];
  1418.         foreach ($this->queryComponents[$groupByItem]['metadata']->fieldNames as $field) {
  1419.             $item       = new AST\PathExpression(AST\PathExpression::TYPE_STATE_FIELD$groupByItem$field);
  1420.             $item->type AST\PathExpression::TYPE_STATE_FIELD;
  1421.             $sqlParts[] = $this->walkPathExpression($item);
  1422.         }
  1423.         foreach ($this->queryComponents[$groupByItem]['metadata']->associationMappings as $mapping) {
  1424.             if ($mapping['isOwningSide'] && $mapping['type'] & ClassMetadataInfo::TO_ONE) {
  1425.                 $item       = new AST\PathExpression(AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION$groupByItem$mapping['fieldName']);
  1426.                 $item->type AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION;
  1427.                 $sqlParts[] = $this->walkPathExpression($item);
  1428.             }
  1429.         }
  1430.         return implode(', '$sqlParts);
  1431.     }
  1432.     /**
  1433.      * {@inheritdoc}
  1434.      */
  1435.     public function walkDeleteClause(AST\DeleteClause $deleteClause)
  1436.     {
  1437.         $class     $this->em->getClassMetadata($deleteClause->abstractSchemaName);
  1438.         $tableName $class->getTableName();
  1439.         $sql       'DELETE FROM ' $this->quoteStrategy->getTableName($class$this->platform);
  1440.         $this->setSQLTableAlias($tableName$tableName$deleteClause->aliasIdentificationVariable);
  1441.         $this->rootAliases[] = $deleteClause->aliasIdentificationVariable;
  1442.         return $sql;
  1443.     }
  1444.     /**
  1445.      * {@inheritdoc}
  1446.      */
  1447.     public function walkUpdateClause($updateClause)
  1448.     {
  1449.         $class     $this->em->getClassMetadata($updateClause->abstractSchemaName);
  1450.         $tableName $class->getTableName();
  1451.         $sql       'UPDATE ' $this->quoteStrategy->getTableName($class$this->platform);
  1452.         $this->setSQLTableAlias($tableName$tableName$updateClause->aliasIdentificationVariable);
  1453.         $this->rootAliases[] = $updateClause->aliasIdentificationVariable;
  1454.         return $sql ' SET ' implode(', 'array_map([$this'walkUpdateItem'], $updateClause->updateItems));
  1455.     }
  1456.     /**
  1457.      * {@inheritdoc}
  1458.      */
  1459.     public function walkUpdateItem($updateItem)
  1460.     {
  1461.         $useTableAliasesBefore    $this->useSqlTableAliases;
  1462.         $this->useSqlTableAliases false;
  1463.         $sql      $this->walkPathExpression($updateItem->pathExpression) . ' = ';
  1464.         $newValue $updateItem->newValue;
  1465.         switch (true) {
  1466.             case $newValue instanceof AST\Node:
  1467.                 $sql .= $newValue->dispatch($this);
  1468.                 break;
  1469.             case $newValue === null:
  1470.                 $sql .= 'NULL';
  1471.                 break;
  1472.             default:
  1473.                 $sql .= $this->conn->quote($newValue);
  1474.                 break;
  1475.         }
  1476.         $this->useSqlTableAliases $useTableAliasesBefore;
  1477.         return $sql;
  1478.     }
  1479.     /**
  1480.      * {@inheritdoc}
  1481.      */
  1482.     public function walkWhereClause($whereClause)
  1483.     {
  1484.         $condSql  $whereClause !== null $this->walkConditionalExpression($whereClause->conditionalExpression) : '';
  1485.         $discrSql $this->generateDiscriminatorColumnConditionSQL($this->rootAliases);
  1486.         if ($this->em->hasFilters()) {
  1487.             $filterClauses = [];
  1488.             foreach ($this->rootAliases as $dqlAlias) {
  1489.                 $class      $this->queryComponents[$dqlAlias]['metadata'];
  1490.                 $tableAlias $this->getSQLTableAlias($class->table['name'], $dqlAlias);
  1491.                 $filterExpr $this->generateFilterConditionSQL($class$tableAlias);
  1492.                 if ($filterExpr) {
  1493.                     $filterClauses[] = $filterExpr;
  1494.                 }
  1495.             }
  1496.             if (count($filterClauses)) {
  1497.                 if ($condSql) {
  1498.                     $condSql '(' $condSql ') AND ';
  1499.                 }
  1500.                 $condSql .= implode(' AND '$filterClauses);
  1501.             }
  1502.         }
  1503.         if ($condSql) {
  1504.             return ' WHERE ' . (! $discrSql $condSql '(' $condSql ') AND ' $discrSql);
  1505.         }
  1506.         if ($discrSql) {
  1507.             return ' WHERE ' $discrSql;
  1508.         }
  1509.         return '';
  1510.     }
  1511.     /**
  1512.      * {@inheritdoc}
  1513.      */
  1514.     public function walkConditionalExpression($condExpr)
  1515.     {
  1516.         // Phase 2 AST optimization: Skip processing of ConditionalExpression
  1517.         // if only one ConditionalTerm is defined
  1518.         if (! ($condExpr instanceof AST\ConditionalExpression)) {
  1519.             return $this->walkConditionalTerm($condExpr);
  1520.         }
  1521.         return implode(' OR 'array_map([$this'walkConditionalTerm'], $condExpr->conditionalTerms));
  1522.     }
  1523.     /**
  1524.      * {@inheritdoc}
  1525.      */
  1526.     public function walkConditionalTerm($condTerm)
  1527.     {
  1528.         // Phase 2 AST optimization: Skip processing of ConditionalTerm
  1529.         // if only one ConditionalFactor is defined
  1530.         if (! ($condTerm instanceof AST\ConditionalTerm)) {
  1531.             return $this->walkConditionalFactor($condTerm);
  1532.         }
  1533.         return implode(' AND 'array_map([$this'walkConditionalFactor'], $condTerm->conditionalFactors));
  1534.     }
  1535.     /**
  1536.      * {@inheritdoc}
  1537.      */
  1538.     public function walkConditionalFactor($factor)
  1539.     {
  1540.         // Phase 2 AST optimization: Skip processing of ConditionalFactor
  1541.         // if only one ConditionalPrimary is defined
  1542.         return ! ($factor instanceof AST\ConditionalFactor)
  1543.             ? $this->walkConditionalPrimary($factor)
  1544.             : ($factor->not 'NOT ' '') . $this->walkConditionalPrimary($factor->conditionalPrimary);
  1545.     }
  1546.     /**
  1547.      * {@inheritdoc}
  1548.      */
  1549.     public function walkConditionalPrimary($primary)
  1550.     {
  1551.         if ($primary->isSimpleConditionalExpression()) {
  1552.             return $primary->simpleConditionalExpression->dispatch($this);
  1553.         }
  1554.         if ($primary->isConditionalExpression()) {
  1555.             $condExpr $primary->conditionalExpression;
  1556.             return '(' $this->walkConditionalExpression($condExpr) . ')';
  1557.         }
  1558.     }
  1559.     /**
  1560.      * {@inheritdoc}
  1561.      */
  1562.     public function walkExistsExpression($existsExpr)
  1563.     {
  1564.         $sql $existsExpr->not 'NOT ' '';
  1565.         $sql .= 'EXISTS (' $this->walkSubselect($existsExpr->subselect) . ')';
  1566.         return $sql;
  1567.     }
  1568.     /**
  1569.      * {@inheritdoc}
  1570.      */
  1571.     public function walkCollectionMemberExpression($collMemberExpr)
  1572.     {
  1573.         $sql  $collMemberExpr->not 'NOT ' '';
  1574.         $sql .= 'EXISTS (SELECT 1 FROM ';
  1575.         $entityExpr   $collMemberExpr->entityExpression;
  1576.         $collPathExpr $collMemberExpr->collectionValuedPathExpression;
  1577.         $fieldName $collPathExpr->field;
  1578.         $dqlAlias  $collPathExpr->identificationVariable;
  1579.         $class $this->queryComponents[$dqlAlias]['metadata'];
  1580.         switch (true) {
  1581.             // InputParameter
  1582.             case $entityExpr instanceof AST\InputParameter:
  1583.                 $dqlParamKey $entityExpr->name;
  1584.                 $entitySql   '?';
  1585.                 break;
  1586.             // SingleValuedAssociationPathExpression | IdentificationVariable
  1587.             case $entityExpr instanceof AST\PathExpression:
  1588.                 $entitySql $this->walkPathExpression($entityExpr);
  1589.                 break;
  1590.             default:
  1591.                 throw new BadMethodCallException('Not implemented');
  1592.         }
  1593.         $assoc $class->associationMappings[$fieldName];
  1594.         if ($assoc['type'] === ClassMetadata::ONE_TO_MANY) {
  1595.             $targetClass      $this->em->getClassMetadata($assoc['targetEntity']);
  1596.             $targetTableAlias $this->getSQLTableAlias($targetClass->getTableName());
  1597.             $sourceTableAlias $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
  1598.             $sql .= $this->quoteStrategy->getTableName($targetClass$this->platform) . ' ' $targetTableAlias ' WHERE ';
  1599.             $owningAssoc $targetClass->associationMappings[$assoc['mappedBy']];
  1600.             $sqlParts    = [];
  1601.             foreach ($owningAssoc['targetToSourceKeyColumns'] as $targetColumn => $sourceColumn) {
  1602.                 $targetColumn $this->quoteStrategy->getColumnName($class->fieldNames[$targetColumn], $class$this->platform);
  1603.                 $sqlParts[] = $sourceTableAlias '.' $targetColumn ' = ' $targetTableAlias '.' $sourceColumn;
  1604.             }
  1605.             foreach ($this->quoteStrategy->getIdentifierColumnNames($targetClass$this->platform) as $targetColumnName) {
  1606.                 if (isset($dqlParamKey)) {
  1607.                     $this->parserResult->addParameterMapping($dqlParamKey$this->sqlParamIndex++);
  1608.                 }
  1609.                 $sqlParts[] = $targetTableAlias '.' $targetColumnName ' = ' $entitySql;
  1610.             }
  1611.             $sql .= implode(' AND '$sqlParts);
  1612.         } else { // many-to-many
  1613.             $targetClass $this->em->getClassMetadata($assoc['targetEntity']);
  1614.             $owningAssoc $assoc['isOwningSide'] ? $assoc $targetClass->associationMappings[$assoc['mappedBy']];
  1615.             $joinTable   $owningAssoc['joinTable'];
  1616.             // SQL table aliases
  1617.             $joinTableAlias   $this->getSQLTableAlias($joinTable['name']);
  1618.             $sourceTableAlias $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
  1619.             $sql .= $this->quoteStrategy->getJoinTableName($owningAssoc$targetClass$this->platform) . ' ' $joinTableAlias ' WHERE ';
  1620.             $joinColumns $assoc['isOwningSide'] ? $joinTable['joinColumns'] : $joinTable['inverseJoinColumns'];
  1621.             $sqlParts    = [];
  1622.             foreach ($joinColumns as $joinColumn) {
  1623.                 $targetColumn $this->quoteStrategy->getColumnName($class->fieldNames[$joinColumn['referencedColumnName']], $class$this->platform);
  1624.                 $sqlParts[] = $joinTableAlias '.' $joinColumn['name'] . ' = ' $sourceTableAlias '.' $targetColumn;
  1625.             }
  1626.             $joinColumns $assoc['isOwningSide'] ? $joinTable['inverseJoinColumns'] : $joinTable['joinColumns'];
  1627.             foreach ($joinColumns as $joinColumn) {
  1628.                 if (isset($dqlParamKey)) {
  1629.                     $this->parserResult->addParameterMapping($dqlParamKey$this->sqlParamIndex++);
  1630.                 }
  1631.                 $sqlParts[] = $joinTableAlias '.' $joinColumn['name'] . ' IN (' $entitySql ')';
  1632.             }
  1633.             $sql .= implode(' AND '$sqlParts);
  1634.         }
  1635.         return $sql ')';
  1636.     }
  1637.     /**
  1638.      * {@inheritdoc}
  1639.      */
  1640.     public function walkEmptyCollectionComparisonExpression($emptyCollCompExpr)
  1641.     {
  1642.         $sizeFunc                           = new AST\Functions\SizeFunction('size');
  1643.         $sizeFunc->collectionPathExpression $emptyCollCompExpr->expression;
  1644.         return $sizeFunc->getSql($this) . ($emptyCollCompExpr->not ' > 0' ' = 0');
  1645.     }
  1646.     /**
  1647.      * {@inheritdoc}
  1648.      */
  1649.     public function walkNullComparisonExpression($nullCompExpr)
  1650.     {
  1651.         $expression $nullCompExpr->expression;
  1652.         $comparison ' IS' . ($nullCompExpr->not ' NOT' '') . ' NULL';
  1653.         // Handle ResultVariable
  1654.         if (is_string($expression) && isset($this->queryComponents[$expression]['resultVariable'])) {
  1655.             return $this->walkResultVariable($expression) . $comparison;
  1656.         }
  1657.         // Handle InputParameter mapping inclusion to ParserResult
  1658.         if ($expression instanceof AST\InputParameter) {
  1659.             return $this->walkInputParameter($expression) . $comparison;
  1660.         }
  1661.         return $expression->dispatch($this) . $comparison;
  1662.     }
  1663.     /**
  1664.      * {@inheritdoc}
  1665.      */
  1666.     public function walkInExpression($inExpr)
  1667.     {
  1668.         $sql $this->walkArithmeticExpression($inExpr->expression) . ($inExpr->not ' NOT' '') . ' IN (';
  1669.         $sql .= $inExpr->subselect
  1670.             $this->walkSubselect($inExpr->subselect)
  1671.             : implode(', 'array_map([$this'walkInParameter'], $inExpr->literals));
  1672.         $sql .= ')';
  1673.         return $sql;
  1674.     }
  1675.     /**
  1676.      * {@inheritdoc}
  1677.      *
  1678.      * @throws QueryException
  1679.      */
  1680.     public function walkInstanceOfExpression($instanceOfExpr)
  1681.     {
  1682.         $sql '';
  1683.         $dqlAlias   $instanceOfExpr->identificationVariable;
  1684.         $discrClass $class $this->queryComponents[$dqlAlias]['metadata'];
  1685.         if ($class->discriminatorColumn) {
  1686.             $discrClass $this->em->getClassMetadata($class->rootEntityName);
  1687.         }
  1688.         if ($this->useSqlTableAliases) {
  1689.             $sql .= $this->getSQLTableAlias($discrClass->getTableName(), $dqlAlias) . '.';
  1690.         }
  1691.         $sql .= $class->discriminatorColumn['name'] . ($instanceOfExpr->not ' NOT IN ' ' IN ');
  1692.         $sql .= $this->getChildDiscriminatorsFromClassMetadata($discrClass$instanceOfExpr);
  1693.         return $sql;
  1694.     }
  1695.     /**
  1696.      * @param mixed $inParam
  1697.      *
  1698.      * @return string
  1699.      */
  1700.     public function walkInParameter($inParam)
  1701.     {
  1702.         return $inParam instanceof AST\InputParameter
  1703.             $this->walkInputParameter($inParam)
  1704.             : $this->walkLiteral($inParam);
  1705.     }
  1706.     /**
  1707.      * {@inheritdoc}
  1708.      */
  1709.     public function walkLiteral($literal)
  1710.     {
  1711.         switch ($literal->type) {
  1712.             case AST\Literal::STRING:
  1713.                 return $this->conn->quote($literal->value);
  1714.             case AST\Literal::BOOLEAN:
  1715.                 return $this->conn->getDatabasePlatform()->convertBooleans(strtolower($literal->value) === 'true');
  1716.             case AST\Literal::NUMERIC:
  1717.                 return $literal->value;
  1718.             default:
  1719.                 throw QueryException::invalidLiteral($literal);
  1720.         }
  1721.     }
  1722.     /**
  1723.      * {@inheritdoc}
  1724.      */
  1725.     public function walkBetweenExpression($betweenExpr)
  1726.     {
  1727.         $sql $this->walkArithmeticExpression($betweenExpr->expression);
  1728.         if ($betweenExpr->not) {
  1729.             $sql .= ' NOT';
  1730.         }
  1731.         $sql .= ' BETWEEN ' $this->walkArithmeticExpression($betweenExpr->leftBetweenExpression)
  1732.             . ' AND ' $this->walkArithmeticExpression($betweenExpr->rightBetweenExpression);
  1733.         return $sql;
  1734.     }
  1735.     /**
  1736.      * {@inheritdoc}
  1737.      */
  1738.     public function walkLikeExpression($likeExpr)
  1739.     {
  1740.         $stringExpr $likeExpr->stringExpression;
  1741.         $leftExpr   is_string($stringExpr) && isset($this->queryComponents[$stringExpr]['resultVariable'])
  1742.             ? $this->walkResultVariable($stringExpr)
  1743.             : $stringExpr->dispatch($this);
  1744.         $sql $leftExpr . ($likeExpr->not ' NOT' '') . ' LIKE ';
  1745.         if ($likeExpr->stringPattern instanceof AST\InputParameter) {
  1746.             $sql .= $this->walkInputParameter($likeExpr->stringPattern);
  1747.         } elseif ($likeExpr->stringPattern instanceof AST\Functions\FunctionNode) {
  1748.             $sql .= $this->walkFunction($likeExpr->stringPattern);
  1749.         } elseif ($likeExpr->stringPattern instanceof AST\PathExpression) {
  1750.             $sql .= $this->walkPathExpression($likeExpr->stringPattern);
  1751.         } else {
  1752.             $sql .= $this->walkLiteral($likeExpr->stringPattern);
  1753.         }
  1754.         if ($likeExpr->escapeChar) {
  1755.             $sql .= ' ESCAPE ' $this->walkLiteral($likeExpr->escapeChar);
  1756.         }
  1757.         return $sql;
  1758.     }
  1759.     /**
  1760.      * {@inheritdoc}
  1761.      */
  1762.     public function walkStateFieldPathExpression($stateFieldPathExpression)
  1763.     {
  1764.         return $this->walkPathExpression($stateFieldPathExpression);
  1765.     }
  1766.     /**
  1767.      * {@inheritdoc}
  1768.      */
  1769.     public function walkComparisonExpression($compExpr)
  1770.     {
  1771.         $leftExpr  $compExpr->leftExpression;
  1772.         $rightExpr $compExpr->rightExpression;
  1773.         $sql       '';
  1774.         $sql .= $leftExpr instanceof AST\Node
  1775.             $leftExpr->dispatch($this)
  1776.             : (is_numeric($leftExpr) ? $leftExpr $this->conn->quote($leftExpr));
  1777.         $sql .= ' ' $compExpr->operator ' ';
  1778.         $sql .= $rightExpr instanceof AST\Node
  1779.             $rightExpr->dispatch($this)
  1780.             : (is_numeric($rightExpr) ? $rightExpr $this->conn->quote($rightExpr));
  1781.         return $sql;
  1782.     }
  1783.     /**
  1784.      * {@inheritdoc}
  1785.      */
  1786.     public function walkInputParameter($inputParam)
  1787.     {
  1788.         $this->parserResult->addParameterMapping($inputParam->name$this->sqlParamIndex++);
  1789.         $parameter $this->query->getParameter($inputParam->name);
  1790.         if ($parameter) {
  1791.             $type $parameter->getType();
  1792.             if (Type::hasType($type)) {
  1793.                 return Type::getType($type)->convertToDatabaseValueSQL('?'$this->platform);
  1794.             }
  1795.         }
  1796.         return '?';
  1797.     }
  1798.     /**
  1799.      * {@inheritdoc}
  1800.      */
  1801.     public function walkArithmeticExpression($arithmeticExpr)
  1802.     {
  1803.         return $arithmeticExpr->isSimpleArithmeticExpression()
  1804.             ? $this->walkSimpleArithmeticExpression($arithmeticExpr->simpleArithmeticExpression)
  1805.             : '(' $this->walkSubselect($arithmeticExpr->subselect) . ')';
  1806.     }
  1807.     /**
  1808.      * {@inheritdoc}
  1809.      */
  1810.     public function walkSimpleArithmeticExpression($simpleArithmeticExpr)
  1811.     {
  1812.         if (! ($simpleArithmeticExpr instanceof AST\SimpleArithmeticExpression)) {
  1813.             return $this->walkArithmeticTerm($simpleArithmeticExpr);
  1814.         }
  1815.         return implode(' 'array_map([$this'walkArithmeticTerm'], $simpleArithmeticExpr->arithmeticTerms));
  1816.     }
  1817.     /**
  1818.      * {@inheritdoc}
  1819.      */
  1820.     public function walkArithmeticTerm($term)
  1821.     {
  1822.         if (is_string($term)) {
  1823.             return isset($this->queryComponents[$term])
  1824.                 ? $this->walkResultVariable($this->queryComponents[$term]['token']['value'])
  1825.                 : $term;
  1826.         }
  1827.         // Phase 2 AST optimization: Skip processing of ArithmeticTerm
  1828.         // if only one ArithmeticFactor is defined
  1829.         if (! ($term instanceof AST\ArithmeticTerm)) {
  1830.             return $this->walkArithmeticFactor($term);
  1831.         }
  1832.         return implode(' 'array_map([$this'walkArithmeticFactor'], $term->arithmeticFactors));
  1833.     }
  1834.     /**
  1835.      * {@inheritdoc}
  1836.      */
  1837.     public function walkArithmeticFactor($factor)
  1838.     {
  1839.         if (is_string($factor)) {
  1840.             return isset($this->queryComponents[$factor])
  1841.                 ? $this->walkResultVariable($this->queryComponents[$factor]['token']['value'])
  1842.                 : $factor;
  1843.         }
  1844.         // Phase 2 AST optimization: Skip processing of ArithmeticFactor
  1845.         // if only one ArithmeticPrimary is defined
  1846.         if (! ($factor instanceof AST\ArithmeticFactor)) {
  1847.             return $this->walkArithmeticPrimary($factor);
  1848.         }
  1849.         $sign $factor->isNegativeSigned() ? '-' : ($factor->isPositiveSigned() ? '+' '');
  1850.         return $sign $this->walkArithmeticPrimary($factor->arithmeticPrimary);
  1851.     }
  1852.     /**
  1853.      * Walks down an ArithmeticPrimary that represents an AST node, thereby generating the appropriate SQL.
  1854.      *
  1855.      * @param mixed $primary
  1856.      *
  1857.      * @return string The SQL.
  1858.      */
  1859.     public function walkArithmeticPrimary($primary)
  1860.     {
  1861.         if ($primary instanceof AST\SimpleArithmeticExpression) {
  1862.             return '(' $this->walkSimpleArithmeticExpression($primary) . ')';
  1863.         }
  1864.         if ($primary instanceof AST\Node) {
  1865.             return $primary->dispatch($this);
  1866.         }
  1867.         return $this->walkEntityIdentificationVariable($primary);
  1868.     }
  1869.     /**
  1870.      * {@inheritdoc}
  1871.      */
  1872.     public function walkStringPrimary($stringPrimary)
  1873.     {
  1874.         return is_string($stringPrimary)
  1875.             ? $this->conn->quote($stringPrimary)
  1876.             : $stringPrimary->dispatch($this);
  1877.     }
  1878.     /**
  1879.      * {@inheritdoc}
  1880.      */
  1881.     public function walkResultVariable($resultVariable)
  1882.     {
  1883.         $resultAlias $this->scalarResultAliasMap[$resultVariable];
  1884.         if (is_array($resultAlias)) {
  1885.             return implode(', '$resultAlias);
  1886.         }
  1887.         return $resultAlias;
  1888.     }
  1889.     /**
  1890.      * @return string The list in parentheses of valid child discriminators from the given class
  1891.      *
  1892.      * @throws QueryException
  1893.      */
  1894.     private function getChildDiscriminatorsFromClassMetadata(
  1895.         ClassMetadataInfo $rootClass,
  1896.         AST\InstanceOfExpression $instanceOfExpr
  1897.     ): string {
  1898.         $sqlParameterList = [];
  1899.         $discriminators   = [];
  1900.         foreach ($instanceOfExpr->value as $parameter) {
  1901.             if ($parameter instanceof AST\InputParameter) {
  1902.                 $this->rsm->discriminatorParameters[$parameter->name] = $parameter->name;
  1903.                 $sqlParameterList[]                                   = $this->walkInParameter($parameter);
  1904.                 continue;
  1905.             }
  1906.             $metadata $this->em->getClassMetadata($parameter);
  1907.             if ($metadata->getName() !== $rootClass->name && ! $metadata->getReflectionClass()->isSubclassOf($rootClass->name)) {
  1908.                 throw QueryException::instanceOfUnrelatedClass($parameter$rootClass->name);
  1909.             }
  1910.             $discriminators += HierarchyDiscriminatorResolver::resolveDiscriminatorsForClass($metadata$this->em);
  1911.         }
  1912.         foreach (array_keys($discriminators) as $dis) {
  1913.             $sqlParameterList[] = $this->conn->quote($dis);
  1914.         }
  1915.         return '(' implode(', '$sqlParameterList) . ')';
  1916.     }
  1917. }