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

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