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

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