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

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