vendor/doctrine/orm/src/Query/SqlWalker.php line 305

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