Failed Conditions
Push — master ( 7c9ab7...fa4d3b )
by Marco
13:03
created

lib/Doctrine/ORM/Query/SqlWalker.php (1 issue)

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\ORM\Query;
6
7
use BadMethodCallException;
8
use Doctrine\DBAL\Connection;
9
use Doctrine\DBAL\LockMode;
10
use Doctrine\DBAL\Platforms\AbstractPlatform;
11
use Doctrine\DBAL\Types\Type;
12
use Doctrine\ORM\AbstractQuery;
13
use Doctrine\ORM\EntityManagerInterface;
14
use Doctrine\ORM\Mapping\ClassMetadata;
15
use Doctrine\ORM\Mapping\FieldMetadata;
16
use Doctrine\ORM\Mapping\InheritanceType;
17
use Doctrine\ORM\Mapping\JoinColumnMetadata;
18
use Doctrine\ORM\Mapping\ManyToManyAssociationMetadata;
19
use Doctrine\ORM\Mapping\OneToManyAssociationMetadata;
20
use Doctrine\ORM\Mapping\ToManyAssociationMetadata;
21
use Doctrine\ORM\Mapping\ToOneAssociationMetadata;
22
use Doctrine\ORM\OptimisticLockException;
23
use Doctrine\ORM\Query;
24
use Doctrine\ORM\Utility\HierarchyDiscriminatorResolver;
25
use Doctrine\ORM\Utility\PersisterHelper;
26
use function array_diff;
27
use function array_filter;
28
use function array_keys;
29
use function array_map;
30
use function array_merge;
31
use function count;
32
use function implode;
33
use function in_array;
34
use function is_array;
35
use function is_float;
36
use function is_numeric;
37
use function is_string;
38
use function reset;
39
use function sprintf;
40
use function strtolower;
41
use function strtoupper;
42
use function trim;
43
44
/**
45
 * The SqlWalker is a TreeWalker that walks over a DQL AST and constructs
46
 * the corresponding SQL.
47
 */
48
class SqlWalker implements TreeWalker
49
{
50
    public const HINT_DISTINCT = 'doctrine.distinct';
51
52
    /** @var ResultSetMapping */
53
    private $rsm;
54
55
    /**
56
     * Counter for generating unique column aliases.
57
     *
58
     * @var int
59
     */
60
    private $aliasCounter = 0;
61
62
    /**
63
     * Counter for generating unique table aliases.
64
     *
65
     * @var int
66
     */
67
    private $tableAliasCounter = 0;
68
69
    /**
70
     * Counter for generating unique scalar result.
71
     *
72
     * @var int
73
     */
74
    private $scalarResultCounter = 1;
75
76
    /**
77
     * Counter for generating unique parameter indexes.
78
     *
79
     * @var int
80
     */
81
    private $sqlParamIndex = 0;
82
83
    /**
84
     * Counter for generating indexes.
85
     *
86
     * @var int
87
     */
88
    private $newObjectCounter = 0;
89
90
    /** @var ParserResult */
91
    private $parserResult;
92
93
    /** @var EntityManagerInterface */
94
    private $em;
95
96
    /** @var Connection */
97
    private $conn;
98
99
    /** @var AbstractQuery */
100
    private $query;
101
102
    /** @var string[] */
103
    private $tableAliasMap = [];
104
105
    /**
106
     * Map from result variable names to their SQL column alias names.
107
     *
108
     * @var string[]|string[][]
109
     */
110
    private $scalarResultAliasMap = [];
111
112
    /**
113
     * Map from Table-Alias + Column-Name to OrderBy-Direction.
114
     *
115
     * @var mixed[]
116
     */
117
    private $orderedColumnsMap = [];
118
119
    /**
120
     * Map from DQL-Alias + Field-Name to SQL Column Alias.
121
     *
122
     * @var string[][]
123
     */
124
    private $scalarFields = [];
125
126
    /**
127
     * Map of all components/classes that appear in the DQL query.
128
     *
129
     * @var mixed[][]
130
     */
131
    private $queryComponents;
132
133
    /**
134
     * A list of classes that appear in non-scalar SelectExpressions.
135
     *
136
     * @var mixed[][]
137
     */
138
    private $selectedClasses = [];
139
140
    /**
141
     * The DQL alias of the root class of the currently traversed query.
142
     *
143
     * @var string[]
144
     */
145
    private $rootAliases = [];
146
147
    /**
148
     * Flag that indicates whether to generate SQL table aliases in the SQL.
149
     * These should only be generated for SELECT queries, not for UPDATE/DELETE.
150
     *
151
     * @var bool
152
     */
153
    private $useSqlTableAliases = true;
154
155
    /**
156
     * The database platform abstraction.
157
     *
158
     * @var AbstractPlatform
159
     */
160
    private $platform;
161
162
    /**
163
     * {@inheritDoc}
164
     */
165 716
    public function __construct(AbstractQuery $query, ParserResult $parserResult, array $queryComponents)
166
    {
167 716
        $this->query           = $query;
168 716
        $this->parserResult    = $parserResult;
169 716
        $this->queryComponents = $queryComponents;
170 716
        $this->rsm             = $parserResult->getResultSetMapping();
171 716
        $this->em              = $query->getEntityManager();
172 716
        $this->conn            = $this->em->getConnection();
173 716
        $this->platform        = $this->conn->getDatabasePlatform();
174 716
    }
175
176
    /**
177
     * Gets the Query instance used by the walker.
178
     *
179
     * @return Query.
180
     */
181
    public function getQuery()
182
    {
183
        return $this->query;
184
    }
185
186
    /**
187
     * Gets the Connection used by the walker.
188
     *
189
     * @return Connection
190
     */
191 51
    public function getConnection()
192
    {
193 51
        return $this->conn;
194
    }
195
196
    /**
197
     * Gets the EntityManager used by the walker.
198
     *
199
     * @return EntityManagerInterface
200
     */
201 23
    public function getEntityManager()
202
    {
203 23
        return $this->em;
204
    }
205
206
    /**
207
     * Gets the information about a single query component.
208
     *
209
     * @param string $dqlAlias The DQL alias.
210
     *
211
     * @return mixed[][]
212
     */
213 18
    public function getQueryComponent($dqlAlias)
214
    {
215 18
        return $this->queryComponents[$dqlAlias];
216
    }
217
218
    /**
219
     * {@inheritdoc}
220
     */
221
    public function getQueryComponents()
222
    {
223
        return $this->queryComponents;
224
    }
225
226
    /**
227
     * {@inheritdoc}
228
     */
229 1
    public function setQueryComponent($dqlAlias, array $queryComponent)
230
    {
231 1
        $requiredKeys = ['metadata', 'parent', 'relation', 'map', 'nestingLevel', 'token'];
232
233 1
        if (array_diff($requiredKeys, array_keys($queryComponent))) {
234 1
            throw QueryException::invalidQueryComponent($dqlAlias);
235
        }
236
237
        $this->queryComponents[$dqlAlias] = $queryComponent;
238
    }
239
240
    /**
241
     * {@inheritdoc}
242
     */
243 710
    public function getExecutor($AST)
244
    {
245
        switch (true) {
246 710
            case $AST instanceof AST\DeleteStatement:
247 39
                $primaryClass = $this->em->getClassMetadata($AST->deleteClause->abstractSchemaName);
248
249 39
                return $primaryClass->inheritanceType === InheritanceType::JOINED
250 2
                    ? new Exec\MultiTableDeleteExecutor($AST, $this)
251 39
                    : new Exec\SingleTableDeleteUpdateExecutor($AST, $this);
252
253 675
            case $AST instanceof AST\UpdateStatement:
254 28
                $primaryClass = $this->em->getClassMetadata($AST->updateClause->abstractSchemaName);
255
256 28
                return $primaryClass->inheritanceType === InheritanceType::JOINED
257 4
                    ? new Exec\MultiTableUpdateExecutor($AST, $this)
258 28
                    : new Exec\SingleTableDeleteUpdateExecutor($AST, $this);
259
260
            default:
261 651
                return new Exec\SingleSelectExecutor($AST, $this);
262
        }
263
    }
264
265
    /**
266
     * Generates a unique, short SQL table alias.
267
     *
268
     * @param string $tableName Table name
269
     * @param string $dqlAlias  The DQL alias.
270
     *
271
     * @return string Generated table alias.
272
     */
273 662
    public function getSQLTableAlias($tableName, $dqlAlias = '')
274
    {
275 662
        $tableName .= $dqlAlias ? '@[' . $dqlAlias . ']' : '';
276
277 662
        if (! isset($this->tableAliasMap[$tableName])) {
278 662
            $this->tableAliasMap[$tableName] = 't' . $this->tableAliasCounter++;
279
        }
280
281 662
        return $this->tableAliasMap[$tableName];
282
    }
283
284
    /**
285
     * Forces the SqlWalker to use a specific alias for a table name, rather than
286
     * generating an alias on its own.
287
     *
288
     * @param string $tableName
289
     * @param string $alias
290
     * @param string $dqlAlias
291
     *
292
     * @return string
293
     */
294 65
    public function setSQLTableAlias($tableName, $alias, $dqlAlias = '')
295
    {
296 65
        $tableName .= $dqlAlias ? '@[' . $dqlAlias . ']' : '';
297
298 65
        $this->tableAliasMap[$tableName] = $alias;
299
300 65
        return $alias;
301
    }
302
303
    /**
304
     * Gets an SQL column alias for a column name.
305
     *
306
     * @return string
307
     */
308 651
    public function getSQLColumnAlias()
309
    {
310 651
        return $this->platform->getSQLResultCasing('c' . $this->aliasCounter++);
311
    }
312
313
    /**
314
     * Generates the SQL JOINs that are necessary for Class Table Inheritance
315
     * for the given class.
316
     *
317
     * @param ClassMetadata $class    The class for which to generate the joins.
318
     * @param string        $dqlAlias The DQL alias of the class.
319
     *
320
     * @return string The SQL.
321
     */
322 113
    private function generateClassTableInheritanceJoins($class, $dqlAlias)
323
    {
324 113
        $sql = '';
325
326 113
        $baseTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
327
328
        // INNER JOIN parent class tables
329 113
        $parentClass = $class;
330
331 113
        while (($parentClass = $parentClass->getParent()) !== null) {
332 78
            $tableName  = $parentClass->table->getQuotedQualifiedName($this->platform);
333 78
            $tableAlias = $this->getSQLTableAlias($parentClass->getTableName(), $dqlAlias);
334
335
            // If this is a joined association we must use left joins to preserve the correct result.
336 78
            $sql .= isset($this->queryComponents[$dqlAlias]['relation']) ? ' LEFT ' : ' INNER ';
337 78
            $sql .= 'JOIN ' . $tableName . ' ' . $tableAlias . ' ON ';
338
339 78
            $sqlParts = [];
340
341 78
            foreach ($class->getIdentifierColumns($this->em) as $column) {
342 78
                $quotedColumnName = $this->platform->quoteIdentifier($column->getColumnName());
343
344 78
                $sqlParts[] = $baseTableAlias . '.' . $quotedColumnName . ' = ' . $tableAlias . '.' . $quotedColumnName;
345
            }
346
347 78
            $filterSql = $this->generateFilterConditionSQL($parentClass, $tableAlias);
348
349
            // Add filters on the root class
350 78
            if ($filterSql) {
351 1
                $sqlParts[] = $filterSql;
352
            }
353
354 78
            $sql .= implode(' AND ', $sqlParts);
355
        }
356
357
        // Ignore subclassing inclusion if partial objects is disallowed
358 113
        if ($this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD)) {
359 21
            return $sql;
360
        }
361
362
        // LEFT JOIN child class tables
363 92
        foreach ($class->getSubClasses() as $subClassName) {
364 41
            $subClass   = $this->em->getClassMetadata($subClassName);
365 41
            $tableName  = $subClass->table->getQuotedQualifiedName($this->platform);
366 41
            $tableAlias = $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias);
367
368 41
            $sql .= ' LEFT JOIN ' . $tableName . ' ' . $tableAlias . ' ON ';
369
370 41
            $sqlParts = [];
371
372 41
            foreach ($subClass->getIdentifierColumns($this->em) as $column) {
373 41
                $quotedColumnName = $this->platform->quoteIdentifier($column->getColumnName());
374
375 41
                $sqlParts[] = $baseTableAlias . '.' . $quotedColumnName . ' = ' . $tableAlias . '.' . $quotedColumnName;
376
            }
377
378 41
            $sql .= implode(' AND ', $sqlParts);
379
        }
380
381 92
        return $sql;
382
    }
383
384
    /**
385
     * @return string
386
     */
387 645
    private function generateOrderedCollectionOrderByItems()
388
    {
389 645
        $orderedColumns = [];
390
391 645
        foreach ($this->selectedClasses as $selectedClass) {
392 489
            $dqlAlias    = $selectedClass['dqlAlias'];
393 489
            $qComp       = $this->queryComponents[$dqlAlias];
394 489
            $association = $qComp['relation'];
395
396 489
            if (! ($association instanceof ToManyAssociationMetadata)) {
397 489
                continue;
398
            }
399
400 98
            foreach ($association->getOrderBy() as $fieldName => $orientation) {
401 6
                $property      = $qComp['metadata']->getProperty($fieldName);
402 6
                $tableName     = $property->getTableName();
403 6
                $columnName    = $this->platform->quoteIdentifier($property->getColumnName());
404 6
                $orderedColumn = $this->getSQLTableAlias($tableName, $dqlAlias) . '.' . $columnName;
405
406
                // OrderByClause should replace an ordered relation. see - DDC-2475
407 6
                if (isset($this->orderedColumnsMap[$orderedColumn])) {
408 1
                    continue;
409
                }
410
411 6
                $this->orderedColumnsMap[$orderedColumn] = $orientation;
412 98
                $orderedColumns[]                        = $orderedColumn . ' ' . $orientation;
413
            }
414
        }
415
416 645
        return implode(', ', $orderedColumns);
417
    }
418
419
    /**
420
     * Generates a discriminator column SQL condition for the class with the given DQL alias.
421
     *
422
     * @param string[] $dqlAliases List of root DQL aliases to inspect for discriminator restrictions.
423
     *
424
     * @return string
425
     */
426 705
    private function generateDiscriminatorColumnConditionSQL(array $dqlAliases)
427
    {
428 705
        $sqlParts = [];
429
430 705
        foreach ($dqlAliases as $dqlAlias) {
431 705
            $class = $this->queryComponents[$dqlAlias]['metadata'];
432
433 705
            if ($class->inheritanceType !== InheritanceType::SINGLE_TABLE) {
434 679
                continue;
435
            }
436
437 41
            $conn   = $this->em->getConnection();
438 41
            $values = [];
439
440 41
            if ($class->discriminatorValue !== null) { // discriminators can be 0
441 21
                $values[] = $conn->quote($class->discriminatorValue);
442
            }
443
444 41
            foreach ($class->getSubClasses() as $subclassName) {
445 30
                $values[] = $conn->quote($this->em->getClassMetadata($subclassName)->discriminatorValue);
446
            }
447
448 41
            $discrColumn      = $class->discriminatorColumn;
449 41
            $discrColumnType  = $discrColumn->getType();
450 41
            $quotedColumnName = $this->platform->quoteIdentifier($discrColumn->getColumnName());
451 41
            $sqlTableAlias    = $this->useSqlTableAliases
452 36
                ? $this->getSQLTableAlias($discrColumn->getTableName(), $dqlAlias) . '.'
453 41
                : '';
454
455 41
            $sqlParts[] = sprintf(
456 41
                '%s IN (%s)',
457 41
                $discrColumnType->convertToDatabaseValueSQL($sqlTableAlias . $quotedColumnName, $this->platform),
458 41
                implode(', ', $values)
459
            );
460
        }
461
462 705
        $sql = implode(' AND ', $sqlParts);
463
464 705
        return isset($sqlParts[1]) ? '(' . $sql . ')' : $sql;
465
    }
466
467
    /**
468
     * Generates the filter SQL for a given entity and table alias.
469
     *
470
     * @param ClassMetadata $targetEntity     Metadata of the target entity.
471
     * @param string        $targetTableAlias The table alias of the joined/selected table.
472
     *
473
     * @return string The SQL query part to add to a query.
474
     */
475 330
    private function generateFilterConditionSQL(ClassMetadata $targetEntity, $targetTableAlias)
476
    {
477 330
        if (! $this->em->hasFilters()) {
478 294
            return '';
479
        }
480
481 41
        switch ($targetEntity->inheritanceType) {
482 41
            case InheritanceType::NONE:
483 31
                break;
484
485 10
            case InheritanceType::JOINED:
486
                // The classes in the inheritance will be added to the query one by one,
487
                // but only the root node is getting filtered
488 6
                if ($targetEntity->getClassName() !== $targetEntity->getRootClassName()) {
489 4
                    return '';
490
                }
491 6
                break;
492
493 4
            case InheritanceType::SINGLE_TABLE:
494
                // With STI the table will only be queried once, make sure that the filters
495
                // are added to the root entity
496 4
                $targetEntity = $this->em->getClassMetadata($targetEntity->getRootClassName());
497 4
                break;
498
499
            default:
500
                //@todo: throw exception?
501
                return '';
502
        }
503
504 41
        $filterClauses = [];
505
506 41
        foreach ($this->em->getFilters()->getEnabledFilters() as $filter) {
507 10
            $filterExpr = $filter->addFilterConstraint($targetEntity, $targetTableAlias);
0 ignored issues
show
It seems like $targetEntity can also be of type Doctrine\Common\Persistence\Mapping\ClassMetadata; however, parameter $targetEntity of Doctrine\ORM\Query\Filte...::addFilterConstraint() does only seem to accept Doctrine\ORM\Mapping\ClassMetadata, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

507
            $filterExpr = $filter->addFilterConstraint(/** @scrutinizer ignore-type */ $targetEntity, $targetTableAlias);
Loading history...
508
509 10
            if ($filterExpr !== '') {
510 10
                $filterClauses[] = '(' . $filterExpr . ')';
511
            }
512
        }
513
514 41
        return implode(' AND ', $filterClauses);
515
    }
516
517
    /**
518
     * {@inheritdoc}
519
     */
520 651
    public function walkSelectStatement(AST\SelectStatement $AST)
521
    {
522 651
        $limit    = $this->query->getMaxResults();
523 651
        $offset   = $this->query->getFirstResult();
524 651
        $lockMode = $this->query->getHint(Query::HINT_LOCK_MODE);
525 651
        $sql      = $this->walkSelectClause($AST->selectClause)
526 651
            . $this->walkFromClause($AST->fromClause)
527 649
            . $this->walkWhereClause($AST->whereClause);
528
529 646
        if ($AST->groupByClause) {
530 27
            $sql .= $this->walkGroupByClause($AST->groupByClause);
531
        }
532
533 646
        if ($AST->havingClause) {
534 14
            $sql .= $this->walkHavingClause($AST->havingClause);
535
        }
536
537 646
        if ($AST->orderByClause) {
538 144
            $sql .= $this->walkOrderByClause($AST->orderByClause);
539
        }
540
541 645
        if (! $AST->orderByClause) {
542 532
            $orderBySql = $this->generateOrderedCollectionOrderByItems();
543
544 532
            if ($orderBySql) {
545 6
                $sql .= ' ORDER BY ' . $orderBySql;
546
            }
547
        }
548
549 645
        if ($limit !== null || $offset !== null) {
550 52
            $sql = $this->platform->modifyLimitQuery($sql, $limit, $offset);
551
        }
552
553 645
        if ($lockMode === null || $lockMode === false || $lockMode === LockMode::NONE) {
554 640
            return $sql;
555
        }
556
557 5
        if ($lockMode === LockMode::PESSIMISTIC_READ) {
558 3
            return $sql . ' ' . $this->platform->getReadLockSQL();
559
        }
560
561 2
        if ($lockMode === LockMode::PESSIMISTIC_WRITE) {
562 1
            return $sql . ' ' . $this->platform->getWriteLockSQL();
563
        }
564
565 1
        if ($lockMode !== LockMode::OPTIMISTIC) {
566
            throw QueryException::invalidLockMode();
567
        }
568
569 1
        foreach ($this->selectedClasses as $selectedClass) {
570 1
            if (! $selectedClass['class']->isVersioned()) {
571 1
                throw OptimisticLockException::lockFailed($selectedClass['class']->getClassName());
572
            }
573
        }
574
575
        return $sql;
576
    }
577
578
    /**
579
     * {@inheritdoc}
580
     */
581 24
    public function walkUpdateStatement(AST\UpdateStatement $AST)
582
    {
583 24
        $this->useSqlTableAliases = false;
584 24
        $this->rsm->isSelect      = false;
585
586 24
        return $this->walkUpdateClause($AST->updateClause)
587 24
            . $this->walkWhereClause($AST->whereClause);
588
    }
589
590
    /**
591
     * {@inheritdoc}
592
     */
593 37
    public function walkDeleteStatement(AST\DeleteStatement $AST)
594
    {
595 37
        $this->useSqlTableAliases = false;
596 37
        $this->rsm->isSelect      = false;
597
598 37
        return $this->walkDeleteClause($AST->deleteClause)
599 37
            . $this->walkWhereClause($AST->whereClause);
600
    }
601
602
    /**
603
     * Walks down an IdentificationVariable AST node, thereby generating the appropriate SQL.
604
     * This one differs of ->walkIdentificationVariable() because it generates the entity identifiers.
605
     *
606
     * @param string $identVariable
607
     *
608
     * @return string
609
     */
610 2
    public function walkEntityIdentificationVariable($identVariable)
611
    {
612 2
        $class      = $this->queryComponents[$identVariable]['metadata'];
613 2
        $tableAlias = $this->getSQLTableAlias($class->getTableName(), $identVariable);
614 2
        $sqlParts   = [];
615
616 2
        foreach ($class->getIdentifierColumns($this->em) as $column) {
617 2
            $quotedColumnName = $this->platform->quoteIdentifier($column->getColumnName());
618
619 2
            $sqlParts[] = $tableAlias . '.' . $quotedColumnName;
620
        }
621
622 2
        return implode(', ', $sqlParts);
623
    }
624
625
    /**
626
     * Walks down an IdentificationVariable (no AST node associated), thereby generating the SQL.
627
     *
628
     * @param string $identificationVariable
629
     * @param string $fieldName
630
     *
631
     * @return string The SQL.
632
     */
633 434
    public function walkIdentificationVariable($identificationVariable, $fieldName = null)
634
    {
635 434
        $class = $this->queryComponents[$identificationVariable]['metadata'];
636
637 434
        if (! $fieldName) {
638
            return $this->getSQLTableAlias($class->getTableName(), $identificationVariable);
639
        }
640
641 434
        $property = $class->getProperty($fieldName);
642
643 434
        if ($class->inheritanceType === InheritanceType::JOINED && $class->isInheritedProperty($fieldName)) {
644 38
            $class = $property->getDeclaringClass();
645
        }
646
647 434
        return $this->getSQLTableAlias($class->getTableName(), $identificationVariable);
648
    }
649
650
    /**
651
     * {@inheritdoc}
652
     */
653 502
    public function walkPathExpression($pathExpr)
654
    {
655 502
        $sql = '';
656
657
        /** @var Query\AST\PathExpression $pathExpr */
658 502
        switch ($pathExpr->type) {
659 502
            case AST\PathExpression::TYPE_STATE_FIELD:
660 481
                $fieldName = $pathExpr->field;
661 481
                $dqlAlias  = $pathExpr->identificationVariable;
662 481
                $class     = $this->queryComponents[$dqlAlias]['metadata'];
663 481
                $property  = $class->getProperty($fieldName);
664
665 481
                if ($this->useSqlTableAliases) {
666 434
                    $sql .= $this->walkIdentificationVariable($dqlAlias, $fieldName) . '.';
667
                }
668
669 481
                $sql .= $this->platform->quoteIdentifier($property->getColumnName());
670 481
                break;
671
672 63
            case AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION:
673
                // 1- the owning side:
674
                //    Just use the foreign key, i.e. u.group_id
675 63
                $fieldName   = $pathExpr->field;
676 63
                $dqlAlias    = $pathExpr->identificationVariable;
677 63
                $class       = $this->queryComponents[$dqlAlias]['metadata'];
678 63
                $association = $class->getProperty($fieldName);
679
680 63
                if (! $association->isOwningSide()) {
681 2
                    throw QueryException::associationPathInverseSideNotSupported($pathExpr);
682
                }
683
684 61
                $joinColumns = $association->getJoinColumns();
685
686
                // COMPOSITE KEYS NOT (YET?) SUPPORTED
687 61
                if (count($joinColumns) > 1) {
688 1
                    throw QueryException::associationPathCompositeKeyNotSupported();
689
                }
690
691 60
                $joinColumn = reset($joinColumns);
692
693 60
                if ($this->useSqlTableAliases) {
694 57
                    $sql .= $this->getSQLTableAlias($joinColumn->getTableName(), $dqlAlias) . '.';
695
                }
696
697 60
                $sql .= $this->platform->quoteIdentifier($joinColumn->getColumnName());
698 60
                break;
699
700
            default:
701
                throw QueryException::invalidPathExpression($pathExpr);
702
        }
703
704 499
        return $sql;
705
    }
706
707
    /**
708
     * {@inheritdoc}
709
     */
710 651
    public function walkSelectClause($selectClause)
711
    {
712 651
        $sql                  = 'SELECT ' . ($selectClause->isDistinct ? 'DISTINCT ' : '');
713 651
        $sqlSelectExpressions = array_filter(array_map([$this, 'walkSelectExpression'], $selectClause->selectExpressions));
714
715 651
        if ($this->query->getHint(Query::HINT_INTERNAL_ITERATION) === true && $selectClause->isDistinct) {
716 1
            $this->query->setHint(self::HINT_DISTINCT, true);
717
        }
718
719
        $addMetaColumns = (
720 651
            ! $this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD) &&
721 482
            $this->query->getHydrationMode() === Query::HYDRATE_OBJECT
722
        ) || (
723 310
            $this->query->getHydrationMode() !== Query::HYDRATE_OBJECT &&
724 651
            $this->query->getHint(Query::HINT_INCLUDE_META_COLUMNS)
725
        );
726
727 651
        foreach ($this->selectedClasses as $selectedClass) {
728 495
            $class       = $selectedClass['class'];
729 495
            $dqlAlias    = $selectedClass['dqlAlias'];
730 495
            $resultAlias = $selectedClass['resultAlias'];
731
732
            // Register as entity or joined entity result
733 495
            if ($this->queryComponents[$dqlAlias]['relation'] === null) {
734 495
                $this->rsm->addEntityResult($class->getClassName(), $dqlAlias, $resultAlias);
735
            } else {
736 157
                $this->rsm->addJoinedEntityResult(
737 157
                    $class->getClassName(),
738 157
                    $dqlAlias,
739 157
                    $this->queryComponents[$dqlAlias]['parent'],
740 157
                    $this->queryComponents[$dqlAlias]['relation']->getName()
741
                );
742
            }
743
744 495
            if ($class->inheritanceType === InheritanceType::SINGLE_TABLE || $class->inheritanceType === InheritanceType::JOINED) {
745
                // Add discriminator columns to SQL
746 99
                $discrColumn      = $class->discriminatorColumn;
747 99
                $discrColumnName  = $discrColumn->getColumnName();
748 99
                $discrColumnType  = $discrColumn->getType();
749 99
                $quotedColumnName = $this->platform->quoteIdentifier($discrColumnName);
750 99
                $sqlTableAlias    = $this->getSQLTableAlias($discrColumn->getTableName(), $dqlAlias);
751 99
                $sqlColumnAlias   = $this->getSQLColumnAlias();
752
753 99
                $sqlSelectExpressions[] = sprintf(
754 99
                    '%s AS %s',
755 99
                    $discrColumnType->convertToDatabaseValueSQL($sqlTableAlias . '.' . $quotedColumnName, $this->platform),
756 99
                    $sqlColumnAlias
757
                );
758
759 99
                $this->rsm->setDiscriminatorColumn($dqlAlias, $sqlColumnAlias);
760 99
                $this->rsm->addMetaResult($dqlAlias, $sqlColumnAlias, $discrColumnName, false, $discrColumnType);
761
            }
762
763
            // Add foreign key columns of class and also parent classes
764 495
            foreach ($class->getDeclaredPropertiesIterator() as $association) {
765 495
                if (! ($association instanceof ToOneAssociationMetadata && $association->isOwningSide())
766 495
                    || ( ! $addMetaColumns && ! $association->isPrimaryKey())) {
767 494
                    continue;
768
                }
769
770 280
                $targetClass = $this->em->getClassMetadata($association->getTargetEntity());
771
772 280
                foreach ($association->getJoinColumns() as $joinColumn) {
773
                    /** @var JoinColumnMetadata $joinColumn */
774 280
                    $columnName           = $joinColumn->getColumnName();
775 280
                    $referencedColumnName = $joinColumn->getReferencedColumnName();
776 280
                    $quotedColumnName     = $this->platform->quoteIdentifier($columnName);
777 280
                    $columnAlias          = $this->getSQLColumnAlias();
778 280
                    $sqlTableAlias        = $this->getSQLTableAlias($joinColumn->getTableName(), $dqlAlias);
779
780 280
                    if (! $joinColumn->getType()) {
781 20
                        $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em));
782
                    }
783
784 280
                    $sqlSelectExpressions[] = sprintf(
785 280
                        '%s.%s AS %s',
786 280
                        $sqlTableAlias,
787 280
                        $quotedColumnName,
788 280
                        $columnAlias
789
                    );
790
791 280
                    $this->rsm->addMetaResult($dqlAlias, $columnAlias, $columnName, $association->isPrimaryKey(), $joinColumn->getType());
792
                }
793
            }
794
795
            // Add foreign key columns to SQL, if necessary
796 495
            if (! $addMetaColumns) {
797 185
                continue;
798
            }
799
800
            // Add foreign key columns of subclasses
801 350
            foreach ($class->getSubClasses() as $subClassName) {
802 38
                $subClass = $this->em->getClassMetadata($subClassName);
803
804 38
                foreach ($subClass->getDeclaredPropertiesIterator() as $association) {
805
                    // Skip if association is inherited
806 38
                    if ($subClass->isInheritedProperty($association->getName())) {
807 38
                        continue;
808
                    }
809
810 28
                    if (! ($association instanceof ToOneAssociationMetadata && $association->isOwningSide())) {
811 27
                        continue;
812
                    }
813
814 14
                    $targetClass = $this->em->getClassMetadata($association->getTargetEntity());
815
816 14
                    foreach ($association->getJoinColumns() as $joinColumn) {
817
                        /** @var JoinColumnMetadata $joinColumn */
818 14
                        $columnName           = $joinColumn->getColumnName();
819 14
                        $referencedColumnName = $joinColumn->getReferencedColumnName();
820 14
                        $quotedColumnName     = $this->platform->quoteIdentifier($columnName);
821 14
                        $columnAlias          = $this->getSQLColumnAlias();
822 14
                        $sqlTableAlias        = $this->getSQLTableAlias($joinColumn->getTableName(), $dqlAlias);
823
824 14
                        if (! $joinColumn->getType()) {
825 1
                            $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em));
826
                        }
827
828 14
                        $sqlSelectExpressions[] = sprintf(
829 14
                            '%s.%s AS %s',
830 14
                            $sqlTableAlias,
831 14
                            $quotedColumnName,
832 14
                            $columnAlias
833
                        );
834
835 350
                        $this->rsm->addMetaResult($dqlAlias, $columnAlias, $columnName, $association->isPrimaryKey(), $joinColumn->getType());
836
                    }
837
                }
838
            }
839
        }
840
841 651
        return $sql . implode(', ', $sqlSelectExpressions);
842
    }
843
844
    /**
845
     * {@inheritdoc}
846
     */
847 653
    public function walkFromClause($fromClause)
848
    {
849 653
        $identificationVarDecls = $fromClause->identificationVariableDeclarations;
850 653
        $sqlParts               = [];
851
852 653
        foreach ($identificationVarDecls as $identificationVariableDecl) {
853 653
            $sqlParts[] = $this->walkIdentificationVariableDeclaration($identificationVariableDecl);
854
        }
855
856 651
        return ' FROM ' . implode(', ', $sqlParts);
857
    }
858
859
    /**
860
     * Walks down a IdentificationVariableDeclaration AST node, thereby generating the appropriate SQL.
861
     *
862
     * @param AST\IdentificationVariableDeclaration $identificationVariableDecl
863
     *
864
     * @return string
865
     */
866 654
    public function walkIdentificationVariableDeclaration($identificationVariableDecl)
867
    {
868 654
        $sql = $this->walkRangeVariableDeclaration($identificationVariableDecl->rangeVariableDeclaration);
869
870 654
        if ($identificationVariableDecl->indexBy) {
871 5
            $this->walkIndexBy($identificationVariableDecl->indexBy);
872
        }
873
874 654
        foreach ($identificationVariableDecl->joins as $join) {
875 245
            $sql .= $this->walkJoin($join);
876
        }
877
878 652
        return $sql;
879
    }
880
881
    /**
882
     * Walks down a IndexBy AST node.
883
     *
884
     * @param AST\IndexBy $indexBy
885
     */
886 8
    public function walkIndexBy($indexBy)
887
    {
888 8
        $pathExpression = $indexBy->simpleStateFieldPathExpression;
889 8
        $alias          = $pathExpression->identificationVariable;
890 8
        $field          = $pathExpression->field;
891
892 8
        if (isset($this->scalarFields[$alias][$field])) {
893
            $this->rsm->addIndexByScalar($this->scalarFields[$alias][$field]);
894
895
            return;
896
        }
897
898 8
        $this->rsm->addIndexBy($alias, $field);
899 8
    }
900
901
    /**
902
     * Walks down a RangeVariableDeclaration AST node, thereby generating the appropriate SQL.
903
     *
904
     * @param AST\RangeVariableDeclaration $rangeVariableDeclaration
905
     *
906
     * @return string
907
     */
908 654
    public function walkRangeVariableDeclaration($rangeVariableDeclaration)
909
    {
910 654
        return $this->generateRangeVariableDeclarationSQL($rangeVariableDeclaration, false);
911
    }
912
913
    /**
914
     * Generate appropriate SQL for RangeVariableDeclaration AST node
915
     *
916
     * @param AST\RangeVariableDeclaration $rangeVariableDeclaration
917
     */
918 654
    private function generateRangeVariableDeclarationSQL($rangeVariableDeclaration, bool $buildNestedJoins) : string
919
    {
920 654
        $class    = $this->em->getClassMetadata($rangeVariableDeclaration->abstractSchemaName);
921 654
        $dqlAlias = $rangeVariableDeclaration->aliasIdentificationVariable;
922
923 654
        if ($rangeVariableDeclaration->isRoot) {
924 654
            $this->rootAliases[] = $dqlAlias;
925
        }
926
927 654
        $tableName  = $class->table->getQuotedQualifiedName($this->platform);
928 654
        $tableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
929
930 654
        $sql = $this->platform->appendLockHint(
931 654
            $tableName . ' ' . $tableAlias,
932 654
            $this->query->getHint(Query::HINT_LOCK_MODE)
933
        );
934
935 654
        if ($class->inheritanceType !== InheritanceType::JOINED) {
936 553
            return $sql;
937
        }
938
939 109
        $classTableInheritanceJoins = $this->generateClassTableInheritanceJoins($class, $dqlAlias);
940
941 109
        if (! $buildNestedJoins) {
942 107
            return $sql . $classTableInheritanceJoins;
943
        }
944
945 3
        return $classTableInheritanceJoins === '' ? $sql : '(' . $sql . $classTableInheritanceJoins . ')';
946
    }
947
948
    /**
949
     * Walks down a JoinAssociationDeclaration AST node, thereby generating the appropriate SQL.
950
     *
951
     * @param AST\JoinAssociationDeclaration $joinAssociationDeclaration
952
     * @param int                            $joinType
953
     * @param AST\ConditionalExpression      $condExpr
954
     *
955
     * @return string
956
     *
957
     * @throws QueryException
958
     */
959 228
    public function walkJoinAssociationDeclaration($joinAssociationDeclaration, $joinType = AST\Join::JOIN_TYPE_INNER, $condExpr = null)
960
    {
961 228
        $sql = '';
962
963 228
        $associationPathExpression = $joinAssociationDeclaration->joinAssociationPathExpression;
964 228
        $joinedDqlAlias            = $joinAssociationDeclaration->aliasIdentificationVariable;
965 228
        $indexBy                   = $joinAssociationDeclaration->indexBy;
966
967 228
        $association     = $this->queryComponents[$joinedDqlAlias]['relation'];
968 228
        $targetClass     = $this->em->getClassMetadata($association->getTargetEntity());
969 228
        $sourceClass     = $this->em->getClassMetadata($association->getSourceEntity());
970 228
        $targetTableName = $targetClass->table->getQuotedQualifiedName($this->platform);
971
972 228
        $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName(), $joinedDqlAlias);
973 228
        $sourceTableAlias = $this->getSQLTableAlias($sourceClass->getTableName(), $associationPathExpression->identificationVariable);
974
975
        // Ensure we got the owning side, since it has all mapping info
976 228
        $owningAssociation = ! $association->isOwningSide()
977 118
            ? $targetClass->getProperty($association->getMappedBy())
978 228
            : $association;
979
980 228
        if ($this->query->getHint(Query::HINT_INTERNAL_ITERATION) === true &&
981 228
            (! $this->query->getHint(self::HINT_DISTINCT) || isset($this->selectedClasses[$joinedDqlAlias]))) {
982 3
            if ($association instanceof ToManyAssociationMetadata) {
983 2
                throw QueryException::iterateWithFetchJoinNotAllowed($owningAssociation);
984
            }
985
        }
986
987 226
        $targetTableJoin = null;
988
989
        // This condition is not checking ManyToOneAssociationMetadata, because by definition it cannot
990
        // be the owning side and previously we ensured that $assoc is always the owning side of the associations.
991
        // The owning side is necessary at this point because only it contains the JoinColumn information.
992 226
        if ($owningAssociation instanceof ToOneAssociationMetadata) {
993 179
            $conditions = [];
994
995 179
            foreach ($owningAssociation->getJoinColumns() as $joinColumn) {
996 179
                $quotedColumnName           = $this->platform->quoteIdentifier($joinColumn->getColumnName());
997 179
                $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName());
998
999 179
                if ($association->isOwningSide()) {
1000 103
                    $conditions[] = sprintf(
1001 103
                        '%s.%s = %s.%s',
1002 103
                        $sourceTableAlias,
1003 103
                        $quotedColumnName,
1004 103
                        $targetTableAlias,
1005 103
                        $quotedReferencedColumnName
1006
                    );
1007
1008 103
                    continue;
1009
                }
1010
1011 107
                $conditions[] = sprintf(
1012 107
                    '%s.%s = %s.%s',
1013 107
                    $sourceTableAlias,
1014 107
                    $quotedReferencedColumnName,
1015 107
                    $targetTableAlias,
1016 107
                    $quotedColumnName
1017
                );
1018
            }
1019
1020
            // Apply remaining inheritance restrictions
1021 179
            $discrSql = $this->generateDiscriminatorColumnConditionSQL([$joinedDqlAlias]);
1022
1023 179
            if ($discrSql) {
1024 3
                $conditions[] = $discrSql;
1025
            }
1026
1027
            // Apply the filters
1028 179
            $filterExpr = $this->generateFilterConditionSQL($targetClass, $targetTableAlias);
1029
1030 179
            if ($filterExpr) {
1031 1
                $conditions[] = $filterExpr;
1032
            }
1033
1034
            $targetTableJoin = [
1035 179
                'table' => $targetTableName . ' ' . $targetTableAlias,
1036 179
                'condition' => implode(' AND ', $conditions),
1037
            ];
1038 57
        } elseif ($owningAssociation instanceof ManyToManyAssociationMetadata) {
1039
            // Join relation table
1040 57
            $joinTable      = $owningAssociation->getJoinTable();
1041 57
            $joinTableName  = $joinTable->getQuotedQualifiedName($this->platform);
1042 57
            $joinTableAlias = $this->getSQLTableAlias($joinTable->getName(), $joinedDqlAlias);
1043
1044 57
            $conditions  = [];
1045 57
            $joinColumns = $association->isOwningSide()
1046 48
                ? $joinTable->getJoinColumns()
1047 57
                : $joinTable->getInverseJoinColumns();
1048
1049 57
            foreach ($joinColumns as $joinColumn) {
1050 57
                $quotedColumnName           = $this->platform->quoteIdentifier($joinColumn->getColumnName());
1051 57
                $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName());
1052
1053 57
                $conditions[] = sprintf(
1054 57
                    '%s.%s = %s.%s',
1055 57
                    $sourceTableAlias,
1056 57
                    $quotedReferencedColumnName,
1057 57
                    $joinTableAlias,
1058 57
                    $quotedColumnName
1059
                );
1060
            }
1061
1062 57
            $sql .= $joinTableName . ' ' . $joinTableAlias . ' ON ' . implode(' AND ', $conditions);
1063
1064
            // Join target table
1065 57
            $sql .= $joinType === AST\Join::JOIN_TYPE_LEFT || $joinType === AST\Join::JOIN_TYPE_LEFTOUTER ? ' LEFT JOIN ' : ' INNER JOIN ';
1066
1067 57
            $conditions  = [];
1068 57
            $joinColumns = $association->isOwningSide()
1069 48
                ? $joinTable->getInverseJoinColumns()
1070 57
                : $joinTable->getJoinColumns();
1071
1072 57
            foreach ($joinColumns as $joinColumn) {
1073 57
                $quotedColumnName           = $this->platform->quoteIdentifier($joinColumn->getColumnName());
1074 57
                $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName());
1075
1076 57
                $conditions[] = sprintf(
1077 57
                    '%s.%s = %s.%s',
1078 57
                    $targetTableAlias,
1079 57
                    $quotedReferencedColumnName,
1080 57
                    $joinTableAlias,
1081 57
                    $quotedColumnName
1082
                );
1083
            }
1084
1085
            // Apply remaining inheritance restrictions
1086 57
            $discrSql = $this->generateDiscriminatorColumnConditionSQL([$joinedDqlAlias]);
1087
1088 57
            if ($discrSql) {
1089 1
                $conditions[] = $discrSql;
1090
            }
1091
1092
            // Apply the filters
1093 57
            $filterExpr = $this->generateFilterConditionSQL($targetClass, $targetTableAlias);
1094
1095 57
            if ($filterExpr) {
1096 1
                $conditions[] = $filterExpr;
1097
            }
1098
1099
            $targetTableJoin = [
1100 57
                'table' => $targetTableName . ' ' . $targetTableAlias,
1101 57
                'condition' => implode(' AND ', $conditions),
1102
            ];
1103
        } else {
1104
            throw new BadMethodCallException('Type of association must be one of *_TO_ONE or MANY_TO_MANY');
1105
        }
1106
1107
        // Handle WITH clause
1108 226
        $withCondition = $condExpr === null ? '' : ('(' . $this->walkConditionalExpression($condExpr) . ')');
1109
1110 226
        if ($targetClass->inheritanceType === InheritanceType::JOINED) {
1111 10
            $ctiJoins = $this->generateClassTableInheritanceJoins($targetClass, $joinedDqlAlias);
1112
1113
            // If we have WITH condition, we need to build nested joins for target class table and cti joins
1114 10
            if ($withCondition) {
1115 1
                $sql .= '(' . $targetTableJoin['table'] . $ctiJoins . ') ON ' . $targetTableJoin['condition'];
1116
            } else {
1117 10
                $sql .= $targetTableJoin['table'] . ' ON ' . $targetTableJoin['condition'] . $ctiJoins;
1118
            }
1119
        } else {
1120 216
            $sql .= $targetTableJoin['table'] . ' ON ' . $targetTableJoin['condition'];
1121
        }
1122
1123 226
        if ($withCondition) {
1124 6
            $sql .= ' AND ' . $withCondition;
1125
        }
1126
1127
        // Apply the indexes
1128 226
        if ($indexBy) {
1129
            // For Many-To-One or One-To-One associations this obviously makes no sense, but is ignored silently.
1130 5
            $this->walkIndexBy($indexBy);
1131 221
        } elseif ($association instanceof ToManyAssociationMetadata && $association->getIndexedBy()) {
1132 3
            $this->rsm->addIndexBy($joinedDqlAlias, $association->getIndexedBy());
1133
        }
1134
1135 226
        return $sql;
1136
    }
1137
1138
    /**
1139
     * {@inheritdoc}
1140
     */
1141 137
    public function walkFunction($function)
1142
    {
1143 137
        return $function->getSql($this);
1144
    }
1145
1146
    /**
1147
     * {@inheritdoc}
1148
     */
1149 155
    public function walkOrderByClause($orderByClause)
1150
    {
1151 155
        $orderByItems           = array_map([$this, 'walkOrderByItem'], $orderByClause->orderByItems);
1152 154
        $collectionOrderByItems = $this->generateOrderedCollectionOrderByItems();
1153
1154 154
        if ($collectionOrderByItems !== '') {
1155
            $orderByItems = array_merge($orderByItems, (array) $collectionOrderByItems);
1156
        }
1157
1158 154
        return ' ORDER BY ' . implode(', ', $orderByItems);
1159
    }
1160
1161
    /**
1162
     * {@inheritdoc}
1163
     */
1164 173
    public function walkOrderByItem($orderByItem)
1165
    {
1166 173
        $type = strtoupper($orderByItem->type);
1167 173
        $expr = $orderByItem->expression;
1168 173
        $sql  = $expr instanceof AST\Node
1169 164
            ? $expr->dispatch($this)
1170 172
            : $this->walkResultVariable($this->queryComponents[$expr]['token']['value']);
1171
1172 172
        $this->orderedColumnsMap[$sql] = $type;
1173
1174 172
        if ($expr instanceof AST\Subselect) {
1175 2
            return '(' . $sql . ') ' . $type;
1176
        }
1177
1178 170
        return $sql . ' ' . $type;
1179
    }
1180
1181
    /**
1182
     * {@inheritdoc}
1183
     */
1184 14
    public function walkHavingClause($havingClause)
1185
    {
1186 14
        return ' HAVING ' . $this->walkConditionalExpression($havingClause->conditionalExpression);
1187
    }
1188
1189
    /**
1190
     * {@inheritdoc}
1191
     */
1192 245
    public function walkJoin($join)
1193
    {
1194 245
        $joinType        = $join->joinType;
1195 245
        $joinDeclaration = $join->joinAssociationDeclaration;
1196
1197 245
        $sql = $joinType === AST\Join::JOIN_TYPE_LEFT || $joinType === AST\Join::JOIN_TYPE_LEFTOUTER
1198 57
            ? ' LEFT JOIN '
1199 245
            : ' INNER JOIN ';
1200
1201
        switch (true) {
1202 245
            case $joinDeclaration instanceof AST\RangeVariableDeclaration:
1203 18
                $class      = $this->em->getClassMetadata($joinDeclaration->abstractSchemaName);
1204 18
                $dqlAlias   = $joinDeclaration->aliasIdentificationVariable;
1205 18
                $tableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
1206 18
                $conditions = [];
1207
1208 18
                if ($join->conditionalExpression) {
1209 16
                    $conditions[] = '(' . $this->walkConditionalExpression($join->conditionalExpression) . ')';
1210
                }
1211
1212 18
                $isUnconditionalJoin = empty($conditions);
1213 18
                $condExprConjunction = $class->inheritanceType === InheritanceType::JOINED && $joinType !== AST\Join::JOIN_TYPE_LEFT && $joinType !== AST\Join::JOIN_TYPE_LEFTOUTER && $isUnconditionalJoin
1214 2
                    ? ' AND '
1215 18
                    : ' ON ';
1216
1217 18
                $sql .= $this->generateRangeVariableDeclarationSQL($joinDeclaration, ! $isUnconditionalJoin);
1218
1219
                // Apply remaining inheritance restrictions
1220 18
                $discrSql = $this->generateDiscriminatorColumnConditionSQL([$dqlAlias]);
1221
1222 18
                if ($discrSql) {
1223 3
                    $conditions[] = $discrSql;
1224
                }
1225
1226
                // Apply the filters
1227 18
                $filterExpr = $this->generateFilterConditionSQL($class, $tableAlias);
1228
1229 18
                if ($filterExpr) {
1230
                    $conditions[] = $filterExpr;
1231
                }
1232
1233 18
                if ($conditions) {
1234 16
                    $sql .= $condExprConjunction . implode(' AND ', $conditions);
1235
                }
1236
1237 18
                break;
1238
1239 228
            case $joinDeclaration instanceof AST\JoinAssociationDeclaration:
1240 228
                $sql .= $this->walkJoinAssociationDeclaration($joinDeclaration, $joinType, $join->conditionalExpression);
1241 226
                break;
1242
        }
1243
1244 243
        return $sql;
1245
    }
1246
1247
    /**
1248
     * Walks down a CoalesceExpression AST node and generates the corresponding SQL.
1249
     *
1250
     * @param AST\CoalesceExpression $coalesceExpression
1251
     *
1252
     * @return string The SQL.
1253
     */
1254 2
    public function walkCoalesceExpression($coalesceExpression)
1255
    {
1256 2
        $sql = 'COALESCE(';
1257
1258 2
        $scalarExpressions = [];
1259
1260 2
        foreach ($coalesceExpression->scalarExpressions as $scalarExpression) {
1261 2
            $scalarExpressions[] = $this->walkSimpleArithmeticExpression($scalarExpression);
1262
        }
1263
1264 2
        return $sql . implode(', ', $scalarExpressions) . ')';
1265
    }
1266
1267
    /**
1268
     * Walks down a NullIfExpression AST node and generates the corresponding SQL.
1269
     *
1270
     * @param AST\NullIfExpression $nullIfExpression
1271
     *
1272
     * @return string The SQL.
1273
     */
1274 3
    public function walkNullIfExpression($nullIfExpression)
1275
    {
1276 3
        $firstExpression = is_string($nullIfExpression->firstExpression)
1277
            ? $this->conn->quote($nullIfExpression->firstExpression)
1278 3
            : $this->walkSimpleArithmeticExpression($nullIfExpression->firstExpression);
1279
1280 3
        $secondExpression = is_string($nullIfExpression->secondExpression)
1281
            ? $this->conn->quote($nullIfExpression->secondExpression)
1282 3
            : $this->walkSimpleArithmeticExpression($nullIfExpression->secondExpression);
1283
1284 3
        return 'NULLIF(' . $firstExpression . ', ' . $secondExpression . ')';
1285
    }
1286
1287
    /**
1288
     * Walks down a GeneralCaseExpression AST node and generates the corresponding SQL.
1289
     *
1290
     * @return string The SQL.
1291
     */
1292 9
    public function walkGeneralCaseExpression(AST\GeneralCaseExpression $generalCaseExpression)
1293
    {
1294 9
        $sql = 'CASE';
1295
1296 9
        foreach ($generalCaseExpression->whenClauses as $whenClause) {
1297 9
            $sql .= ' WHEN ' . $this->walkConditionalExpression($whenClause->caseConditionExpression);
1298 9
            $sql .= ' THEN ' . $this->walkSimpleArithmeticExpression($whenClause->thenScalarExpression);
1299
        }
1300
1301 9
        $sql .= ' ELSE ' . $this->walkSimpleArithmeticExpression($generalCaseExpression->elseScalarExpression) . ' END';
1302
1303 9
        return $sql;
1304
    }
1305
1306
    /**
1307
     * Walks down a SimpleCaseExpression AST node and generates the corresponding SQL.
1308
     *
1309
     * @param AST\SimpleCaseExpression $simpleCaseExpression
1310
     *
1311
     * @return string The SQL.
1312
     */
1313 5
    public function walkSimpleCaseExpression($simpleCaseExpression)
1314
    {
1315 5
        $sql = 'CASE ' . $this->walkStateFieldPathExpression($simpleCaseExpression->caseOperand);
1316
1317 5
        foreach ($simpleCaseExpression->simpleWhenClauses as $simpleWhenClause) {
1318 5
            $sql .= ' WHEN ' . $this->walkSimpleArithmeticExpression($simpleWhenClause->caseScalarExpression);
1319 5
            $sql .= ' THEN ' . $this->walkSimpleArithmeticExpression($simpleWhenClause->thenScalarExpression);
1320
        }
1321
1322 5
        $sql .= ' ELSE ' . $this->walkSimpleArithmeticExpression($simpleCaseExpression->elseScalarExpression) . ' END';
1323
1324 5
        return $sql;
1325
    }
1326
1327
    /**
1328
     * {@inheritdoc}
1329
     */
1330 651
    public function walkSelectExpression($selectExpression)
1331
    {
1332 651
        $sql    = '';
1333 651
        $expr   = $selectExpression->expression;
1334 651
        $hidden = $selectExpression->hiddenAliasResultVariable;
1335
1336
        switch (true) {
1337 651
            case $expr instanceof AST\PathExpression:
1338 111
                if ($expr->type !== AST\PathExpression::TYPE_STATE_FIELD) {
1339
                    throw QueryException::invalidPathExpression($expr);
1340
                }
1341
1342 111
                $fieldName   = $expr->field;
1343 111
                $dqlAlias    = $expr->identificationVariable;
1344 111
                $qComp       = $this->queryComponents[$dqlAlias];
1345 111
                $class       = $qComp['metadata'];
1346 111
                $property    = $class->getProperty($fieldName);
1347 111
                $columnAlias = $this->getSQLColumnAlias();
1348 111
                $resultAlias = $selectExpression->fieldIdentificationVariable ?: $fieldName;
1349 111
                $col         = sprintf(
1350 111
                    '%s.%s',
1351 111
                    $this->getSQLTableAlias($property->getTableName(), $dqlAlias),
1352 111
                    $this->platform->quoteIdentifier($property->getColumnName())
1353
                );
1354
1355 111
                $sql .= sprintf(
1356 111
                    '%s AS %s',
1357 111
                    $property->getType()->convertToPHPValueSQL($col, $this->conn->getDatabasePlatform()),
1358 111
                    $columnAlias
1359
                );
1360
1361 111
                $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
1362
1363 111
                if (! $hidden) {
1364 111
                    $this->rsm->addScalarResult($columnAlias, $resultAlias, $property->getType());
1365 111
                    $this->scalarFields[$dqlAlias][$fieldName] = $columnAlias;
1366
                }
1367
1368 111
                break;
1369
1370 598
            case $expr instanceof AST\AggregateExpression:
1371 588
            case $expr instanceof AST\Functions\FunctionNode:
1372 532
            case $expr instanceof AST\SimpleArithmeticExpression:
1373 532
            case $expr instanceof AST\ArithmeticTerm:
1374 530
            case $expr instanceof AST\ArithmeticFactor:
1375 529
            case $expr instanceof AST\ParenthesisExpression:
1376 528
            case $expr instanceof AST\Literal:
1377 527
            case $expr instanceof AST\NullIfExpression:
1378 526
            case $expr instanceof AST\CoalesceExpression:
1379 525
            case $expr instanceof AST\GeneralCaseExpression:
1380 521
            case $expr instanceof AST\SimpleCaseExpression:
1381 126
                $columnAlias = $this->getSQLColumnAlias();
1382 126
                $resultAlias = $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
1383
1384 126
                $sql .= $expr->dispatch($this) . ' AS ' . $columnAlias;
1385
1386 126
                $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
1387
1388 126
                if (! $hidden) {
1389
                    // Conceptually we could resolve field type here by traverse through AST to retrieve field type,
1390
                    // but this is not a feasible solution; assume 'string'.
1391 126
                    $this->rsm->addScalarResult($columnAlias, $resultAlias, Type::getType('string'));
1392
                }
1393 126
                break;
1394
1395 520
            case $expr instanceof AST\Subselect:
1396 17
                $columnAlias = $this->getSQLColumnAlias();
1397 17
                $resultAlias = $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
1398
1399 17
                $sql .= '(' . $this->walkSubselect($expr) . ') AS ' . $columnAlias;
1400
1401 17
                $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
1402
1403 17
                if (! $hidden) {
1404
                    // We cannot resolve field type here; assume 'string'.
1405 14
                    $this->rsm->addScalarResult($columnAlias, $resultAlias, Type::getType('string'));
1406
                }
1407 17
                break;
1408
1409 515
            case $expr instanceof AST\NewObjectExpression:
1410 20
                $sql .= $this->walkNewObject($expr, $selectExpression->fieldIdentificationVariable);
1411 20
                break;
1412
1413
            default:
1414
                // IdentificationVariable or PartialObjectExpression
1415 495
                if ($expr instanceof AST\PartialObjectExpression) {
1416 15
                    $dqlAlias        = $expr->identificationVariable;
1417 15
                    $partialFieldSet = $expr->partialFieldSet;
1418
                } else {
1419 490
                    $dqlAlias        = $expr;
1420 490
                    $partialFieldSet = [];
1421
                }
1422
1423 495
                $queryComp   = $this->queryComponents[$dqlAlias];
1424 495
                $class       = $queryComp['metadata'];
1425 495
                $resultAlias = $selectExpression->fieldIdentificationVariable ?: null;
1426
1427 495
                if (! isset($this->selectedClasses[$dqlAlias])) {
1428 495
                    $this->selectedClasses[$dqlAlias] = [
1429 495
                        'class'       => $class,
1430 495
                        'dqlAlias'    => $dqlAlias,
1431 495
                        'resultAlias' => $resultAlias,
1432
                    ];
1433
                }
1434
1435 495
                $sqlParts = [];
1436
1437
                // Select all fields from the queried class
1438 495
                foreach ($class->getDeclaredPropertiesIterator() as $fieldName => $property) {
1439 495
                    if (! ($property instanceof FieldMetadata)) {
1440 443
                        continue;
1441
                    }
1442
1443 494
                    if ($partialFieldSet && ! in_array($fieldName, $partialFieldSet, true)) {
1444 13
                        continue;
1445
                    }
1446
1447 493
                    $columnAlias = $this->getSQLColumnAlias();
1448 493
                    $col         = sprintf(
1449 493
                        '%s.%s',
1450 493
                        $this->getSQLTableAlias($property->getTableName(), $dqlAlias),
1451 493
                        $this->platform->quoteIdentifier($property->getColumnName())
1452
                    );
1453
1454 493
                    $sqlParts[] = sprintf(
1455 493
                        '%s AS %s',
1456 493
                        $property->getType()->convertToPHPValueSQL($col, $this->platform),
1457 493
                        $columnAlias
1458
                    );
1459
1460 493
                    $this->scalarResultAliasMap[$resultAlias][] = $columnAlias;
1461
1462 493
                    $this->rsm->addFieldResult($dqlAlias, $columnAlias, $fieldName, $class->getClassName());
1463
                }
1464
1465
                // Add any additional fields of subclasses (excluding inherited fields)
1466
                // 1) on Single Table Inheritance: always, since its marginal overhead
1467
                // 2) on Class Table Inheritance only if partial objects are disallowed,
1468
                //    since it requires outer joining subtables.
1469 495
                if ($class->inheritanceType === InheritanceType::SINGLE_TABLE || ! $this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD)) {
1470 402
                    foreach ($class->getSubClasses() as $subClassName) {
1471 51
                        $subClass = $this->em->getClassMetadata($subClassName);
1472
1473 51
                        foreach ($subClass->getDeclaredPropertiesIterator() as $fieldName => $property) {
1474 51
                            if (! ($property instanceof FieldMetadata)) {
1475 39
                                continue;
1476
                            }
1477
1478 51
                            if ($subClass->isInheritedProperty($fieldName) || ($partialFieldSet && ! in_array($fieldName, $partialFieldSet, true))) {
1479 51
                                continue;
1480
                            }
1481
1482 38
                            $columnAlias = $this->getSQLColumnAlias();
1483 38
                            $col         = sprintf(
1484 38
                                '%s.%s',
1485 38
                                $this->getSQLTableAlias($property->getTableName(), $dqlAlias),
1486 38
                                $this->platform->quoteIdentifier($property->getColumnName())
1487
                            );
1488
1489 38
                            $sqlParts[] = sprintf(
1490 38
                                '%s AS %s',
1491 38
                                $property->getType()->convertToPHPValueSQL($col, $this->platform),
1492 38
                                $columnAlias
1493
                            );
1494
1495 38
                            $this->scalarResultAliasMap[$resultAlias][] = $columnAlias;
1496
1497 51
                            $this->rsm->addFieldResult($dqlAlias, $columnAlias, $fieldName, $subClassName);
1498
                        }
1499
                    }
1500
                }
1501
1502 495
                $sql .= implode(', ', $sqlParts);
1503
        }
1504
1505 651
        return $sql;
1506
    }
1507
1508
    /**
1509
     * {@inheritdoc}
1510
     */
1511
    public function walkQuantifiedExpression($qExpr)
1512
    {
1513
        return ' ' . strtoupper($qExpr->type) . '(' . $this->walkSubselect($qExpr->subselect) . ')';
1514
    }
1515
1516
    /**
1517
     * {@inheritdoc}
1518
     */
1519 35
    public function walkSubselect($subselect)
1520
    {
1521 35
        $useAliasesBefore  = $this->useSqlTableAliases;
1522 35
        $rootAliasesBefore = $this->rootAliases;
1523
1524 35
        $this->rootAliases        = []; // reset the rootAliases for the subselect
1525 35
        $this->useSqlTableAliases = true;
1526
1527 35
        $sql  = $this->walkSimpleSelectClause($subselect->simpleSelectClause);
1528 35
        $sql .= $this->walkSubselectFromClause($subselect->subselectFromClause);
1529 35
        $sql .= $this->walkWhereClause($subselect->whereClause);
1530
1531 35
        $sql .= $subselect->groupByClause ? $this->walkGroupByClause($subselect->groupByClause) : '';
1532 35
        $sql .= $subselect->havingClause ? $this->walkHavingClause($subselect->havingClause) : '';
1533 35
        $sql .= $subselect->orderByClause ? $this->walkOrderByClause($subselect->orderByClause) : '';
1534
1535 35
        $this->rootAliases        = $rootAliasesBefore; // put the main aliases back
1536 35
        $this->useSqlTableAliases = $useAliasesBefore;
1537
1538 35
        return $sql;
1539
    }
1540
1541
    /**
1542
     * {@inheritdoc}
1543
     */
1544 35
    public function walkSubselectFromClause($subselectFromClause)
1545
    {
1546 35
        $identificationVarDecls = $subselectFromClause->identificationVariableDeclarations;
1547 35
        $sqlParts               = [];
1548
1549 35
        foreach ($identificationVarDecls as $subselectIdVarDecl) {
1550 35
            $sqlParts[] = $this->walkIdentificationVariableDeclaration($subselectIdVarDecl);
1551
        }
1552
1553 35
        return ' FROM ' . implode(', ', $sqlParts);
1554
    }
1555
1556
    /**
1557
     * {@inheritdoc}
1558
     */
1559 35
    public function walkSimpleSelectClause($simpleSelectClause)
1560
    {
1561 35
        return 'SELECT' . ($simpleSelectClause->isDistinct ? ' DISTINCT' : '')
1562 35
            . $this->walkSimpleSelectExpression($simpleSelectClause->simpleSelectExpression);
1563
    }
1564
1565
    /**
1566
     * @return string.
1567
     */
1568 22
    public function walkParenthesisExpression(AST\ParenthesisExpression $parenthesisExpression)
1569
    {
1570 22
        return sprintf('(%s)', $parenthesisExpression->expression->dispatch($this));
1571
    }
1572
1573
    /**
1574
     * @param AST\NewObjectExpression $newObjectExpression
1575
     * @param string|null             $newObjectResultAlias
1576
     *
1577
     * @return string The SQL.
1578
     */
1579 20
    public function walkNewObject($newObjectExpression, $newObjectResultAlias = null)
1580
    {
1581 20
        $sqlSelectExpressions = [];
1582 20
        $objIndex             = $newObjectResultAlias ?: $this->newObjectCounter++;
1583
1584 20
        foreach ($newObjectExpression->args as $argIndex => $e) {
1585 20
            $resultAlias = $this->scalarResultCounter++;
1586 20
            $columnAlias = $this->getSQLColumnAlias();
1587 20
            $fieldType   = Type::getType('string');
1588
1589
            switch (true) {
1590 20
                case $e instanceof AST\NewObjectExpression:
1591
                    $sqlSelectExpressions[] = $e->dispatch($this);
1592
                    break;
1593
1594 20
                case $e instanceof AST\Subselect:
1595 1
                    $sqlSelectExpressions[] = '(' . $e->dispatch($this) . ') AS ' . $columnAlias;
1596 1
                    break;
1597
1598 20
                case $e instanceof AST\PathExpression:
1599 20
                    $dqlAlias  = $e->identificationVariable;
1600 20
                    $qComp     = $this->queryComponents[$dqlAlias];
1601 20
                    $class     = $qComp['metadata'];
1602 20
                    $fieldType = $class->getProperty($e->field)->getType();
1603
1604 20
                    $sqlSelectExpressions[] = trim((string) $e->dispatch($this)) . ' AS ' . $columnAlias;
1605 20
                    break;
1606
1607 6
                case $e instanceof AST\Literal:
1608 1
                    switch ($e->type) {
1609 1
                        case AST\Literal::BOOLEAN:
1610 1
                            $fieldType = Type::getType('boolean');
1611 1
                            break;
1612
1613 1
                        case AST\Literal::NUMERIC:
1614 1
                            $fieldType = Type::getType(is_float($e->value) ? 'float' : 'integer');
1615 1
                            break;
1616
                    }
1617
1618 1
                    $sqlSelectExpressions[] = trim((string) $e->dispatch($this)) . ' AS ' . $columnAlias;
1619 1
                    break;
1620
1621
                default:
1622 5
                    $sqlSelectExpressions[] = trim((string) $e->dispatch($this)) . ' AS ' . $columnAlias;
1623 5
                    break;
1624
            }
1625
1626 20
            $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
1627 20
            $this->rsm->addScalarResult($columnAlias, $resultAlias, $fieldType);
1628
1629 20
            $this->rsm->newObjectMappings[$columnAlias] = [
1630 20
                'className' => $newObjectExpression->className,
1631 20
                'objIndex'  => $objIndex,
1632 20
                'argIndex'  => $argIndex,
1633
            ];
1634
        }
1635
1636 20
        return implode(', ', $sqlSelectExpressions);
1637
    }
1638
1639
    /**
1640
     * {@inheritdoc}
1641
     */
1642 35
    public function walkSimpleSelectExpression($simpleSelectExpression)
1643
    {
1644 35
        $expr = $simpleSelectExpression->expression;
1645 35
        $sql  = ' ';
1646
1647
        switch (true) {
1648 35
            case $expr instanceof AST\PathExpression:
1649 9
                $sql .= $this->walkPathExpression($expr);
1650 9
                break;
1651
1652 26
            case $expr instanceof AST\Subselect:
1653
                $alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
1654
1655
                $columnAlias                        = 'sclr' . $this->aliasCounter++;
1656
                $this->scalarResultAliasMap[$alias] = $columnAlias;
1657
1658
                $sql .= '(' . $this->walkSubselect($expr) . ') AS ' . $columnAlias;
1659
                break;
1660
1661 26
            case $expr instanceof AST\Functions\FunctionNode:
1662 11
            case $expr instanceof AST\SimpleArithmeticExpression:
1663 10
            case $expr instanceof AST\ArithmeticTerm:
1664 9
            case $expr instanceof AST\ArithmeticFactor:
1665 9
            case $expr instanceof AST\Literal:
1666 7
            case $expr instanceof AST\NullIfExpression:
1667 7
            case $expr instanceof AST\CoalesceExpression:
1668 7
            case $expr instanceof AST\GeneralCaseExpression:
1669 5
            case $expr instanceof AST\SimpleCaseExpression:
1670 23
                $alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
1671
1672 23
                $columnAlias                        = $this->getSQLColumnAlias();
1673 23
                $this->scalarResultAliasMap[$alias] = $columnAlias;
1674
1675 23
                $sql .= $expr->dispatch($this) . ' AS ' . $columnAlias;
1676 23
                break;
1677
1678 3
            case $expr instanceof AST\ParenthesisExpression:
1679 1
                $sql .= $this->walkParenthesisExpression($expr);
1680 1
                break;
1681
1682
            default: // IdentificationVariable
1683 2
                $sql .= $this->walkEntityIdentificationVariable($expr);
1684 2
                break;
1685
        }
1686
1687 35
        return $sql;
1688
    }
1689
1690
    /**
1691
     * {@inheritdoc}
1692
     */
1693 82
    public function walkAggregateExpression($aggExpression)
1694
    {
1695 82
        return $aggExpression->functionName . '(' . ($aggExpression->isDistinct ? 'DISTINCT ' : '')
1696 82
            . $this->walkSimpleArithmeticExpression($aggExpression->pathExpression) . ')';
1697
    }
1698
1699
    /**
1700
     * {@inheritdoc}
1701
     */
1702 27
    public function walkGroupByClause($groupByClause)
1703
    {
1704 27
        $sqlParts = [];
1705
1706 27
        foreach ($groupByClause->groupByItems as $groupByItem) {
1707 27
            $sqlParts[] = $this->walkGroupByItem($groupByItem);
1708
        }
1709
1710 27
        return ' GROUP BY ' . implode(', ', $sqlParts);
1711
    }
1712
1713
    /**
1714
     * {@inheritdoc}
1715
     */
1716 27
    public function walkGroupByItem($groupByItem)
1717
    {
1718
        // StateFieldPathExpression
1719 27
        if (! is_string($groupByItem)) {
1720 14
            return $this->walkPathExpression($groupByItem);
1721
        }
1722
1723
        // ResultVariable
1724 13
        if (isset($this->queryComponents[$groupByItem]['resultVariable'])) {
1725 2
            $resultVariable = $this->queryComponents[$groupByItem]['resultVariable'];
1726
1727 2
            if ($resultVariable instanceof AST\PathExpression) {
1728 1
                return $this->walkPathExpression($resultVariable);
1729
            }
1730
1731 1
            if (isset($resultVariable->pathExpression)) {
1732
                return $this->walkPathExpression($resultVariable->pathExpression);
1733
            }
1734
1735 1
            return $this->walkResultVariable($groupByItem);
1736
        }
1737
1738
        // IdentificationVariable
1739
        /** @var ClassMetadata $classMetadata */
1740 11
        $classMetadata = $this->queryComponents[$groupByItem]['metadata'];
1741 11
        $sqlParts      = [];
1742
1743 11
        foreach ($classMetadata->getDeclaredPropertiesIterator() as $property) {
1744
            switch (true) {
1745 11
                case $property instanceof FieldMetadata:
1746 11
                    $type       = AST\PathExpression::TYPE_STATE_FIELD;
1747 11
                    $item       = new AST\PathExpression($type, $groupByItem, $property->getName());
1748 11
                    $item->type = $type;
1749
1750 11
                    $sqlParts[] = $this->walkPathExpression($item);
1751 11
                    break;
1752
1753 11
                case $property instanceof ToOneAssociationMetadata && $property->isOwningSide():
1754 7
                    $type       = AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION;
1755 7
                    $item       = new AST\PathExpression($type, $groupByItem, $property->getName());
1756 7
                    $item->type = $type;
1757
1758 7
                    $sqlParts[] = $this->walkPathExpression($item);
1759 11
                    break;
1760
            }
1761
        }
1762
1763 11
        return implode(', ', $sqlParts);
1764
    }
1765
1766
    /**
1767
     * {@inheritdoc}
1768
     */
1769 37
    public function walkDeleteClause(AST\DeleteClause $deleteClause)
1770
    {
1771 37
        $class     = $this->em->getClassMetadata($deleteClause->abstractSchemaName);
1772 37
        $tableName = $class->getTableName();
1773 37
        $sql       = 'DELETE FROM ' . $class->table->getQuotedQualifiedName($this->platform);
1774
1775 37
        $this->setSQLTableAlias($tableName, $tableName, $deleteClause->aliasIdentificationVariable);
1776
1777 37
        $this->rootAliases[] = $deleteClause->aliasIdentificationVariable;
1778
1779 37
        return $sql;
1780
    }
1781
1782
    /**
1783
     * {@inheritdoc}
1784
     */
1785 24
    public function walkUpdateClause($updateClause)
1786
    {
1787 24
        $class     = $this->em->getClassMetadata($updateClause->abstractSchemaName);
1788 24
        $tableName = $class->getTableName();
1789 24
        $sql       = 'UPDATE ' . $class->table->getQuotedQualifiedName($this->platform);
1790
1791 24
        $this->setSQLTableAlias($tableName, $tableName, $updateClause->aliasIdentificationVariable);
1792 24
        $this->rootAliases[] = $updateClause->aliasIdentificationVariable;
1793
1794 24
        return $sql . ' SET ' . implode(', ', array_map([$this, 'walkUpdateItem'], $updateClause->updateItems));
1795
    }
1796
1797
    /**
1798
     * {@inheritdoc}
1799
     */
1800 28
    public function walkUpdateItem($updateItem)
1801
    {
1802 28
        $useTableAliasesBefore    = $this->useSqlTableAliases;
1803 28
        $this->useSqlTableAliases = false;
1804
1805 28
        $sql      = $this->walkPathExpression($updateItem->pathExpression) . ' = ';
1806 28
        $newValue = $updateItem->newValue;
1807
1808
        switch (true) {
1809 28
            case $newValue instanceof AST\Node:
1810 27
                $sql .= $newValue->dispatch($this);
1811 27
                break;
1812
1813 1
            case $newValue === null:
1814 1
                $sql .= 'NULL';
1815 1
                break;
1816
1817
            default:
1818
                $sql .= $this->conn->quote($newValue);
1819
                break;
1820
        }
1821
1822 28
        $this->useSqlTableAliases = $useTableAliasesBefore;
1823
1824 28
        return $sql;
1825
    }
1826
1827
    /**
1828
     * {@inheritdoc}
1829
     */
1830 708
    public function walkWhereClause($whereClause)
1831
    {
1832 708
        $condSql  = $whereClause !== null ? $this->walkConditionalExpression($whereClause->conditionalExpression) : '';
1833 705
        $discrSql = $this->generateDiscriminatorColumnConditionSQL($this->rootAliases);
1834
1835 705
        if ($this->em->hasFilters()) {
1836 41
            $filterClauses = [];
1837 41
            foreach ($this->rootAliases as $dqlAlias) {
1838 41
                $class      = $this->queryComponents[$dqlAlias]['metadata'];
1839 41
                $tableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
1840 41
                $filterExpr = $this->generateFilterConditionSQL($class, $tableAlias);
1841
1842 41
                if ($filterExpr) {
1843 41
                    $filterClauses[] = $filterExpr;
1844
                }
1845
            }
1846
1847 41
            if ($filterClauses) {
1848 6
                if ($condSql) {
1849 2
                    $condSql = '(' . $condSql . ') AND ';
1850
                }
1851
1852 6
                $condSql .= implode(' AND ', $filterClauses);
1853
            }
1854
        }
1855
1856 705
        if ($condSql) {
1857 347
            return ' WHERE ' . (! $discrSql ? $condSql : '(' . $condSql . ') AND ' . $discrSql);
1858
        }
1859
1860 435
        if ($discrSql) {
1861 24
            return ' WHERE ' . $discrSql;
1862
        }
1863
1864 415
        return '';
1865
    }
1866
1867
    /**
1868
     * {@inheritdoc}
1869
     */
1870 380
    public function walkConditionalExpression($condExpr)
1871
    {
1872
        // Phase 2 AST optimization: Skip processing of ConditionalExpression
1873
        // if only one ConditionalTerm is defined
1874 380
        if (! ($condExpr instanceof AST\ConditionalExpression)) {
1875 324
            return $this->walkConditionalTerm($condExpr);
1876
        }
1877
1878 74
        return implode(' OR ', array_map([$this, 'walkConditionalTerm'], $condExpr->conditionalTerms));
1879
    }
1880
1881
    /**
1882
     * {@inheritdoc}
1883
     */
1884 380
    public function walkConditionalTerm($condTerm)
1885
    {
1886
        // Phase 2 AST optimization: Skip processing of ConditionalTerm
1887
        // if only one ConditionalFactor is defined
1888 380
        if (! ($condTerm instanceof AST\ConditionalTerm)) {
1889 310
            return $this->walkConditionalFactor($condTerm);
1890
        }
1891
1892 93
        return implode(' AND ', array_map([$this, 'walkConditionalFactor'], $condTerm->conditionalFactors));
1893
    }
1894
1895
    /**
1896
     * {@inheritdoc}
1897
     */
1898 380
    public function walkConditionalFactor($factor)
1899
    {
1900
        // Phase 2 AST optimization: Skip processing of ConditionalFactor
1901
        // if only one ConditionalPrimary is defined
1902 380
        return ! ($factor instanceof AST\ConditionalFactor)
1903 377
            ? $this->walkConditionalPrimary($factor)
1904 377
            : ($factor->not ? 'NOT ' : '') . $this->walkConditionalPrimary($factor->conditionalPrimary);
1905
    }
1906
1907
    /**
1908
     * {@inheritdoc}
1909
     */
1910 380
    public function walkConditionalPrimary($primary)
1911
    {
1912 380
        if ($primary->isSimpleConditionalExpression()) {
1913 380
            return $primary->simpleConditionalExpression->dispatch($this);
1914
        }
1915
1916 25
        if ($primary->isConditionalExpression()) {
1917 25
            $condExpr = $primary->conditionalExpression;
1918
1919 25
            return '(' . $this->walkConditionalExpression($condExpr) . ')';
1920
        }
1921
    }
1922
1923
    /**
1924
     * {@inheritdoc}
1925
     */
1926 5
    public function walkExistsExpression($existsExpr)
1927
    {
1928 5
        $sql = $existsExpr->not ? 'NOT ' : '';
1929
1930 5
        $sql .= 'EXISTS (' . $this->walkSubselect($existsExpr->subselect) . ')';
1931
1932 5
        return $sql;
1933
    }
1934
1935
    /**
1936
     * {@inheritdoc}
1937
     */
1938 7
    public function walkCollectionMemberExpression($collMemberExpr)
1939
    {
1940 7
        $sql  = $collMemberExpr->not ? 'NOT ' : '';
1941 7
        $sql .= 'EXISTS (SELECT 1 FROM ';
1942
1943 7
        $entityExpr   = $collMemberExpr->entityExpression;
1944 7
        $collPathExpr = $collMemberExpr->collectionValuedPathExpression;
1945
1946 7
        $fieldName = $collPathExpr->field;
1947 7
        $dqlAlias  = $collPathExpr->identificationVariable;
1948
1949 7
        $class = $this->queryComponents[$dqlAlias]['metadata'];
1950
1951
        switch (true) {
1952
            // InputParameter
1953 7
            case $entityExpr instanceof AST\InputParameter:
1954 4
                $dqlParamKey = $entityExpr->name;
1955 4
                $entitySql   = '?';
1956 4
                break;
1957
1958
            // SingleValuedAssociationPathExpression | IdentificationVariable
1959 3
            case $entityExpr instanceof AST\PathExpression:
1960 3
                $entitySql = $this->walkPathExpression($entityExpr);
1961 3
                break;
1962
1963
            default:
1964
                throw new BadMethodCallException('Not implemented');
1965
        }
1966
1967 7
        $association       = $class->getProperty($fieldName);
1968 7
        $targetClass       = $this->em->getClassMetadata($association->getTargetEntity());
1969 7
        $owningAssociation = $association->isOwningSide()
1970 6
            ? $association
1971 7
            : $targetClass->getProperty($association->getMappedBy());
1972
1973 7
        if ($association instanceof OneToManyAssociationMetadata) {
1974 1
            $targetTableName  = $targetClass->table->getQuotedQualifiedName($this->platform);
1975 1
            $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName());
1976 1
            $sourceTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
1977
1978 1
            $sql .= $targetTableName . ' ' . $targetTableAlias . ' WHERE ';
1979
1980 1
            $sqlParts = [];
1981
1982 1
            foreach ($owningAssociation->getJoinColumns() as $joinColumn) {
1983 1
                $sqlParts[] = sprintf(
1984 1
                    '%s.%s = %s.%s',
1985 1
                    $sourceTableAlias,
1986 1
                    $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName()),
1987 1
                    $targetTableAlias,
1988 1
                    $this->platform->quoteIdentifier($joinColumn->getColumnName())
1989
                );
1990
            }
1991
1992 1
            foreach ($targetClass->getIdentifierColumns($this->em) as $targetColumn) {
1993 1
                $quotedTargetColumnName = $this->platform->quoteIdentifier($targetColumn->getColumnName());
1994
1995 1
                if (isset($dqlParamKey)) {
1996 1
                    $this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++);
1997
                }
1998
1999 1
                $sqlParts[] = $targetTableAlias . '.' . $quotedTargetColumnName . ' = ' . $entitySql;
2000
            }
2001
2002 1
            $sql .= implode(' AND ', $sqlParts);
2003
        } else { // many-to-many
2004
            // SQL table aliases
2005 6
            $joinTable        = $owningAssociation->getJoinTable();
2006 6
            $joinTableName    = $joinTable->getQuotedQualifiedName($this->platform);
2007 6
            $joinTableAlias   = $this->getSQLTableAlias($joinTable->getName());
2008 6
            $targetTableName  = $targetClass->table->getQuotedQualifiedName($this->platform);
2009 6
            $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName());
2010 6
            $sourceTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
2011
2012
            // join to target table
2013 6
            $sql .= $joinTableName . ' ' . $joinTableAlias . ' INNER JOIN ' . $targetTableName . ' ' . $targetTableAlias . ' ON ';
2014
2015
            // join conditions
2016 6
            $joinSqlParts = [];
2017 6
            $joinColumns  = $association->isOwningSide()
2018 6
                ? $joinTable->getInverseJoinColumns()
2019 6
                : $joinTable->getJoinColumns();
2020
2021 6
            foreach ($joinColumns as $joinColumn) {
2022 6
                $quotedColumnName           = $this->platform->quoteIdentifier($joinColumn->getColumnName());
2023 6
                $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName());
2024
2025 6
                $joinSqlParts[] = sprintf(
2026 6
                    '%s.%s = %s.%s',
2027 6
                    $joinTableAlias,
2028 6
                    $quotedColumnName,
2029 6
                    $targetTableAlias,
2030 6
                    $quotedReferencedColumnName
2031
                );
2032
            }
2033
2034 6
            $sql .= implode(' AND ', $joinSqlParts);
2035 6
            $sql .= ' WHERE ';
2036
2037 6
            $sqlParts    = [];
2038 6
            $joinColumns = $association->isOwningSide()
2039 6
                ? $joinTable->getJoinColumns()
2040 6
                : $joinTable->getInverseJoinColumns();
2041
2042 6
            foreach ($joinColumns as $joinColumn) {
2043 6
                $quotedColumnName           = $this->platform->quoteIdentifier($joinColumn->getColumnName());
2044 6
                $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName());
2045
2046 6
                $sqlParts[] = sprintf(
2047 6
                    '%s.%s = %s.%s',
2048 6
                    $joinTableAlias,
2049 6
                    $quotedColumnName,
2050 6
                    $sourceTableAlias,
2051 6
                    $quotedReferencedColumnName
2052
                );
2053
            }
2054
2055 6
            foreach ($targetClass->getIdentifierColumns($this->em) as $targetColumn) {
2056 6
                $quotedTargetColumnName = $this->platform->quoteIdentifier($targetColumn->getColumnName());
2057
2058 6
                if (isset($dqlParamKey)) {
2059 3
                    $this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++);
2060
                }
2061
2062 6
                $sqlParts[] = $targetTableAlias . '.' . $quotedTargetColumnName . ' = ' . $entitySql;
2063
            }
2064
2065 6
            $sql .= implode(' AND ', $sqlParts);
2066
        }
2067
2068 7
        return $sql . ')';
2069
    }
2070
2071
    /**
2072
     * {@inheritdoc}
2073
     */
2074 3
    public function walkEmptyCollectionComparisonExpression($emptyCollCompExpr)
2075
    {
2076 3
        $sizeFunc                           = new AST\Functions\SizeFunction('size');
2077 3
        $sizeFunc->collectionPathExpression = $emptyCollCompExpr->expression;
2078
2079 3
        return $sizeFunc->getSql($this) . ($emptyCollCompExpr->not ? ' > 0' : ' = 0');
2080
    }
2081
2082
    /**
2083
     * {@inheritdoc}
2084
     */
2085 13
    public function walkNullComparisonExpression($nullCompExpr)
2086
    {
2087 13
        $expression = $nullCompExpr->expression;
2088 13
        $comparison = ' IS' . ($nullCompExpr->not ? ' NOT' : '') . ' NULL';
2089
2090
        // Handle ResultVariable
2091 13
        if (is_string($expression) && isset($this->queryComponents[$expression]['resultVariable'])) {
2092 2
            return $this->walkResultVariable($expression) . $comparison;
2093
        }
2094
2095
        // Handle InputParameter mapping inclusion to ParserResult
2096 11
        if ($expression instanceof AST\InputParameter) {
2097
            return $this->walkInputParameter($expression) . $comparison;
2098
        }
2099
2100 11
        return $expression->dispatch($this) . $comparison;
2101
    }
2102
2103
    /**
2104
     * {@inheritdoc}
2105
     */
2106 88
    public function walkInExpression($inExpr)
2107
    {
2108 88
        $sql = $this->walkArithmeticExpression($inExpr->expression) . ($inExpr->not ? ' NOT' : '') . ' IN (';
2109
2110 87
        $sql .= $inExpr->subselect
2111 7
            ? $this->walkSubselect($inExpr->subselect)
2112 87
            : implode(', ', array_map([$this, 'walkInParameter'], $inExpr->literals));
2113
2114 87
        $sql .= ')';
2115
2116 87
        return $sql;
2117
    }
2118
2119
    /**
2120
     * {@inheritdoc}
2121
     *
2122
     * @throws QueryException
2123
     */
2124 14
    public function walkInstanceOfExpression($instanceOfExpr)
2125
    {
2126 14
        $dqlAlias         = $instanceOfExpr->identificationVariable;
2127 14
        $class            = $this->queryComponents[$dqlAlias]['metadata'];
2128 14
        $discrClass       = $this->em->getClassMetadata($class->getRootClassName());
2129 14
        $discrColumn      = $class->discriminatorColumn;
2130 14
        $discrColumnType  = $discrColumn->getType();
2131 14
        $quotedColumnName = $this->platform->quoteIdentifier($discrColumn->getColumnName());
2132 14
        $sqlTableAlias    = $this->useSqlTableAliases
2133 14
            ? $this->getSQLTableAlias($discrColumn->getTableName(), $dqlAlias) . '.'
2134 14
            : '';
2135
2136 14
        return sprintf(
2137 14
            '%s %sIN %s',
2138 14
            $discrColumnType->convertToDatabaseValueSQL($sqlTableAlias . $quotedColumnName, $this->platform),
2139 14
            ($instanceOfExpr->not ? 'NOT ' : ''),
2140 14
            $this->getChildDiscriminatorsFromClassMetadata($discrClass, $instanceOfExpr)
2141
        );
2142
    }
2143
2144
    /**
2145
     * {@inheritdoc}
2146
     */
2147 80
    public function walkInParameter($inParam)
2148
    {
2149 80
        return $inParam instanceof AST\InputParameter
2150 71
            ? $this->walkInputParameter($inParam)
2151 80
            : $this->walkLiteral($inParam);
2152
    }
2153
2154
    /**
2155
     * {@inheritdoc}
2156
     */
2157 163
    public function walkLiteral($literal)
2158
    {
2159 163
        switch ($literal->type) {
2160 163
            case AST\Literal::STRING:
2161 54
                return $this->conn->quote($literal->value);
2162
2163 123
            case AST\Literal::BOOLEAN:
2164 8
                return $this->conn->getDatabasePlatform()->convertBooleans(strtolower($literal->value) === 'true');
2165
2166 116
            case AST\Literal::NUMERIC:
2167 116
                return $literal->value;
2168
2169
            default:
2170
                throw QueryException::invalidLiteral($literal);
2171
        }
2172
    }
2173
2174
    /**
2175
     * {@inheritdoc}
2176
     */
2177 6
    public function walkBetweenExpression($betweenExpr)
2178
    {
2179 6
        $sql = $this->walkArithmeticExpression($betweenExpr->expression);
2180
2181 6
        if ($betweenExpr->not) {
2182 2
            $sql .= ' NOT';
2183
        }
2184
2185 6
        $sql .= ' BETWEEN ' . $this->walkArithmeticExpression($betweenExpr->leftBetweenExpression)
2186 6
            . ' AND ' . $this->walkArithmeticExpression($betweenExpr->rightBetweenExpression);
2187
2188 6
        return $sql;
2189
    }
2190
2191
    /**
2192
     * {@inheritdoc}
2193
     */
2194 9
    public function walkLikeExpression($likeExpr)
2195
    {
2196 9
        $stringExpr = $likeExpr->stringExpression;
2197 9
        $leftExpr   = is_string($stringExpr) && isset($this->queryComponents[$stringExpr]['resultVariable'])
2198 1
            ? $this->walkResultVariable($stringExpr)
2199 9
            : $stringExpr->dispatch($this);
2200
2201 9
        $sql = $leftExpr . ($likeExpr->not ? ' NOT' : '') . ' LIKE ';
2202
2203 9
        if ($likeExpr->stringPattern instanceof AST\InputParameter) {
2204 3
            $sql .= $this->walkInputParameter($likeExpr->stringPattern);
2205 7
        } elseif ($likeExpr->stringPattern instanceof AST\Functions\FunctionNode) {
2206 2
            $sql .= $this->walkFunction($likeExpr->stringPattern);
2207 7
        } elseif ($likeExpr->stringPattern instanceof AST\PathExpression) {
2208 2
            $sql .= $this->walkPathExpression($likeExpr->stringPattern);
2209
        } else {
2210 7
            $sql .= $this->walkLiteral($likeExpr->stringPattern);
2211
        }
2212
2213 9
        if ($likeExpr->escapeChar) {
2214 1
            $sql .= ' ESCAPE ' . $this->walkLiteral($likeExpr->escapeChar);
2215
        }
2216
2217 9
        return $sql;
2218
    }
2219
2220
    /**
2221
     * {@inheritdoc}
2222
     */
2223 5
    public function walkStateFieldPathExpression($stateFieldPathExpression)
2224
    {
2225 5
        return $this->walkPathExpression($stateFieldPathExpression);
2226
    }
2227
2228
    /**
2229
     * {@inheritdoc}
2230
     */
2231 268
    public function walkComparisonExpression($compExpr)
2232
    {
2233 268
        $leftExpr  = $compExpr->leftExpression;
2234 268
        $rightExpr = $compExpr->rightExpression;
2235 268
        $sql       = '';
2236
2237 268
        $sql .= $leftExpr instanceof AST\Node
2238 268
            ? $leftExpr->dispatch($this)
2239 267
            : (is_numeric($leftExpr) ? $leftExpr : $this->conn->quote($leftExpr));
2240
2241 267
        $sql .= ' ' . $compExpr->operator . ' ';
2242
2243 267
        $sql .= $rightExpr instanceof AST\Node
2244 265
            ? $rightExpr->dispatch($this)
2245 267
            : (is_numeric($rightExpr) ? $rightExpr : $this->conn->quote($rightExpr));
2246
2247 267
        return $sql;
2248
    }
2249
2250
    /**
2251
     * {@inheritdoc}
2252
     */
2253 223
    public function walkInputParameter($inputParam)
2254
    {
2255 223
        $this->parserResult->addParameterMapping($inputParam->name, $this->sqlParamIndex++);
2256
2257 223
        $parameter = $this->query->getParameter($inputParam->name);
2258
2259 223
        if ($parameter) {
2260 146
            $type = $parameter->getType();
2261
2262 146
            if (Type::hasType($type)) {
2263 59
                return Type::getType($type)->convertToDatabaseValueSQL('?', $this->platform);
2264
            }
2265
        }
2266
2267 172
        return '?';
2268
    }
2269
2270
    /**
2271
     * {@inheritdoc}
2272
     */
2273 336
    public function walkArithmeticExpression($arithmeticExpr)
2274
    {
2275 336
        return $arithmeticExpr->isSimpleArithmeticExpression()
2276 336
            ? $this->walkSimpleArithmeticExpression($arithmeticExpr->simpleArithmeticExpression)
2277 334
            : '(' . $this->walkSubselect($arithmeticExpr->subselect) . ')';
2278
    }
2279
2280
    /**
2281
     * {@inheritdoc}
2282
     */
2283 401
    public function walkSimpleArithmeticExpression($simpleArithmeticExpr)
2284
    {
2285 401
        if (! ($simpleArithmeticExpr instanceof AST\SimpleArithmeticExpression)) {
2286 350
            return $this->walkArithmeticTerm($simpleArithmeticExpr);
2287
        }
2288
2289 77
        return implode(' ', array_map([$this, 'walkArithmeticTerm'], $simpleArithmeticExpr->arithmeticTerms));
2290
    }
2291
2292
    /**
2293
     * {@inheritdoc}
2294
     */
2295 422
    public function walkArithmeticTerm($term)
2296
    {
2297 422
        if (is_string($term)) {
2298 21
            return isset($this->queryComponents[$term])
2299 6
                ? $this->walkResultVariable($this->queryComponents[$term]['token']['value'])
2300 21
                : $term;
2301
        }
2302
2303
        // Phase 2 AST optimization: Skip processing of ArithmeticTerm
2304
        // if only one ArithmeticFactor is defined
2305 421
        if (! ($term instanceof AST\ArithmeticTerm)) {
2306 399
            return $this->walkArithmeticFactor($term);
2307
        }
2308
2309 47
        return implode(' ', array_map([$this, 'walkArithmeticFactor'], $term->arithmeticFactors));
2310
    }
2311
2312
    /**
2313
     * {@inheritdoc}
2314
     */
2315 422
    public function walkArithmeticFactor($factor)
2316
    {
2317 422
        if (is_string($factor)) {
2318 47
            return isset($this->queryComponents[$factor])
2319 2
                ? $this->walkResultVariable($this->queryComponents[$factor]['token']['value'])
2320 47
                : $factor;
2321
        }
2322
2323
        // Phase 2 AST optimization: Skip processing of ArithmeticFactor
2324
        // if only one ArithmeticPrimary is defined
2325 422
        if (! ($factor instanceof AST\ArithmeticFactor)) {
2326 421
            return $this->walkArithmeticPrimary($factor);
2327
        }
2328
2329 3
        $sign = $factor->isNegativeSigned() ? '-' : ($factor->isPositiveSigned() ? '+' : '');
2330
2331 3
        return $sign . $this->walkArithmeticPrimary($factor->arithmeticPrimary);
2332
    }
2333
2334
    /**
2335
     * Walks down an ArithmeticPrimary that represents an AST node, thereby generating the appropriate SQL.
2336
     *
2337
     * @param mixed $primary
2338
     *
2339
     * @return string The SQL.
2340
     */
2341 422
    public function walkArithmeticPrimary($primary)
2342
    {
2343 422
        if ($primary instanceof AST\SimpleArithmeticExpression) {
2344
            return '(' . $this->walkSimpleArithmeticExpression($primary) . ')';
2345
        }
2346
2347 422
        if ($primary instanceof AST\Node) {
2348 422
            return $primary->dispatch($this);
2349
        }
2350
2351
        return $this->walkEntityIdentificationVariable($primary);
2352
    }
2353
2354
    /**
2355
     * {@inheritdoc}
2356
     */
2357 22
    public function walkStringPrimary($stringPrimary)
2358
    {
2359 22
        return is_string($stringPrimary)
2360
            ? $this->conn->quote($stringPrimary)
2361 22
            : $stringPrimary->dispatch($this);
2362
    }
2363
2364
    /**
2365
     * {@inheritdoc}
2366
     */
2367 32
    public function walkResultVariable($resultVariable)
2368
    {
2369 32
        $resultAlias = $this->scalarResultAliasMap[$resultVariable];
2370
2371 32
        if (is_array($resultAlias)) {
2372 1
            return implode(', ', $resultAlias);
2373
        }
2374
2375 31
        return $resultAlias;
2376
    }
2377
2378
    /**
2379
     * @return string The list in parentheses of valid child discriminators from the given class
2380
     *
2381
     * @throws QueryException
2382
     */
2383 14
    private function getChildDiscriminatorsFromClassMetadata(ClassMetadata $rootClass, AST\InstanceOfExpression $instanceOfExpr) : string
2384
    {
2385 14
        $sqlParameterList = [];
2386 14
        $discriminators   = [];
2387
2388 14
        foreach ($instanceOfExpr->value as $parameter) {
2389 14
            if ($parameter instanceof AST\InputParameter) {
2390 4
                $this->rsm->discriminatorParameters[$parameter->name] = $parameter->name;
2391
2392 4
                $sqlParameterList[] = $this->walkInputParameter($parameter);
2393
2394 4
                continue;
2395
            }
2396
2397
            // Get name from ClassMetadata to resolve aliases.
2398 10
            $entityClass     = $this->em->getClassMetadata($parameter);
2399 10
            $entityClassName = $entityClass->getClassName();
2400
2401 10
            if ($entityClassName !== $rootClass->getClassName()) {
2402 7
                if (! $entityClass->getReflectionClass()->isSubclassOf($rootClass->getClassName())) {
2403 1
                    throw QueryException::instanceOfUnrelatedClass($entityClassName, $rootClass->getClassName());
2404
                }
2405
            }
2406
2407 9
            $discriminators += HierarchyDiscriminatorResolver::resolveDiscriminatorsForClass($entityClass, $this->em);
2408
        }
2409
2410 13
        foreach (array_keys($discriminators) as $discriminator) {
2411 9
            $sqlParameterList[] = $this->conn->quote($discriminator);
2412
        }
2413
2414 13
        return '(' . implode(', ', $sqlParameterList) . ')';
2415
    }
2416
}
2417