Passed
Pull Request — master (#7641)
by
unknown
09:30
created

SqlWalker::walkGroupByItem()   B

Complexity

Conditions 9
Paths 8

Size

Total Lines 48
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 9.0046

Importance

Changes 0
Metric Value
cc 9
eloc 26
nc 8
nop 1
dl 0
loc 48
ccs 25
cts 26
cp 0.9615
crap 9.0046
rs 8.0555
c 0
b 0
f 0
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 717
    public function __construct(AbstractQuery $query, ParserResult $parserResult, array $queryComponents)
166
    {
167 717
        $this->query           = $query;
168 717
        $this->parserResult    = $parserResult;
169 717
        $this->queryComponents = $queryComponents;
170 717
        $this->rsm             = $parserResult->getResultSetMapping();
171 717
        $this->em              = $query->getEntityManager();
172 717
        $this->conn            = $this->em->getConnection();
173 717
        $this->platform        = $this->conn->getDatabasePlatform();
174 717
    }
175
176
    /**
177
     * Gets the Query instance used by the walker.
178
     *
179
     * @return Query.
0 ignored issues
show
Documentation Bug introduced by
The doc comment Query. at position 0 could not be parsed: Unknown type name 'Query.' at position 0 in Query..
Loading history...
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 52
    public function getConnection()
192
    {
193 52
        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 711
    public function getExecutor($AST)
244
    {
245
        switch (true) {
246 711
            case $AST instanceof AST\DeleteStatement:
247 39
                $primaryClass = $this->em->getClassMetadata($AST->deleteClause->abstractSchemaName);
248
249 39
                return $primaryClass->inheritanceType === InheritanceType::JOINED
0 ignored issues
show
Bug introduced by
Accessing inheritanceType on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
250 2
                    ? new Exec\MultiTableDeleteExecutor($AST, $this)
251 39
                    : new Exec\SingleTableDeleteUpdateExecutor($AST, $this);
252 676
            case $AST instanceof AST\UpdateStatement:
253 28
                $primaryClass = $this->em->getClassMetadata($AST->updateClause->abstractSchemaName);
254
255 28
                return $primaryClass->inheritanceType === InheritanceType::JOINED
256 4
                    ? new Exec\MultiTableUpdateExecutor($AST, $this)
257 28
                    : new Exec\SingleTableDeleteUpdateExecutor($AST, $this);
258
            default:
259 652
                return new Exec\SingleSelectExecutor($AST, $this);
260
        }
261
    }
262
263
    /**
264
     * Generates a unique, short SQL table alias.
265
     *
266
     * @param string $tableName Table name
267
     * @param string $dqlAlias  The DQL alias.
268
     *
269
     * @return string Generated table alias.
270
     */
271 663
    public function getSQLTableAlias($tableName, $dqlAlias = '')
272
    {
273 663
        $tableName .= $dqlAlias ? '@[' . $dqlAlias . ']' : '';
274
275 663
        if (! isset($this->tableAliasMap[$tableName])) {
276 663
            $this->tableAliasMap[$tableName] = 't' . $this->tableAliasCounter++;
277
        }
278
279 663
        return $this->tableAliasMap[$tableName];
280
    }
281
282
    /**
283
     * Forces the SqlWalker to use a specific alias for a table name, rather than
284
     * generating an alias on its own.
285
     *
286
     * @param string $tableName
287
     * @param string $alias
288
     * @param string $dqlAlias
289
     *
290
     * @return string
291
     */
292 65
    public function setSQLTableAlias($tableName, $alias, $dqlAlias = '')
293
    {
294 65
        $tableName .= $dqlAlias ? '@[' . $dqlAlias . ']' : '';
295
296 65
        $this->tableAliasMap[$tableName] = $alias;
297
298 65
        return $alias;
299
    }
300
301
    /**
302
     * Gets an SQL column alias for a column name.
303
     *
304
     * @return string
305
     */
306 652
    public function getSQLColumnAlias()
307
    {
308 652
        return $this->platform->getSQLResultCasing('c' . $this->aliasCounter++);
309
    }
310
311
    /**
312
     * Generates the SQL JOINs that are necessary for Class Table Inheritance
313
     * for the given class.
314
     *
315
     * @param ClassMetadata $class    The class for which to generate the joins.
316
     * @param string        $dqlAlias The DQL alias of the class.
317
     *
318
     * @return string The SQL.
319
     */
320 113
    private function generateClassTableInheritanceJoins($class, $dqlAlias)
321
    {
322 113
        $sql = '';
323
324 113
        $baseTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
325
326
        // INNER JOIN parent class tables
327 113
        $parentClass = $class;
328
329 113
        while (($parentClass = $parentClass->getParent()) !== null) {
330 78
            $tableName  = $parentClass->table->getQuotedQualifiedName($this->platform);
331 78
            $tableAlias = $this->getSQLTableAlias($parentClass->getTableName(), $dqlAlias);
0 ignored issues
show
Bug introduced by
The method getTableName() does not exist on Doctrine\ORM\Mapping\ComponentMetadata. It seems like you code against a sub-type of Doctrine\ORM\Mapping\ComponentMetadata such as Doctrine\ORM\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

331
            $tableAlias = $this->getSQLTableAlias($parentClass->/** @scrutinizer ignore-call */ getTableName(), $dqlAlias);
Loading history...
332
333
            // If this is a joined association we must use left joins to preserve the correct result.
334 78
            $sql .= isset($this->queryComponents[$dqlAlias]['relation']) ? ' LEFT ' : ' INNER ';
335 78
            $sql .= 'JOIN ' . $tableName . ' ' . $tableAlias . ' ON ';
336
337 78
            $sqlParts = [];
338
339 78
            foreach ($class->getIdentifierColumns($this->em) as $column) {
340 78
                $quotedColumnName = $this->platform->quoteIdentifier($column->getColumnName());
341
342 78
                $sqlParts[] = $baseTableAlias . '.' . $quotedColumnName . ' = ' . $tableAlias . '.' . $quotedColumnName;
343
            }
344
345 78
            $filterSql = $this->generateFilterConditionSQL($parentClass, $tableAlias);
346
347
            // Add filters on the root class
348 78
            if ($filterSql) {
349 1
                $sqlParts[] = $filterSql;
350
            }
351
352 78
            $sql .= implode(' AND ', $sqlParts);
353
        }
354
355
        // Ignore subclassing inclusion if partial objects is disallowed
356 113
        if ($this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD)) {
357 21
            return $sql;
358
        }
359
360
        // LEFT JOIN child class tables
361 92
        foreach ($class->getSubClasses() as $subClassName) {
362 41
            $subClass   = $this->em->getClassMetadata($subClassName);
363 41
            $tableName  = $subClass->table->getQuotedQualifiedName($this->platform);
0 ignored issues
show
Bug introduced by
Accessing table on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
364 41
            $tableAlias = $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias);
0 ignored issues
show
Bug introduced by
The method getTableName() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

364
            $tableAlias = $this->getSQLTableAlias($subClass->/** @scrutinizer ignore-call */ getTableName(), $dqlAlias);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
365
366 41
            $sql .= ' LEFT JOIN ' . $tableName . ' ' . $tableAlias . ' ON ';
367
368 41
            $sqlParts = [];
369
370 41
            foreach ($subClass->getIdentifierColumns($this->em) as $column) {
0 ignored issues
show
Bug introduced by
The method getIdentifierColumns() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. Did you maybe mean getIdentifier()? ( Ignorable by Annotation )

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

370
            foreach ($subClass->/** @scrutinizer ignore-call */ getIdentifierColumns($this->em) as $column) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
371 41
                $quotedColumnName = $this->platform->quoteIdentifier($column->getColumnName());
372
373 41
                $sqlParts[] = $baseTableAlias . '.' . $quotedColumnName . ' = ' . $tableAlias . '.' . $quotedColumnName;
374
            }
375
376 41
            $sql .= implode(' AND ', $sqlParts);
377
        }
378
379 92
        return $sql;
380
    }
381
382
    /**
383
     * @return string
384
     */
385 646
    private function generateOrderedCollectionOrderByItems()
386
    {
387 646
        $orderedColumns = [];
388
389 646
        foreach ($this->selectedClasses as $selectedClass) {
390 490
            $dqlAlias    = $selectedClass['dqlAlias'];
391 490
            $qComp       = $this->queryComponents[$dqlAlias];
392 490
            $association = $qComp['relation'];
393
394 490
            if (! ($association instanceof ToManyAssociationMetadata)) {
395 490
                continue;
396
            }
397
398 98
            foreach ($association->getOrderBy() as $fieldName => $orientation) {
399 6
                $property      = $qComp['metadata']->getProperty($fieldName);
400 6
                $tableName     = $property->getTableName();
401 6
                $columnName    = $this->platform->quoteIdentifier($property->getColumnName());
402 6
                $orderedColumn = $this->getSQLTableAlias($tableName, $dqlAlias) . '.' . $columnName;
403
404
                // OrderByClause should replace an ordered relation. see - DDC-2475
405 6
                if (isset($this->orderedColumnsMap[$orderedColumn])) {
406 1
                    continue;
407
                }
408
409 6
                $this->orderedColumnsMap[$orderedColumn] = $orientation;
410 6
                $orderedColumns[]                        = $orderedColumn . ' ' . $orientation;
411
            }
412
        }
413
414 646
        return implode(', ', $orderedColumns);
415
    }
416
417
    /**
418
     * Generates a discriminator column SQL condition for the class with the given DQL alias.
419
     *
420
     * @param string[] $dqlAliases List of root DQL aliases to inspect for discriminator restrictions.
421
     *
422
     * @return string
423
     */
424 706
    private function generateDiscriminatorColumnConditionSQL(array $dqlAliases)
425
    {
426 706
        $sqlParts = [];
427
428 706
        foreach ($dqlAliases as $dqlAlias) {
429 706
            $class = $this->queryComponents[$dqlAlias]['metadata'];
430
431 706
            if ($class->inheritanceType !== InheritanceType::SINGLE_TABLE) {
432 680
                continue;
433
            }
434
435 41
            $conn   = $this->em->getConnection();
436 41
            $values = [];
437
438 41
            if ($class->discriminatorValue !== null) { // discriminators can be 0
439 21
                $values[] = $conn->quote($class->discriminatorValue);
440
            }
441
442 41
            foreach ($class->getSubClasses() as $subclassName) {
443 30
                $values[] = $conn->quote($this->em->getClassMetadata($subclassName)->discriminatorValue);
0 ignored issues
show
Bug introduced by
Accessing discriminatorValue on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
444
            }
445
446 41
            $discrColumn      = $class->discriminatorColumn;
447 41
            $discrColumnType  = $discrColumn->getType();
448 41
            $quotedColumnName = $this->platform->quoteIdentifier($discrColumn->getColumnName());
449 41
            $sqlTableAlias    = $this->useSqlTableAliases
450 36
                ? $this->getSQLTableAlias($discrColumn->getTableName(), $dqlAlias) . '.'
451 41
                : '';
452
453 41
            $sqlParts[] = sprintf(
454 41
                '%s IN (%s)',
455 41
                $discrColumnType->convertToDatabaseValueSQL($sqlTableAlias . $quotedColumnName, $this->platform),
456 41
                implode(', ', $values)
457
            );
458
        }
459
460 706
        $sql = implode(' AND ', $sqlParts);
461
462 706
        return isset($sqlParts[1]) ? '(' . $sql . ')' : $sql;
463
    }
464
465
    /**
466
     * Generates the filter SQL for a given entity and table alias.
467
     *
468
     * @param ClassMetadata $targetEntity     Metadata of the target entity.
469
     * @param string        $targetTableAlias The table alias of the joined/selected table.
470
     *
471
     * @return string The SQL query part to add to a query.
472
     */
473 330
    private function generateFilterConditionSQL(ClassMetadata $targetEntity, $targetTableAlias)
474
    {
475 330
        if (! $this->em->hasFilters()) {
476 294
            return '';
477
        }
478
479 41
        switch ($targetEntity->inheritanceType) {
480 41
            case InheritanceType::NONE:
481 31
                break;
482
483 10
            case InheritanceType::JOINED:
484
                // The classes in the inheritance will be added to the query one by one,
485
                // but only the root node is getting filtered
486 6
                if ($targetEntity->getClassName() !== $targetEntity->getRootClassName()) {
487 4
                    return '';
488
                }
489 6
                break;
490
491 4
            case InheritanceType::SINGLE_TABLE:
492
                // With STI the table will only be queried once, make sure that the filters
493
                // are added to the root entity
494 4
                $targetEntity = $this->em->getClassMetadata($targetEntity->getRootClassName());
495 4
                break;
496
497
            default:
498
                //@todo: throw exception?
499
                return '';
500
        }
501
502 41
        $filterClauses = [];
503
504 41
        foreach ($this->em->getFilters()->getEnabledFilters() as $filter) {
505 10
            $filterExpr = $filter->addFilterConstraint($targetEntity, $targetTableAlias);
506
507 10
            if ($filterExpr !== '') {
508 9
                $filterClauses[] = '(' . $filterExpr . ')';
509
            }
510
        }
511
512 41
        return implode(' AND ', $filterClauses);
513
    }
514
515
    /**
516
     * {@inheritdoc}
517
     */
518 652
    public function walkSelectStatement(AST\SelectStatement $AST)
519
    {
520 652
        $limit    = $this->query->getMaxResults();
0 ignored issues
show
Bug introduced by
The method getMaxResults() does not exist on Doctrine\ORM\AbstractQuery. Did you maybe mean getResult()? ( Ignorable by Annotation )

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

520
        /** @scrutinizer ignore-call */ 
521
        $limit    = $this->query->getMaxResults();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
521 652
        $offset   = $this->query->getFirstResult();
0 ignored issues
show
Bug introduced by
The method getFirstResult() does not exist on Doctrine\ORM\AbstractQuery. It seems like you code against a sub-type of Doctrine\ORM\AbstractQuery such as Doctrine\ORM\Query. ( Ignorable by Annotation )

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

521
        /** @scrutinizer ignore-call */ 
522
        $offset   = $this->query->getFirstResult();
Loading history...
522 652
        $lockMode = $this->query->getHint(Query::HINT_LOCK_MODE);
523 652
        $sql      = $this->walkSelectClause($AST->selectClause)
524 652
            . $this->walkFromClause($AST->fromClause)
525 650
            . $this->walkWhereClause($AST->whereClause);
526
527 647
        if ($AST->groupByClause) {
528 27
            $sql .= $this->walkGroupByClause($AST->groupByClause);
529
        }
530
531 647
        if ($AST->havingClause) {
532 14
            $sql .= $this->walkHavingClause($AST->havingClause);
533
        }
534
535 647
        if ($AST->orderByClause) {
536 144
            $sql .= $this->walkOrderByClause($AST->orderByClause);
537
        }
538
539 646
        if (! $AST->orderByClause) {
540 533
            $orderBySql = $this->generateOrderedCollectionOrderByItems();
541
542 533
            if ($orderBySql) {
543 6
                $sql .= ' ORDER BY ' . $orderBySql;
544
            }
545
        }
546
547 646
        if ($limit !== null || $offset !== null) {
548 52
            $sql = $this->platform->modifyLimitQuery($sql, $limit, $offset ?? 0);
549
        }
550
551 646
        if ($lockMode === null || $lockMode === false || $lockMode === LockMode::NONE) {
552 641
            return $sql;
553
        }
554
555 5
        if ($lockMode === LockMode::PESSIMISTIC_READ) {
556 3
            return $sql . ' ' . $this->platform->getReadLockSQL();
557
        }
558
559 2
        if ($lockMode === LockMode::PESSIMISTIC_WRITE) {
560 1
            return $sql . ' ' . $this->platform->getWriteLockSQL();
561
        }
562
563 1
        if ($lockMode !== LockMode::OPTIMISTIC) {
564
            throw QueryException::invalidLockMode();
565
        }
566
567 1
        foreach ($this->selectedClasses as $selectedClass) {
568 1
            if (! $selectedClass['class']->isVersioned()) {
569 1
                throw OptimisticLockException::lockFailed($selectedClass['class']->getClassName());
570
            }
571
        }
572
573
        return $sql;
574
    }
575
576
    /**
577
     * {@inheritdoc}
578
     */
579 24
    public function walkUpdateStatement(AST\UpdateStatement $AST)
580
    {
581 24
        $this->useSqlTableAliases = false;
582 24
        $this->rsm->isSelect      = false;
583
584 24
        return $this->walkUpdateClause($AST->updateClause)
585 24
            . $this->walkWhereClause($AST->whereClause);
586
    }
587
588
    /**
589
     * {@inheritdoc}
590
     */
591 37
    public function walkDeleteStatement(AST\DeleteStatement $AST)
592
    {
593 37
        $this->useSqlTableAliases = false;
594 37
        $this->rsm->isSelect      = false;
595
596 37
        return $this->walkDeleteClause($AST->deleteClause)
597 37
            . $this->walkWhereClause($AST->whereClause);
598
    }
599
600
    /**
601
     * Walks down an IdentificationVariable AST node, thereby generating the appropriate SQL.
602
     * This one differs of ->walkIdentificationVariable() because it generates the entity identifiers.
603
     *
604
     * @param string $identVariable
605
     *
606
     * @return string
607
     */
608 2
    public function walkEntityIdentificationVariable($identVariable)
609
    {
610 2
        $class      = $this->queryComponents[$identVariable]['metadata'];
611 2
        $tableAlias = $this->getSQLTableAlias($class->getTableName(), $identVariable);
612 2
        $sqlParts   = [];
613
614 2
        foreach ($class->getIdentifierColumns($this->em) as $column) {
615 2
            $quotedColumnName = $this->platform->quoteIdentifier($column->getColumnName());
616
617 2
            $sqlParts[] = $tableAlias . '.' . $quotedColumnName;
618
        }
619
620 2
        return implode(', ', $sqlParts);
621
    }
622
623
    /**
624
     * Walks down an IdentificationVariable (no AST node associated), thereby generating the SQL.
625
     *
626
     * @param string $identificationVariable
627
     * @param string $fieldName
628
     *
629
     * @return string The SQL.
630
     */
631 435
    public function walkIdentificationVariable($identificationVariable, $fieldName = null)
632
    {
633 435
        $class = $this->queryComponents[$identificationVariable]['metadata'];
634
635 435
        if (! $fieldName) {
636
            return $this->getSQLTableAlias($class->getTableName(), $identificationVariable);
637
        }
638
639 435
        $property = $class->getProperty($fieldName);
640
641 435
        if ($class->inheritanceType === InheritanceType::JOINED && $class->isInheritedProperty($fieldName)) {
642 38
            $class = $property->getDeclaringClass();
643
        }
644
645 435
        return $this->getSQLTableAlias($class->getTableName(), $identificationVariable);
646
    }
647
648
    /**
649
     * {@inheritdoc}
650
     */
651 503
    public function walkPathExpression($pathExpr)
652
    {
653 503
        $sql = '';
654
655
        /** @var Query\AST\PathExpression $pathExpr */
656 503
        switch ($pathExpr->type) {
657 503
            case AST\PathExpression::TYPE_STATE_FIELD:
658 482
                $fieldName = $pathExpr->field;
659 482
                $dqlAlias  = $pathExpr->identificationVariable;
660 482
                $class     = $this->queryComponents[$dqlAlias]['metadata'];
661 482
                $property  = $class->getProperty($fieldName);
662
663 482
                if ($this->useSqlTableAliases) {
664 435
                    $sql .= $this->walkIdentificationVariable($dqlAlias, $fieldName) . '.';
665
                }
666
667 482
                $sql .= $this->platform->quoteIdentifier($property->getColumnName());
668 482
                break;
669
670 63
            case AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION:
671
                // 1- the owning side:
672
                //    Just use the foreign key, i.e. u.group_id
673 63
                $fieldName   = $pathExpr->field;
674 63
                $dqlAlias    = $pathExpr->identificationVariable;
675 63
                $class       = $this->queryComponents[$dqlAlias]['metadata'];
676 63
                $association = $class->getProperty($fieldName);
677
678 63
                if (! $association->isOwningSide()) {
679 2
                    throw QueryException::associationPathInverseSideNotSupported($pathExpr);
680
                }
681
682 61
                $joinColumns = $association->getJoinColumns();
683
684
                // COMPOSITE KEYS NOT (YET?) SUPPORTED
685 61
                if (count($joinColumns) > 1) {
686 1
                    throw QueryException::associationPathCompositeKeyNotSupported();
687
                }
688
689 60
                $joinColumn = reset($joinColumns);
690
691 60
                if ($this->useSqlTableAliases) {
692 57
                    $sql .= $this->getSQLTableAlias($joinColumn->getTableName(), $dqlAlias) . '.';
693
                }
694
695 60
                $sql .= $this->platform->quoteIdentifier($joinColumn->getColumnName());
696 60
                break;
697
698
            default:
699
                throw QueryException::invalidPathExpression($pathExpr);
700
        }
701
702 500
        return $sql;
703
    }
704
705
    /**
706
     * {@inheritdoc}
707
     */
708 652
    public function walkSelectClause($selectClause)
709
    {
710 652
        $sql                  = 'SELECT ' . ($selectClause->isDistinct ? 'DISTINCT ' : '');
711 652
        $sqlSelectExpressions = array_filter(array_map([$this, 'walkSelectExpression'], $selectClause->selectExpressions));
712
713 652
        if ($this->query->getHint(Query::HINT_INTERNAL_ITERATION) === true && $selectClause->isDistinct) {
714 1
            $this->query->setHint(self::HINT_DISTINCT, true);
715
        }
716
717
        $addMetaColumns = (
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: $addMetaColumns = (! $th..._INCLUDE_META_COLUMNS)), Probably Intended Meaning: $addMetaColumns = ! $thi..._INCLUDE_META_COLUMNS))
Loading history...
718 652
            ! $this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD) &&
719 482
            $this->query->getHydrationMode() === Query::HYDRATE_OBJECT
720
        ) || (
721 311
            $this->query->getHydrationMode() !== Query::HYDRATE_OBJECT &&
722 652
            $this->query->getHint(Query::HINT_INCLUDE_META_COLUMNS)
723
        );
724
725 652
        foreach ($this->selectedClasses as $selectedClass) {
726 496
            $class       = $selectedClass['class'];
727 496
            $dqlAlias    = $selectedClass['dqlAlias'];
728 496
            $resultAlias = $selectedClass['resultAlias'];
729
730
            // Register as entity or joined entity result
731 496
            if ($this->queryComponents[$dqlAlias]['relation'] === null) {
732 496
                $this->rsm->addEntityResult($class->getClassName(), $dqlAlias, $resultAlias);
733
            } else {
734 157
                $this->rsm->addJoinedEntityResult(
735 157
                    $class->getClassName(),
736 157
                    $dqlAlias,
737 157
                    $this->queryComponents[$dqlAlias]['parent'],
738 157
                    $this->queryComponents[$dqlAlias]['relation']->getName()
739
                );
740
            }
741
742 496
            if ($class->inheritanceType === InheritanceType::SINGLE_TABLE || $class->inheritanceType === InheritanceType::JOINED) {
743
                // Add discriminator columns to SQL
744 99
                $discrColumn      = $class->discriminatorColumn;
745 99
                $discrColumnName  = $discrColumn->getColumnName();
746 99
                $discrColumnType  = $discrColumn->getType();
747 99
                $quotedColumnName = $this->platform->quoteIdentifier($discrColumnName);
748 99
                $sqlTableAlias    = $this->getSQLTableAlias($discrColumn->getTableName(), $dqlAlias);
749 99
                $sqlColumnAlias   = $this->getSQLColumnAlias();
750
751 99
                $sqlSelectExpressions[] = sprintf(
752 99
                    '%s AS %s',
753 99
                    $discrColumnType->convertToDatabaseValueSQL($sqlTableAlias . '.' . $quotedColumnName, $this->platform),
754 99
                    $sqlColumnAlias
755
                );
756
757 99
                $this->rsm->setDiscriminatorColumn($dqlAlias, $sqlColumnAlias);
758 99
                $this->rsm->addMetaResult($dqlAlias, $sqlColumnAlias, $discrColumnName, false, $discrColumnType);
759
            }
760
761
            // Add foreign key columns of class and also parent classes
762 496
            foreach ($class->getDeclaredPropertiesIterator() as $association) {
763 496
                if (! ($association instanceof ToOneAssociationMetadata && $association->isOwningSide())
764 496
                    || ( ! $addMetaColumns && ! $association->isPrimaryKey())) {
765 495
                    continue;
766
                }
767
768 280
                $targetClass = $this->em->getClassMetadata($association->getTargetEntity());
769
770 280
                foreach ($association->getJoinColumns() as $joinColumn) {
771
                    /** @var JoinColumnMetadata $joinColumn */
772 280
                    $columnName           = $joinColumn->getColumnName();
773 280
                    $referencedColumnName = $joinColumn->getReferencedColumnName();
774 280
                    $quotedColumnName     = $this->platform->quoteIdentifier($columnName);
775 280
                    $columnAlias          = $this->getSQLColumnAlias();
776 280
                    $sqlTableAlias        = $this->getSQLTableAlias($joinColumn->getTableName(), $dqlAlias);
777
778 280
                    if (! $joinColumn->getType()) {
779 20
                        $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em));
780
                    }
781
782 280
                    $sqlSelectExpressions[] = sprintf(
783 280
                        '%s.%s AS %s',
784 280
                        $sqlTableAlias,
785 280
                        $quotedColumnName,
786 280
                        $columnAlias
787
                    );
788
789 280
                    $this->rsm->addMetaResult($dqlAlias, $columnAlias, $columnName, $association->isPrimaryKey(), $joinColumn->getType());
0 ignored issues
show
Bug introduced by
Are you sure the usage of $joinColumn->getType() targeting Doctrine\ORM\Mapping\ColumnMetadata::getType() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
790
                }
791
            }
792
793
            // Add foreign key columns to SQL, if necessary
794 496
            if (! $addMetaColumns) {
795 186
                continue;
796
            }
797
798
            // Add foreign key columns of subclasses
799 350
            foreach ($class->getSubClasses() as $subClassName) {
800 38
                $subClass = $this->em->getClassMetadata($subClassName);
801
802 38
                foreach ($subClass->getDeclaredPropertiesIterator() as $association) {
0 ignored issues
show
Bug introduced by
The method getDeclaredPropertiesIterator() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

802
                foreach ($subClass->/** @scrutinizer ignore-call */ getDeclaredPropertiesIterator() as $association) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
803
                    // Skip if association is inherited
804 38
                    if ($subClass->isInheritedProperty($association->getName())) {
0 ignored issues
show
Bug introduced by
The method isInheritedProperty() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

804
                    if ($subClass->/** @scrutinizer ignore-call */ isInheritedProperty($association->getName())) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
805 38
                        continue;
806
                    }
807
808 28
                    if (! ($association instanceof ToOneAssociationMetadata && $association->isOwningSide())) {
809 27
                        continue;
810
                    }
811
812 14
                    $targetClass = $this->em->getClassMetadata($association->getTargetEntity());
813
814 14
                    foreach ($association->getJoinColumns() as $joinColumn) {
815
                        /** @var JoinColumnMetadata $joinColumn */
816 14
                        $columnName           = $joinColumn->getColumnName();
817 14
                        $referencedColumnName = $joinColumn->getReferencedColumnName();
818 14
                        $quotedColumnName     = $this->platform->quoteIdentifier($columnName);
819 14
                        $columnAlias          = $this->getSQLColumnAlias();
820 14
                        $sqlTableAlias        = $this->getSQLTableAlias($joinColumn->getTableName(), $dqlAlias);
821
822 14
                        if (! $joinColumn->getType()) {
823 1
                            $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $this->em));
824
                        }
825
826 14
                        $sqlSelectExpressions[] = sprintf(
827 14
                            '%s.%s AS %s',
828 14
                            $sqlTableAlias,
829 14
                            $quotedColumnName,
830 14
                            $columnAlias
831
                        );
832
833 14
                        $this->rsm->addMetaResult($dqlAlias, $columnAlias, $columnName, $association->isPrimaryKey(), $joinColumn->getType());
834
                    }
835
                }
836
            }
837
        }
838
839 652
        return $sql . implode(', ', $sqlSelectExpressions);
840
    }
841
842
    /**
843
     * {@inheritdoc}
844
     */
845 654
    public function walkFromClause($fromClause)
846
    {
847 654
        $identificationVarDecls = $fromClause->identificationVariableDeclarations;
848 654
        $sqlParts               = [];
849
850 654
        foreach ($identificationVarDecls as $identificationVariableDecl) {
851 654
            $sqlParts[] = $this->walkIdentificationVariableDeclaration($identificationVariableDecl);
852
        }
853
854 652
        return ' FROM ' . implode(', ', $sqlParts);
855
    }
856
857
    /**
858
     * Walks down a IdentificationVariableDeclaration AST node, thereby generating the appropriate SQL.
859
     *
860
     * @param AST\IdentificationVariableDeclaration $identificationVariableDecl
861
     *
862
     * @return string
863
     */
864 655
    public function walkIdentificationVariableDeclaration($identificationVariableDecl)
865
    {
866 655
        $sql = $this->walkRangeVariableDeclaration($identificationVariableDecl->rangeVariableDeclaration);
867
868 655
        if ($identificationVariableDecl->indexBy) {
869 5
            $this->walkIndexBy($identificationVariableDecl->indexBy);
870
        }
871
872 655
        foreach ($identificationVariableDecl->joins as $join) {
873 245
            $sql .= $this->walkJoin($join);
874
        }
875
876 653
        return $sql;
877
    }
878
879
    /**
880
     * Walks down a IndexBy AST node.
881
     *
882
     * @param AST\IndexBy $indexBy
883
     */
884 8
    public function walkIndexBy($indexBy)
885
    {
886 8
        $pathExpression = $indexBy->simpleStateFieldPathExpression;
887 8
        $alias          = $pathExpression->identificationVariable;
888 8
        $field          = $pathExpression->field;
889
890 8
        if (isset($this->scalarFields[$alias][$field])) {
891
            $this->rsm->addIndexByScalar($this->scalarFields[$alias][$field]);
892
893
            return;
894
        }
895
896 8
        $this->rsm->addIndexBy($alias, $field);
897 8
    }
898
899
    /**
900
     * Walks down a RangeVariableDeclaration AST node, thereby generating the appropriate SQL.
901
     *
902
     * @param AST\RangeVariableDeclaration $rangeVariableDeclaration
903
     *
904
     * @return string
905
     */
906 655
    public function walkRangeVariableDeclaration($rangeVariableDeclaration)
907
    {
908 655
        return $this->generateRangeVariableDeclarationSQL($rangeVariableDeclaration, false);
909
    }
910
911
    /**
912
     * Generate appropriate SQL for RangeVariableDeclaration AST node
913
     *
914
     * @param AST\RangeVariableDeclaration $rangeVariableDeclaration
915
     */
916 655
    private function generateRangeVariableDeclarationSQL($rangeVariableDeclaration, bool $buildNestedJoins) : string
917
    {
918 655
        $class    = $this->em->getClassMetadata($rangeVariableDeclaration->abstractSchemaName);
919 655
        $dqlAlias = $rangeVariableDeclaration->aliasIdentificationVariable;
920
921 655
        if ($rangeVariableDeclaration->isRoot) {
922 655
            $this->rootAliases[] = $dqlAlias;
923
        }
924
925 655
        $tableName  = $class->table->getQuotedQualifiedName($this->platform);
0 ignored issues
show
Bug introduced by
Accessing table on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
926 655
        $tableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
927
928 655
        $sql = $this->platform->appendLockHint(
929 655
            $tableName . ' ' . $tableAlias,
930 655
            $this->query->getHint(Query::HINT_LOCK_MODE)
0 ignored issues
show
Bug introduced by
It seems like $this->query->getHint(Do...\Query::HINT_LOCK_MODE) can also be of type false; however, parameter $lockMode of Doctrine\DBAL\Platforms\...tform::appendLockHint() does only seem to accept integer|null, 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

930
            /** @scrutinizer ignore-type */ $this->query->getHint(Query::HINT_LOCK_MODE)
Loading history...
931
        );
932
933 655
        if ($class->inheritanceType !== InheritanceType::JOINED) {
0 ignored issues
show
Bug introduced by
Accessing inheritanceType on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
934 554
            return $sql;
935
        }
936
937 109
        $classTableInheritanceJoins = $this->generateClassTableInheritanceJoins($class, $dqlAlias);
938
939 109
        if (! $buildNestedJoins) {
940 107
            return $sql . $classTableInheritanceJoins;
941
        }
942
943 3
        return $classTableInheritanceJoins === '' ? $sql : '(' . $sql . $classTableInheritanceJoins . ')';
944
    }
945
946
    /**
947
     * Walks down a JoinAssociationDeclaration AST node, thereby generating the appropriate SQL.
948
     *
949
     * @param AST\JoinAssociationDeclaration $joinAssociationDeclaration
950
     * @param int                            $joinType
951
     * @param AST\ConditionalExpression      $condExpr
952
     *
953
     * @return string
954
     *
955
     * @throws QueryException
956
     */
957 228
    public function walkJoinAssociationDeclaration($joinAssociationDeclaration, $joinType = AST\Join::JOIN_TYPE_INNER, $condExpr = null)
958
    {
959 228
        $sql = '';
960
961 228
        $associationPathExpression = $joinAssociationDeclaration->joinAssociationPathExpression;
962 228
        $joinedDqlAlias            = $joinAssociationDeclaration->aliasIdentificationVariable;
963 228
        $indexBy                   = $joinAssociationDeclaration->indexBy;
964
965 228
        $association     = $this->queryComponents[$joinedDqlAlias]['relation'];
966 228
        $targetClass     = $this->em->getClassMetadata($association->getTargetEntity());
967 228
        $sourceClass     = $this->em->getClassMetadata($association->getSourceEntity());
968 228
        $targetTableName = $targetClass->table->getQuotedQualifiedName($this->platform);
0 ignored issues
show
Bug introduced by
Accessing table on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
969
970 228
        $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName(), $joinedDqlAlias);
971 228
        $sourceTableAlias = $this->getSQLTableAlias($sourceClass->getTableName(), $associationPathExpression->identificationVariable);
972
973
        // Ensure we got the owning side, since it has all mapping info
974 228
        $owningAssociation = ! $association->isOwningSide()
975 118
            ? $targetClass->getProperty($association->getMappedBy())
0 ignored issues
show
Bug introduced by
The method getProperty() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

975
            ? $targetClass->/** @scrutinizer ignore-call */ getProperty($association->getMappedBy())

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
976 228
            : $association;
977
978 228
        if ($this->query->getHint(Query::HINT_INTERNAL_ITERATION) === true &&
979 228
            (! $this->query->getHint(self::HINT_DISTINCT) || isset($this->selectedClasses[$joinedDqlAlias]))) {
980 3
            if ($association instanceof ToManyAssociationMetadata) {
981 2
                throw QueryException::iterateWithFetchJoinNotAllowed($owningAssociation);
982
            }
983
        }
984
985 226
        $targetTableJoin = null;
986
987
        // This condition is not checking ManyToOneAssociationMetadata, because by definition it cannot
988
        // be the owning side and previously we ensured that $assoc is always the owning side of the associations.
989
        // The owning side is necessary at this point because only it contains the JoinColumn information.
990 226
        if ($owningAssociation instanceof ToOneAssociationMetadata) {
991 179
            $conditions = [];
992
993 179
            foreach ($owningAssociation->getJoinColumns() as $joinColumn) {
994 179
                $quotedColumnName           = $this->platform->quoteIdentifier($joinColumn->getColumnName());
995 179
                $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName());
996
997 179
                if ($association->isOwningSide()) {
998 103
                    $conditions[] = sprintf(
999 103
                        '%s.%s = %s.%s',
1000 103
                        $sourceTableAlias,
1001 103
                        $quotedColumnName,
1002 103
                        $targetTableAlias,
1003 103
                        $quotedReferencedColumnName
1004
                    );
1005
1006 103
                    continue;
1007
                }
1008
1009 107
                $conditions[] = sprintf(
1010 107
                    '%s.%s = %s.%s',
1011 107
                    $sourceTableAlias,
1012 107
                    $quotedReferencedColumnName,
1013 107
                    $targetTableAlias,
1014 107
                    $quotedColumnName
1015
                );
1016
            }
1017
1018
            // Apply remaining inheritance restrictions
1019 179
            $discrSql = $this->generateDiscriminatorColumnConditionSQL([$joinedDqlAlias]);
1020
1021 179
            if ($discrSql) {
1022 3
                $conditions[] = $discrSql;
1023
            }
1024
1025
            // Apply the filters
1026 179
            $filterExpr = $this->generateFilterConditionSQL($targetClass, $targetTableAlias);
1027
1028 179
            if ($filterExpr) {
1029 1
                $conditions[] = $filterExpr;
1030
            }
1031
1032
            $targetTableJoin = [
1033 179
                'table' => $targetTableName . ' ' . $targetTableAlias,
1034 179
                'condition' => implode(' AND ', $conditions),
1035
            ];
1036 57
        } elseif ($owningAssociation instanceof ManyToManyAssociationMetadata) {
1037
            // Join relation table
1038 57
            $joinTable      = $owningAssociation->getJoinTable();
1039 57
            $joinTableName  = $joinTable->getQuotedQualifiedName($this->platform);
1040 57
            $joinTableAlias = $this->getSQLTableAlias($joinTable->getName(), $joinedDqlAlias);
1041
1042 57
            $conditions  = [];
1043 57
            $joinColumns = $association->isOwningSide()
1044 48
                ? $joinTable->getJoinColumns()
1045 57
                : $joinTable->getInverseJoinColumns();
1046
1047 57
            foreach ($joinColumns as $joinColumn) {
1048 57
                $quotedColumnName           = $this->platform->quoteIdentifier($joinColumn->getColumnName());
1049 57
                $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName());
1050
1051 57
                $conditions[] = sprintf(
1052 57
                    '%s.%s = %s.%s',
1053 57
                    $sourceTableAlias,
1054 57
                    $quotedReferencedColumnName,
1055 57
                    $joinTableAlias,
1056 57
                    $quotedColumnName
1057
                );
1058
            }
1059
1060 57
            $sql .= $joinTableName . ' ' . $joinTableAlias . ' ON ' . implode(' AND ', $conditions);
1061
1062
            // Join target table
1063 57
            $sql .= $joinType === AST\Join::JOIN_TYPE_LEFT || $joinType === AST\Join::JOIN_TYPE_LEFTOUTER ? ' LEFT JOIN ' : ' INNER JOIN ';
1064
1065 57
            $conditions  = [];
1066 57
            $joinColumns = $association->isOwningSide()
1067 48
                ? $joinTable->getInverseJoinColumns()
1068 57
                : $joinTable->getJoinColumns();
1069
1070 57
            foreach ($joinColumns as $joinColumn) {
1071 57
                $quotedColumnName           = $this->platform->quoteIdentifier($joinColumn->getColumnName());
1072 57
                $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName());
1073
1074 57
                $conditions[] = sprintf(
1075 57
                    '%s.%s = %s.%s',
1076 57
                    $targetTableAlias,
1077 57
                    $quotedReferencedColumnName,
1078 57
                    $joinTableAlias,
1079 57
                    $quotedColumnName
1080
                );
1081
            }
1082
1083
            // Apply remaining inheritance restrictions
1084 57
            $discrSql = $this->generateDiscriminatorColumnConditionSQL([$joinedDqlAlias]);
1085
1086 57
            if ($discrSql) {
1087 1
                $conditions[] = $discrSql;
1088
            }
1089
1090
            // Apply the filters
1091 57
            $filterExpr = $this->generateFilterConditionSQL($targetClass, $targetTableAlias);
1092
1093 57
            if ($filterExpr) {
1094 1
                $conditions[] = $filterExpr;
1095
            }
1096
1097
            $targetTableJoin = [
1098 57
                'table' => $targetTableName . ' ' . $targetTableAlias,
1099 57
                'condition' => implode(' AND ', $conditions),
1100
            ];
1101
        } else {
1102
            throw new BadMethodCallException('Type of association must be one of *_TO_ONE or MANY_TO_MANY');
1103
        }
1104
1105
        // Handle WITH clause
1106 226
        $withCondition = $condExpr === null ? '' : ('(' . $this->walkConditionalExpression($condExpr) . ')');
1107
1108 226
        if ($targetClass->inheritanceType === InheritanceType::JOINED) {
0 ignored issues
show
Bug introduced by
Accessing inheritanceType on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1109 10
            $ctiJoins = $this->generateClassTableInheritanceJoins($targetClass, $joinedDqlAlias);
1110
1111
            // If we have WITH condition, we need to build nested joins for target class table and cti joins
1112 10
            if ($withCondition) {
1113 1
                $sql .= '(' . $targetTableJoin['table'] . $ctiJoins . ') ON ' . $targetTableJoin['condition'];
1114
            } else {
1115 10
                $sql .= $targetTableJoin['table'] . ' ON ' . $targetTableJoin['condition'] . $ctiJoins;
1116
            }
1117
        } else {
1118 216
            $sql .= $targetTableJoin['table'] . ' ON ' . $targetTableJoin['condition'];
1119
        }
1120
1121 226
        if ($withCondition) {
1122 6
            $sql .= ' AND ' . $withCondition;
1123
        }
1124
1125
        // Apply the indexes
1126 226
        if ($indexBy) {
1127
            // For Many-To-One or One-To-One associations this obviously makes no sense, but is ignored silently.
1128 5
            $this->walkIndexBy($indexBy);
1129 221
        } elseif ($association instanceof ToManyAssociationMetadata && $association->getIndexedBy()) {
1130 3
            $this->rsm->addIndexBy($joinedDqlAlias, $association->getIndexedBy());
1131
        }
1132
1133 226
        return $sql;
1134
    }
1135
1136
    /**
1137
     * {@inheritdoc}
1138
     */
1139 138
    public function walkFunction($function)
1140
    {
1141 138
        return $function->getSql($this);
1142
    }
1143
1144
    /**
1145
     * {@inheritdoc}
1146
     */
1147 155
    public function walkOrderByClause($orderByClause)
1148
    {
1149 155
        $orderByItems           = array_map([$this, 'walkOrderByItem'], $orderByClause->orderByItems);
1150 154
        $collectionOrderByItems = $this->generateOrderedCollectionOrderByItems();
1151
1152 154
        if ($collectionOrderByItems !== '') {
1153
            $orderByItems = array_merge($orderByItems, (array) $collectionOrderByItems);
1154
        }
1155
1156 154
        return ' ORDER BY ' . implode(', ', $orderByItems);
1157
    }
1158
1159
    /**
1160
     * {@inheritdoc}
1161
     */
1162 173
    public function walkOrderByItem($orderByItem)
1163
    {
1164 173
        $type = strtoupper($orderByItem->type);
1165 173
        $expr = $orderByItem->expression;
1166 173
        $sql  = $expr instanceof AST\Node
1167 164
            ? $expr->dispatch($this)
1168 172
            : $this->walkResultVariable($this->queryComponents[$expr]['token']['value']);
1169
1170 172
        $this->orderedColumnsMap[$sql] = $type;
1171
1172 172
        if ($expr instanceof AST\Subselect) {
1173 2
            return '(' . $sql . ') ' . $type;
1174
        }
1175
1176 170
        return $sql . ' ' . $type;
1177
    }
1178
1179
    /**
1180
     * {@inheritdoc}
1181
     */
1182 14
    public function walkHavingClause($havingClause)
1183
    {
1184 14
        return ' HAVING ' . $this->walkConditionalExpression($havingClause->conditionalExpression);
1185
    }
1186
1187
    /**
1188
     * {@inheritdoc}
1189
     */
1190 245
    public function walkJoin($join)
1191
    {
1192 245
        $joinType        = $join->joinType;
1193 245
        $joinDeclaration = $join->joinAssociationDeclaration;
1194
1195 245
        $sql = $joinType === AST\Join::JOIN_TYPE_LEFT || $joinType === AST\Join::JOIN_TYPE_LEFTOUTER
1196 57
            ? ' LEFT JOIN '
1197 245
            : ' INNER JOIN ';
1198
1199
        switch (true) {
1200 245
            case $joinDeclaration instanceof AST\RangeVariableDeclaration:
1201 18
                $class      = $this->em->getClassMetadata($joinDeclaration->abstractSchemaName);
1202 18
                $dqlAlias   = $joinDeclaration->aliasIdentificationVariable;
1203 18
                $tableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
1204 18
                $conditions = [];
1205
1206 18
                if ($join->conditionalExpression) {
1207 16
                    $conditions[] = '(' . $this->walkConditionalExpression($join->conditionalExpression) . ')';
1208
                }
1209
1210 18
                $isUnconditionalJoin = empty($conditions);
1211 18
                $condExprConjunction = $class->inheritanceType === InheritanceType::JOINED && $joinType !== AST\Join::JOIN_TYPE_LEFT && $joinType !== AST\Join::JOIN_TYPE_LEFTOUTER && $isUnconditionalJoin
0 ignored issues
show
Bug introduced by
Accessing inheritanceType on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1212 2
                    ? ' AND '
1213 18
                    : ' ON ';
1214
1215 18
                $sql .= $this->generateRangeVariableDeclarationSQL($joinDeclaration, ! $isUnconditionalJoin);
1216
1217
                // Apply remaining inheritance restrictions
1218 18
                $discrSql = $this->generateDiscriminatorColumnConditionSQL([$dqlAlias]);
1219
1220 18
                if ($discrSql) {
1221 3
                    $conditions[] = $discrSql;
1222
                }
1223
1224
                // Apply the filters
1225 18
                $filterExpr = $this->generateFilterConditionSQL($class, $tableAlias);
1226
1227 18
                if ($filterExpr) {
1228
                    $conditions[] = $filterExpr;
1229
                }
1230
1231 18
                if ($conditions) {
1232 16
                    $sql .= $condExprConjunction . implode(' AND ', $conditions);
1233
                }
1234
1235 18
                break;
1236
1237 228
            case $joinDeclaration instanceof AST\JoinAssociationDeclaration:
1238 228
                $sql .= $this->walkJoinAssociationDeclaration($joinDeclaration, $joinType, $join->conditionalExpression);
1239 226
                break;
1240
        }
1241
1242 243
        return $sql;
1243
    }
1244
1245
    /**
1246
     * Walks down a CoalesceExpression AST node and generates the corresponding SQL.
1247
     *
1248
     * @param AST\CoalesceExpression $coalesceExpression
1249
     *
1250
     * @return string The SQL.
1251
     */
1252 2
    public function walkCoalesceExpression($coalesceExpression)
1253
    {
1254 2
        $sql = 'COALESCE(';
1255
1256 2
        $scalarExpressions = [];
1257
1258 2
        foreach ($coalesceExpression->scalarExpressions as $scalarExpression) {
1259 2
            $scalarExpressions[] = $this->walkSimpleArithmeticExpression($scalarExpression);
1260
        }
1261
1262 2
        return $sql . implode(', ', $scalarExpressions) . ')';
1263
    }
1264
1265
    /**
1266
     * Walks down a NullIfExpression AST node and generates the corresponding SQL.
1267
     *
1268
     * @param AST\NullIfExpression $nullIfExpression
1269
     *
1270
     * @return string The SQL.
1271
     */
1272 3
    public function walkNullIfExpression($nullIfExpression)
1273
    {
1274 3
        $firstExpression = is_string($nullIfExpression->firstExpression)
1275
            ? $this->conn->quote($nullIfExpression->firstExpression)
1276 3
            : $this->walkSimpleArithmeticExpression($nullIfExpression->firstExpression);
1277
1278 3
        $secondExpression = is_string($nullIfExpression->secondExpression)
1279
            ? $this->conn->quote($nullIfExpression->secondExpression)
1280 3
            : $this->walkSimpleArithmeticExpression($nullIfExpression->secondExpression);
1281
1282 3
        return 'NULLIF(' . $firstExpression . ', ' . $secondExpression . ')';
1283
    }
1284
1285
    /**
1286
     * Walks down a GeneralCaseExpression AST node and generates the corresponding SQL.
1287
     *
1288
     * @return string The SQL.
1289
     */
1290 9
    public function walkGeneralCaseExpression(AST\GeneralCaseExpression $generalCaseExpression)
1291
    {
1292 9
        $sql = 'CASE';
1293
1294 9
        foreach ($generalCaseExpression->whenClauses as $whenClause) {
1295 9
            $sql .= ' WHEN ' . $this->walkConditionalExpression($whenClause->caseConditionExpression);
1296 9
            $sql .= ' THEN ' . $this->walkSimpleArithmeticExpression($whenClause->thenScalarExpression);
1297
        }
1298
1299 9
        $sql .= ' ELSE ' . $this->walkSimpleArithmeticExpression($generalCaseExpression->elseScalarExpression) . ' END';
1300
1301 9
        return $sql;
1302
    }
1303
1304
    /**
1305
     * Walks down a SimpleCaseExpression AST node and generates the corresponding SQL.
1306
     *
1307
     * @param AST\SimpleCaseExpression $simpleCaseExpression
1308
     *
1309
     * @return string The SQL.
1310
     */
1311 5
    public function walkSimpleCaseExpression($simpleCaseExpression)
1312
    {
1313 5
        $sql = 'CASE ' . $this->walkStateFieldPathExpression($simpleCaseExpression->caseOperand);
1314
1315 5
        foreach ($simpleCaseExpression->simpleWhenClauses as $simpleWhenClause) {
1316 5
            $sql .= ' WHEN ' . $this->walkSimpleArithmeticExpression($simpleWhenClause->caseScalarExpression);
1317 5
            $sql .= ' THEN ' . $this->walkSimpleArithmeticExpression($simpleWhenClause->thenScalarExpression);
1318
        }
1319
1320 5
        $sql .= ' ELSE ' . $this->walkSimpleArithmeticExpression($simpleCaseExpression->elseScalarExpression) . ' END';
1321
1322 5
        return $sql;
1323
    }
1324
1325
    /**
1326
     * {@inheritdoc}
1327
     */
1328 652
    public function walkSelectExpression($selectExpression)
1329
    {
1330 652
        $sql    = '';
1331 652
        $expr   = $selectExpression->expression;
1332 652
        $hidden = $selectExpression->hiddenAliasResultVariable;
1333
1334
        switch (true) {
1335 652
            case $expr instanceof AST\PathExpression:
1336 111
                if ($expr->type !== AST\PathExpression::TYPE_STATE_FIELD) {
1337
                    throw QueryException::invalidPathExpression($expr);
1338
                }
1339
1340 111
                $fieldName   = $expr->field;
1341 111
                $dqlAlias    = $expr->identificationVariable;
1342 111
                $qComp       = $this->queryComponents[$dqlAlias];
1343 111
                $class       = $qComp['metadata'];
1344 111
                $property    = $class->getProperty($fieldName);
1345 111
                $columnAlias = $this->getSQLColumnAlias();
1346 111
                $resultAlias = $selectExpression->fieldIdentificationVariable ?: $fieldName;
1347 111
                $col         = sprintf(
1348 111
                    '%s.%s',
1349 111
                    $this->getSQLTableAlias($property->getTableName(), $dqlAlias),
1350 111
                    $this->platform->quoteIdentifier($property->getColumnName())
1351
                );
1352
1353 111
                $sql .= sprintf(
1354 111
                    '%s AS %s',
1355 111
                    $property->getType()->convertToPHPValueSQL($col, $this->conn->getDatabasePlatform()),
1356 111
                    $columnAlias
1357
                );
1358
1359 111
                $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
1360
1361 111
                if (! $hidden) {
1362 111
                    $this->rsm->addScalarResult($columnAlias, $resultAlias, $property->getType());
1363 111
                    $this->scalarFields[$dqlAlias][$fieldName] = $columnAlias;
1364
                }
1365
1366 111
                break;
1367
1368 599
            case $expr instanceof AST\AggregateExpression:
1369 589
            case $expr instanceof AST\Functions\FunctionNode:
1370 533
            case $expr instanceof AST\SimpleArithmeticExpression:
1371 533
            case $expr instanceof AST\ArithmeticTerm:
1372 531
            case $expr instanceof AST\ArithmeticFactor:
1373 530
            case $expr instanceof AST\ParenthesisExpression:
1374 529
            case $expr instanceof AST\Literal:
1375 528
            case $expr instanceof AST\NullIfExpression:
1376 527
            case $expr instanceof AST\CoalesceExpression:
1377 526
            case $expr instanceof AST\GeneralCaseExpression:
1378 522
            case $expr instanceof AST\SimpleCaseExpression:
1379 127
                $columnAlias = $this->getSQLColumnAlias();
1380 127
                $resultAlias = $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
1381
1382 127
                $sql .= $expr->dispatch($this) . ' AS ' . $columnAlias;
1383
1384 127
                $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
1385
1386 127
                if (! $hidden) {
1387
                    // Conceptually we could resolve field type here by traverse through AST to retrieve field type,
1388
                    // but this is not a feasible solution; assume 'string'.
1389 127
                    if ($expr instanceof Query\AST\TypedExpression) {
1390 98
                        $type = $expr->getReturnType();
1391
                    } else {
1392 29
                        $type = Type::getType(Type::STRING);
1393
                    }
1394 127
                    $this->rsm->addScalarResult($columnAlias, $resultAlias, $type);
1395
                }
1396 127
                break;
1397
1398 521
            case $expr instanceof AST\Subselect:
1399 17
                $columnAlias = $this->getSQLColumnAlias();
1400 17
                $resultAlias = $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
1401
1402 17
                $sql .= '(' . $this->walkSubselect($expr) . ') AS ' . $columnAlias;
1403
1404 17
                $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
1405
1406 17
                if (! $hidden) {
1407
                    // We cannot resolve field type here; assume 'string'.
1408 14
                    $this->rsm->addScalarResult($columnAlias, $resultAlias, Type::getType('string'));
1409
                }
1410 17
                break;
1411
1412 516
            case $expr instanceof AST\NewObjectExpression:
1413 20
                $sql .= $this->walkNewObject($expr, $selectExpression->fieldIdentificationVariable);
1414 20
                break;
1415
1416
            default:
1417
                // IdentificationVariable or PartialObjectExpression
1418 496
                if ($expr instanceof AST\PartialObjectExpression) {
1419 15
                    $dqlAlias        = $expr->identificationVariable;
1420 15
                    $partialFieldSet = $expr->partialFieldSet;
1421
                } else {
1422 491
                    $dqlAlias        = $expr;
1423 491
                    $partialFieldSet = [];
1424
                }
1425
1426 496
                $queryComp   = $this->queryComponents[$dqlAlias];
1427 496
                $class       = $queryComp['metadata'];
1428 496
                $resultAlias = $selectExpression->fieldIdentificationVariable ?: null;
1429
1430 496
                if (! isset($this->selectedClasses[$dqlAlias])) {
1431 496
                    $this->selectedClasses[$dqlAlias] = [
1432 496
                        'class'       => $class,
1433 496
                        'dqlAlias'    => $dqlAlias,
1434 496
                        'resultAlias' => $resultAlias,
1435
                    ];
1436
                }
1437
1438 496
                $sqlParts = [];
1439
1440
                // Select all fields from the queried class
1441 496
                foreach ($class->getDeclaredPropertiesIterator() as $fieldName => $property) {
1442 496
                    if (! ($property instanceof FieldMetadata)) {
1443 443
                        continue;
1444
                    }
1445
1446 495
                    if ($partialFieldSet && ! in_array($fieldName, $partialFieldSet, true)) {
1447 13
                        continue;
1448
                    }
1449
1450 494
                    $columnAlias = $this->getSQLColumnAlias();
1451 494
                    $col         = sprintf(
1452 494
                        '%s.%s',
1453 494
                        $this->getSQLTableAlias($property->getTableName(), $dqlAlias),
1454 494
                        $this->platform->quoteIdentifier($property->getColumnName())
1455
                    );
1456
1457 494
                    $sqlParts[] = sprintf(
1458 494
                        '%s AS %s',
1459 494
                        $property->getType()->convertToPHPValueSQL($col, $this->platform),
1460 494
                        $columnAlias
1461
                    );
1462
1463 494
                    $this->scalarResultAliasMap[$resultAlias][] = $columnAlias;
1464
1465 494
                    $this->rsm->addFieldResult($dqlAlias, $columnAlias, $fieldName, $class->getClassName());
1466
                }
1467
1468
                // Add any additional fields of subclasses (excluding inherited fields)
1469
                // 1) on Single Table Inheritance: always, since its marginal overhead
1470
                // 2) on Class Table Inheritance only if partial objects are disallowed,
1471
                //    since it requires outer joining subtables.
1472 496
                if ($class->inheritanceType === InheritanceType::SINGLE_TABLE || ! $this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD)) {
1473 402
                    foreach ($class->getSubClasses() as $subClassName) {
1474 51
                        $subClass = $this->em->getClassMetadata($subClassName);
1475
1476 51
                        foreach ($subClass->getDeclaredPropertiesIterator() as $fieldName => $property) {
1477 51
                            if (! ($property instanceof FieldMetadata)) {
1478 39
                                continue;
1479
                            }
1480
1481 51
                            if ($subClass->isInheritedProperty($fieldName) || ($partialFieldSet && ! in_array($fieldName, $partialFieldSet, true))) {
1482 51
                                continue;
1483
                            }
1484
1485 38
                            $columnAlias = $this->getSQLColumnAlias();
1486 38
                            $col         = sprintf(
1487 38
                                '%s.%s',
1488 38
                                $this->getSQLTableAlias($property->getTableName(), $dqlAlias),
1489 38
                                $this->platform->quoteIdentifier($property->getColumnName())
1490
                            );
1491
1492 38
                            $sqlParts[] = sprintf(
1493 38
                                '%s AS %s',
1494 38
                                $property->getType()->convertToPHPValueSQL($col, $this->platform),
1495 38
                                $columnAlias
1496
                            );
1497
1498 38
                            $this->scalarResultAliasMap[$resultAlias][] = $columnAlias;
1499
1500 38
                            $this->rsm->addFieldResult($dqlAlias, $columnAlias, $fieldName, $subClassName);
1501
                        }
1502
                    }
1503
                }
1504
1505 496
                $sql .= implode(', ', $sqlParts);
1506
        }
1507
1508 652
        return $sql;
1509
    }
1510
1511
    /**
1512
     * {@inheritdoc}
1513
     */
1514
    public function walkQuantifiedExpression($qExpr)
1515
    {
1516
        return ' ' . strtoupper($qExpr->type) . '(' . $this->walkSubselect($qExpr->subselect) . ')';
1517
    }
1518
1519
    /**
1520
     * {@inheritdoc}
1521
     */
1522 35
    public function walkSubselect($subselect)
1523
    {
1524 35
        $useAliasesBefore  = $this->useSqlTableAliases;
1525 35
        $rootAliasesBefore = $this->rootAliases;
1526
1527 35
        $this->rootAliases        = []; // reset the rootAliases for the subselect
1528 35
        $this->useSqlTableAliases = true;
1529
1530 35
        $sql  = $this->walkSimpleSelectClause($subselect->simpleSelectClause);
1531 35
        $sql .= $this->walkSubselectFromClause($subselect->subselectFromClause);
1532 35
        $sql .= $this->walkWhereClause($subselect->whereClause);
1533
1534 35
        $sql .= $subselect->groupByClause ? $this->walkGroupByClause($subselect->groupByClause) : '';
1535 35
        $sql .= $subselect->havingClause ? $this->walkHavingClause($subselect->havingClause) : '';
1536 35
        $sql .= $subselect->orderByClause ? $this->walkOrderByClause($subselect->orderByClause) : '';
1537
1538 35
        $this->rootAliases        = $rootAliasesBefore; // put the main aliases back
1539 35
        $this->useSqlTableAliases = $useAliasesBefore;
1540
1541 35
        return $sql;
1542
    }
1543
1544
    /**
1545
     * {@inheritdoc}
1546
     */
1547 35
    public function walkSubselectFromClause($subselectFromClause)
1548
    {
1549 35
        $identificationVarDecls = $subselectFromClause->identificationVariableDeclarations;
1550 35
        $sqlParts               = [];
1551
1552 35
        foreach ($identificationVarDecls as $subselectIdVarDecl) {
1553 35
            $sqlParts[] = $this->walkIdentificationVariableDeclaration($subselectIdVarDecl);
1554
        }
1555
1556 35
        return ' FROM ' . implode(', ', $sqlParts);
1557
    }
1558
1559
    /**
1560
     * {@inheritdoc}
1561
     */
1562 35
    public function walkSimpleSelectClause($simpleSelectClause)
1563
    {
1564 35
        return 'SELECT' . ($simpleSelectClause->isDistinct ? ' DISTINCT' : '')
1565 35
            . $this->walkSimpleSelectExpression($simpleSelectClause->simpleSelectExpression);
1566
    }
1567
1568
    /**
1569
     * @return string.
0 ignored issues
show
Documentation Bug introduced by
The doc comment string. at position 0 could not be parsed: Unknown type name 'string.' at position 0 in string..
Loading history...
1570
     */
1571 22
    public function walkParenthesisExpression(AST\ParenthesisExpression $parenthesisExpression)
1572
    {
1573 22
        return sprintf('(%s)', $parenthesisExpression->expression->dispatch($this));
1574
    }
1575
1576
    /**
1577
     * @param AST\NewObjectExpression $newObjectExpression
1578
     * @param string|null             $newObjectResultAlias
1579
     *
1580
     * @return string The SQL.
1581
     */
1582 20
    public function walkNewObject($newObjectExpression, $newObjectResultAlias = null)
1583
    {
1584 20
        $sqlSelectExpressions = [];
1585 20
        $objIndex             = $newObjectResultAlias ?: $this->newObjectCounter++;
1586
1587 20
        foreach ($newObjectExpression->args as $argIndex => $e) {
1588 20
            $resultAlias = $this->scalarResultCounter++;
1589 20
            $columnAlias = $this->getSQLColumnAlias();
1590 20
            $fieldType   = Type::getType('string');
1591
1592
            switch (true) {
1593 20
                case $e instanceof AST\NewObjectExpression:
1594
                    $sqlSelectExpressions[] = $e->dispatch($this);
1595
                    break;
1596
1597 20
                case $e instanceof AST\Subselect:
1598 1
                    $sqlSelectExpressions[] = '(' . $e->dispatch($this) . ') AS ' . $columnAlias;
1599 1
                    break;
1600
1601 20
                case $e instanceof AST\PathExpression:
1602 20
                    $dqlAlias  = $e->identificationVariable;
1603 20
                    $qComp     = $this->queryComponents[$dqlAlias];
1604 20
                    $class     = $qComp['metadata'];
1605 20
                    $fieldType = $class->getProperty($e->field)->getType();
1606
1607 20
                    $sqlSelectExpressions[] = trim((string) $e->dispatch($this)) . ' AS ' . $columnAlias;
1608 20
                    break;
1609
1610 6
                case $e instanceof AST\Literal:
1611 1
                    switch ($e->type) {
1612 1
                        case AST\Literal::BOOLEAN:
1613 1
                            $fieldType = Type::getType('boolean');
1614 1
                            break;
1615
1616 1
                        case AST\Literal::NUMERIC:
1617 1
                            $fieldType = Type::getType(is_float($e->value) ? 'float' : 'integer');
1618 1
                            break;
1619
                    }
1620
1621 1
                    $sqlSelectExpressions[] = trim((string) $e->dispatch($this)) . ' AS ' . $columnAlias;
1622 1
                    break;
1623
1624
                default:
1625 5
                    $sqlSelectExpressions[] = trim((string) $e->dispatch($this)) . ' AS ' . $columnAlias;
1626 5
                    break;
1627
            }
1628
1629 20
            $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
1630 20
            $this->rsm->addScalarResult($columnAlias, $resultAlias, $fieldType);
1631
1632 20
            $this->rsm->newObjectMappings[$columnAlias] = [
1633 20
                'className' => $newObjectExpression->className,
1634 20
                'objIndex'  => $objIndex,
1635 20
                'argIndex'  => $argIndex,
1636
            ];
1637
        }
1638
1639 20
        return implode(', ', $sqlSelectExpressions);
1640
    }
1641
1642
    /**
1643
     * {@inheritdoc}
1644
     */
1645 35
    public function walkSimpleSelectExpression($simpleSelectExpression)
1646
    {
1647 35
        $expr = $simpleSelectExpression->expression;
1648 35
        $sql  = ' ';
1649
1650
        switch (true) {
1651 35
            case $expr instanceof AST\PathExpression:
1652 9
                $sql .= $this->walkPathExpression($expr);
1653 9
                break;
1654
1655 26
            case $expr instanceof AST\Subselect:
1656
                $alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
1657
1658
                $columnAlias                        = 'sclr' . $this->aliasCounter++;
1659
                $this->scalarResultAliasMap[$alias] = $columnAlias;
1660
1661
                $sql .= '(' . $this->walkSubselect($expr) . ') AS ' . $columnAlias;
1662
                break;
1663
1664 26
            case $expr instanceof AST\Functions\FunctionNode:
1665 11
            case $expr instanceof AST\SimpleArithmeticExpression:
1666 10
            case $expr instanceof AST\ArithmeticTerm:
1667 9
            case $expr instanceof AST\ArithmeticFactor:
1668 9
            case $expr instanceof AST\Literal:
1669 7
            case $expr instanceof AST\NullIfExpression:
1670 7
            case $expr instanceof AST\CoalesceExpression:
1671 7
            case $expr instanceof AST\GeneralCaseExpression:
1672 5
            case $expr instanceof AST\SimpleCaseExpression:
1673 23
                $alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
1674
1675 23
                $columnAlias                        = $this->getSQLColumnAlias();
1676 23
                $this->scalarResultAliasMap[$alias] = $columnAlias;
1677
1678 23
                $sql .= $expr->dispatch($this) . ' AS ' . $columnAlias;
1679 23
                break;
1680
1681 3
            case $expr instanceof AST\ParenthesisExpression:
1682 1
                $sql .= $this->walkParenthesisExpression($expr);
1683 1
                break;
1684
1685
            default: // IdentificationVariable
1686 2
                $sql .= $this->walkEntityIdentificationVariable($expr);
1687 2
                break;
1688
        }
1689
1690 35
        return $sql;
1691
    }
1692
1693
    /**
1694
     * {@inheritdoc}
1695
     */
1696 83
    public function walkAggregateExpression($aggExpression)
1697
    {
1698 83
        return $aggExpression->functionName . '(' . ($aggExpression->isDistinct ? 'DISTINCT ' : '')
1699 83
            . $this->walkSimpleArithmeticExpression($aggExpression->pathExpression) . ')';
1700
    }
1701
1702
    /**
1703
     * {@inheritdoc}
1704
     */
1705 27
    public function walkGroupByClause($groupByClause)
1706
    {
1707 27
        $sqlParts = [];
1708
1709 27
        foreach ($groupByClause->groupByItems as $groupByItem) {
1710 27
            $sqlParts[] = $this->walkGroupByItem($groupByItem);
1711
        }
1712
1713 27
        return ' GROUP BY ' . implode(', ', $sqlParts);
1714
    }
1715
1716
    /**
1717
     * {@inheritdoc}
1718
     */
1719 27
    public function walkGroupByItem($groupByItem)
1720
    {
1721
        // StateFieldPathExpression
1722 27
        if (! is_string($groupByItem)) {
1723 14
            return $this->walkPathExpression($groupByItem);
1724
        }
1725
1726
        // ResultVariable
1727 13
        if (isset($this->queryComponents[$groupByItem]['resultVariable'])) {
1728 2
            $resultVariable = $this->queryComponents[$groupByItem]['resultVariable'];
1729
1730 2
            if ($resultVariable instanceof AST\PathExpression) {
1731 1
                return $this->walkPathExpression($resultVariable);
1732
            }
1733
1734 1
            if (isset($resultVariable->pathExpression)) {
1735
                return $this->walkPathExpression($resultVariable->pathExpression);
1736
            }
1737
1738 1
            return $this->walkResultVariable($groupByItem);
1739
        }
1740
1741
        // IdentificationVariable
1742
        /** @var ClassMetadata $classMetadata */
1743 11
        $classMetadata = $this->queryComponents[$groupByItem]['metadata'];
1744 11
        $sqlParts      = [];
1745
1746 11
        foreach ($classMetadata->getDeclaredPropertiesIterator() as $property) {
1747
            switch (true) {
1748 11
                case $property instanceof FieldMetadata:
1749 11
                    $type       = AST\PathExpression::TYPE_STATE_FIELD;
1750 11
                    $item       = new AST\PathExpression($type, $groupByItem, $property->getName());
1751 11
                    $item->type = $type;
1752
1753 11
                    $sqlParts[] = $this->walkPathExpression($item);
1754 11
                    break;
1755
1756 11
                case $property instanceof ToOneAssociationMetadata && $property->isOwningSide():
1757 7
                    $type       = AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION;
1758 7
                    $item       = new AST\PathExpression($type, $groupByItem, $property->getName());
1759 7
                    $item->type = $type;
1760
1761 7
                    $sqlParts[] = $this->walkPathExpression($item);
1762 7
                    break;
1763
            }
1764
        }
1765
1766 11
        return implode(', ', $sqlParts);
1767
    }
1768
1769
    /**
1770
     * {@inheritdoc}
1771
     */
1772 37
    public function walkDeleteClause(AST\DeleteClause $deleteClause)
1773
    {
1774 37
        $class     = $this->em->getClassMetadata($deleteClause->abstractSchemaName);
1775 37
        $tableName = $class->getTableName();
1776 37
        $sql       = 'DELETE FROM ' . $class->table->getQuotedQualifiedName($this->platform);
0 ignored issues
show
Bug introduced by
Accessing table on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1777
1778 37
        $this->setSQLTableAlias($tableName, $tableName, $deleteClause->aliasIdentificationVariable);
1779
1780 37
        $this->rootAliases[] = $deleteClause->aliasIdentificationVariable;
1781
1782 37
        return $sql;
1783
    }
1784
1785
    /**
1786
     * {@inheritdoc}
1787
     */
1788 24
    public function walkUpdateClause($updateClause)
1789
    {
1790 24
        $class     = $this->em->getClassMetadata($updateClause->abstractSchemaName);
1791 24
        $tableName = $class->getTableName();
1792 24
        $sql       = 'UPDATE ' . $class->table->getQuotedQualifiedName($this->platform);
0 ignored issues
show
Bug introduced by
Accessing table on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1793
1794 24
        $this->setSQLTableAlias($tableName, $tableName, $updateClause->aliasIdentificationVariable);
1795 24
        $this->rootAliases[] = $updateClause->aliasIdentificationVariable;
1796
1797 24
        return $sql . ' SET ' . implode(', ', array_map([$this, 'walkUpdateItem'], $updateClause->updateItems));
1798
    }
1799
1800
    /**
1801
     * {@inheritdoc}
1802
     */
1803 28
    public function walkUpdateItem($updateItem)
1804
    {
1805 28
        $useTableAliasesBefore    = $this->useSqlTableAliases;
1806 28
        $this->useSqlTableAliases = false;
1807
1808 28
        $sql      = $this->walkPathExpression($updateItem->pathExpression) . ' = ';
1809 28
        $newValue = $updateItem->newValue;
1810
1811
        switch (true) {
1812 28
            case $newValue instanceof AST\Node:
1813 27
                $sql .= $newValue->dispatch($this);
1814 27
                break;
1815
1816 1
            case $newValue === null:
1817 1
                $sql .= 'NULL';
1818 1
                break;
1819
1820
            default:
1821
                $sql .= $this->conn->quote($newValue);
1822
                break;
1823
        }
1824
1825 28
        $this->useSqlTableAliases = $useTableAliasesBefore;
1826
1827 28
        return $sql;
1828
    }
1829
1830
    /**
1831
     * {@inheritdoc}
1832
     */
1833 709
    public function walkWhereClause($whereClause)
1834
    {
1835 709
        $condSql  = $whereClause !== null ? $this->walkConditionalExpression($whereClause->conditionalExpression) : '';
1836 706
        $discrSql = $this->generateDiscriminatorColumnConditionSQL($this->rootAliases);
1837
1838 706
        if ($this->em->hasFilters()) {
1839 41
            $filterClauses = [];
1840 41
            foreach ($this->rootAliases as $dqlAlias) {
1841 41
                $class      = $this->queryComponents[$dqlAlias]['metadata'];
1842 41
                $tableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
1843 41
                $filterExpr = $this->generateFilterConditionSQL($class, $tableAlias);
1844
1845 41
                if ($filterExpr) {
1846 6
                    $filterClauses[] = $filterExpr;
1847
                }
1848
            }
1849
1850 41
            if ($filterClauses) {
1851 6
                if ($condSql) {
1852 2
                    $condSql = '(' . $condSql . ') AND ';
1853
                }
1854
1855 6
                $condSql .= implode(' AND ', $filterClauses);
1856
            }
1857
        }
1858
1859 706
        if ($condSql) {
1860 347
            return ' WHERE ' . (! $discrSql ? $condSql : '(' . $condSql . ') AND ' . $discrSql);
1861
        }
1862
1863 436
        if ($discrSql) {
1864 24
            return ' WHERE ' . $discrSql;
1865
        }
1866
1867 416
        return '';
1868
    }
1869
1870
    /**
1871
     * {@inheritdoc}
1872
     */
1873 380
    public function walkConditionalExpression($condExpr)
1874
    {
1875
        // Phase 2 AST optimization: Skip processing of ConditionalExpression
1876
        // if only one ConditionalTerm is defined
1877 380
        if (! ($condExpr instanceof AST\ConditionalExpression)) {
1878 324
            return $this->walkConditionalTerm($condExpr);
1879
        }
1880
1881 74
        return implode(' OR ', array_map([$this, 'walkConditionalTerm'], $condExpr->conditionalTerms));
1882
    }
1883
1884
    /**
1885
     * {@inheritdoc}
1886
     */
1887 380
    public function walkConditionalTerm($condTerm)
1888
    {
1889
        // Phase 2 AST optimization: Skip processing of ConditionalTerm
1890
        // if only one ConditionalFactor is defined
1891 380
        if (! ($condTerm instanceof AST\ConditionalTerm)) {
1892 310
            return $this->walkConditionalFactor($condTerm);
1893
        }
1894
1895 93
        return implode(' AND ', array_map([$this, 'walkConditionalFactor'], $condTerm->conditionalFactors));
1896
    }
1897
1898
    /**
1899
     * {@inheritdoc}
1900
     */
1901 380
    public function walkConditionalFactor($factor)
1902
    {
1903
        // Phase 2 AST optimization: Skip processing of ConditionalFactor
1904
        // if only one ConditionalPrimary is defined
1905 380
        return ! ($factor instanceof AST\ConditionalFactor)
1906 377
            ? $this->walkConditionalPrimary($factor)
1907 377
            : ($factor->not ? 'NOT ' : '') . $this->walkConditionalPrimary($factor->conditionalPrimary);
1908
    }
1909
1910
    /**
1911
     * {@inheritdoc}
1912
     */
1913 380
    public function walkConditionalPrimary($primary)
1914
    {
1915 380
        if ($primary->isSimpleConditionalExpression()) {
1916 380
            return $primary->simpleConditionalExpression->dispatch($this);
1917
        }
1918
1919 25
        if ($primary->isConditionalExpression()) {
1920 25
            $condExpr = $primary->conditionalExpression;
1921
1922 25
            return '(' . $this->walkConditionalExpression($condExpr) . ')';
1923
        }
1924
    }
1925
1926
    /**
1927
     * {@inheritdoc}
1928
     */
1929 5
    public function walkExistsExpression($existsExpr)
1930
    {
1931 5
        $sql = $existsExpr->not ? 'NOT ' : '';
1932
1933 5
        $sql .= 'EXISTS (' . $this->walkSubselect($existsExpr->subselect) . ')';
1934
1935 5
        return $sql;
1936
    }
1937
1938
    /**
1939
     * {@inheritdoc}
1940
     */
1941 7
    public function walkCollectionMemberExpression($collMemberExpr)
1942
    {
1943 7
        $sql  = $collMemberExpr->not ? 'NOT ' : '';
1944 7
        $sql .= 'EXISTS (SELECT 1 FROM ';
1945
1946 7
        $entityExpr   = $collMemberExpr->entityExpression;
1947 7
        $collPathExpr = $collMemberExpr->collectionValuedPathExpression;
1948
1949 7
        $fieldName = $collPathExpr->field;
1950 7
        $dqlAlias  = $collPathExpr->identificationVariable;
1951
1952 7
        $class = $this->queryComponents[$dqlAlias]['metadata'];
1953
1954
        switch (true) {
1955
            // InputParameter
1956 7
            case $entityExpr instanceof AST\InputParameter:
1957 4
                $dqlParamKey = $entityExpr->name;
1958 4
                $entitySql   = '?';
1959 4
                break;
1960
1961
            // SingleValuedAssociationPathExpression | IdentificationVariable
1962 3
            case $entityExpr instanceof AST\PathExpression:
1963 3
                $entitySql = $this->walkPathExpression($entityExpr);
1964 3
                break;
1965
1966
            default:
1967
                throw new BadMethodCallException('Not implemented');
1968
        }
1969
1970 7
        $association       = $class->getProperty($fieldName);
1971 7
        $targetClass       = $this->em->getClassMetadata($association->getTargetEntity());
1972 7
        $owningAssociation = $association->isOwningSide()
1973 6
            ? $association
1974 7
            : $targetClass->getProperty($association->getMappedBy());
1975
1976 7
        if ($association instanceof OneToManyAssociationMetadata) {
1977 1
            $targetTableName  = $targetClass->table->getQuotedQualifiedName($this->platform);
0 ignored issues
show
Bug introduced by
Accessing table on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1978 1
            $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName());
1979 1
            $sourceTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
1980
1981 1
            $sql .= $targetTableName . ' ' . $targetTableAlias . ' WHERE ';
1982
1983 1
            $sqlParts = [];
1984
1985 1
            foreach ($owningAssociation->getJoinColumns() as $joinColumn) {
1986 1
                $sqlParts[] = sprintf(
1987 1
                    '%s.%s = %s.%s',
1988 1
                    $sourceTableAlias,
1989 1
                    $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName()),
1990 1
                    $targetTableAlias,
1991 1
                    $this->platform->quoteIdentifier($joinColumn->getColumnName())
1992
                );
1993
            }
1994
1995 1
            foreach ($targetClass->getIdentifierColumns($this->em) as $targetColumn) {
1996 1
                $quotedTargetColumnName = $this->platform->quoteIdentifier($targetColumn->getColumnName());
1997
1998 1
                if (isset($dqlParamKey)) {
1999 1
                    $this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++);
2000
                }
2001
2002 1
                $sqlParts[] = $targetTableAlias . '.' . $quotedTargetColumnName . ' = ' . $entitySql;
2003
            }
2004
2005 1
            $sql .= implode(' AND ', $sqlParts);
2006
        } else { // many-to-many
2007
            // SQL table aliases
2008 6
            $joinTable        = $owningAssociation->getJoinTable();
2009 6
            $joinTableName    = $joinTable->getQuotedQualifiedName($this->platform);
2010 6
            $joinTableAlias   = $this->getSQLTableAlias($joinTable->getName());
2011 6
            $targetTableName  = $targetClass->table->getQuotedQualifiedName($this->platform);
2012 6
            $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName());
2013 6
            $sourceTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
2014
2015
            // join to target table
2016 6
            $sql .= $joinTableName . ' ' . $joinTableAlias . ' INNER JOIN ' . $targetTableName . ' ' . $targetTableAlias . ' ON ';
2017
2018
            // join conditions
2019 6
            $joinSqlParts = [];
2020 6
            $joinColumns  = $association->isOwningSide()
2021 6
                ? $joinTable->getInverseJoinColumns()
2022 6
                : $joinTable->getJoinColumns();
2023
2024 6
            foreach ($joinColumns as $joinColumn) {
2025 6
                $quotedColumnName           = $this->platform->quoteIdentifier($joinColumn->getColumnName());
2026 6
                $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName());
2027
2028 6
                $joinSqlParts[] = sprintf(
2029 6
                    '%s.%s = %s.%s',
2030 6
                    $joinTableAlias,
2031 6
                    $quotedColumnName,
2032 6
                    $targetTableAlias,
2033 6
                    $quotedReferencedColumnName
2034
                );
2035
            }
2036
2037 6
            $sql .= implode(' AND ', $joinSqlParts);
2038 6
            $sql .= ' WHERE ';
2039
2040 6
            $sqlParts    = [];
2041 6
            $joinColumns = $association->isOwningSide()
2042 6
                ? $joinTable->getJoinColumns()
2043 6
                : $joinTable->getInverseJoinColumns();
2044
2045 6
            foreach ($joinColumns as $joinColumn) {
2046 6
                $quotedColumnName           = $this->platform->quoteIdentifier($joinColumn->getColumnName());
2047 6
                $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName());
2048
2049 6
                $sqlParts[] = sprintf(
2050 6
                    '%s.%s = %s.%s',
2051 6
                    $joinTableAlias,
2052 6
                    $quotedColumnName,
2053 6
                    $sourceTableAlias,
2054 6
                    $quotedReferencedColumnName
2055
                );
2056
            }
2057
2058 6
            foreach ($targetClass->getIdentifierColumns($this->em) as $targetColumn) {
2059 6
                $quotedTargetColumnName = $this->platform->quoteIdentifier($targetColumn->getColumnName());
2060
2061 6
                if (isset($dqlParamKey)) {
2062 3
                    $this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++);
2063
                }
2064
2065 6
                $sqlParts[] = $targetTableAlias . '.' . $quotedTargetColumnName . ' = ' . $entitySql;
2066
            }
2067
2068 6
            $sql .= implode(' AND ', $sqlParts);
2069
        }
2070
2071 7
        return $sql . ')';
2072
    }
2073
2074
    /**
2075
     * {@inheritdoc}
2076
     */
2077 3
    public function walkEmptyCollectionComparisonExpression($emptyCollCompExpr)
2078
    {
2079 3
        $sizeFunc                           = new AST\Functions\SizeFunction('size');
2080 3
        $sizeFunc->collectionPathExpression = $emptyCollCompExpr->expression;
2081
2082 3
        return $sizeFunc->getSql($this) . ($emptyCollCompExpr->not ? ' > 0' : ' = 0');
2083
    }
2084
2085
    /**
2086
     * {@inheritdoc}
2087
     */
2088 13
    public function walkNullComparisonExpression($nullCompExpr)
2089
    {
2090 13
        $expression = $nullCompExpr->expression;
2091 13
        $comparison = ' IS' . ($nullCompExpr->not ? ' NOT' : '') . ' NULL';
2092
2093
        // Handle ResultVariable
2094 13
        if (is_string($expression) && isset($this->queryComponents[$expression]['resultVariable'])) {
2095 2
            return $this->walkResultVariable($expression) . $comparison;
2096
        }
2097
2098
        // Handle InputParameter mapping inclusion to ParserResult
2099 11
        if ($expression instanceof AST\InputParameter) {
2100
            return $this->walkInputParameter($expression) . $comparison;
2101
        }
2102
2103 11
        return $expression->dispatch($this) . $comparison;
2104
    }
2105
2106
    /**
2107
     * {@inheritdoc}
2108
     */
2109 88
    public function walkInExpression($inExpr)
2110
    {
2111 88
        $sql = $this->walkArithmeticExpression($inExpr->expression) . ($inExpr->not ? ' NOT' : '') . ' IN (';
2112
2113 87
        $sql .= $inExpr->subselect
2114 7
            ? $this->walkSubselect($inExpr->subselect)
2115 87
            : implode(', ', array_map([$this, 'walkInParameter'], $inExpr->literals));
2116
2117 87
        $sql .= ')';
2118
2119 87
        return $sql;
2120
    }
2121
2122
    /**
2123
     * {@inheritdoc}
2124
     *
2125
     * @throws QueryException
2126
     */
2127 14
    public function walkInstanceOfExpression($instanceOfExpr)
2128
    {
2129 14
        $dqlAlias         = $instanceOfExpr->identificationVariable;
2130 14
        $class            = $this->queryComponents[$dqlAlias]['metadata'];
2131 14
        $discrClass       = $this->em->getClassMetadata($class->getRootClassName());
2132 14
        $discrColumn      = $class->discriminatorColumn;
2133 14
        $discrColumnType  = $discrColumn->getType();
2134 14
        $quotedColumnName = $this->platform->quoteIdentifier($discrColumn->getColumnName());
2135 14
        $sqlTableAlias    = $this->useSqlTableAliases
2136 14
            ? $this->getSQLTableAlias($discrColumn->getTableName(), $dqlAlias) . '.'
2137 14
            : '';
2138
2139 14
        return sprintf(
2140 14
            '%s %sIN %s',
2141 14
            $discrColumnType->convertToDatabaseValueSQL($sqlTableAlias . $quotedColumnName, $this->platform),
2142 14
            ($instanceOfExpr->not ? 'NOT ' : ''),
2143 14
            $this->getChildDiscriminatorsFromClassMetadata($discrClass, $instanceOfExpr)
2144
        );
2145
    }
2146
2147
    /**
2148
     * {@inheritdoc}
2149
     */
2150 80
    public function walkInParameter($inParam)
2151
    {
2152 80
        return $inParam instanceof AST\InputParameter
2153 71
            ? $this->walkInputParameter($inParam)
2154 80
            : $this->walkLiteral($inParam);
2155
    }
2156
2157
    /**
2158
     * {@inheritdoc}
2159
     */
2160 163
    public function walkLiteral($literal)
2161
    {
2162 163
        switch ($literal->type) {
2163 163
            case AST\Literal::STRING:
2164 54
                return $this->conn->quote($literal->value);
2165 123
            case AST\Literal::BOOLEAN:
2166 8
                return $this->conn->getDatabasePlatform()->convertBooleans(strtolower($literal->value) === 'true');
2167 116
            case AST\Literal::NUMERIC:
2168 116
                return $literal->value;
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 402
    public function walkSimpleArithmeticExpression($simpleArithmeticExpr)
2284
    {
2285 402
        if (! ($simpleArithmeticExpr instanceof AST\SimpleArithmeticExpression)) {
2286 351
            return $this->walkArithmeticTerm($simpleArithmeticExpr);
2287
        }
2288
2289 77
        return implode(' ', array_map([$this, 'walkArithmeticTerm'], $simpleArithmeticExpr->arithmeticTerms));
2290
    }
2291
2292
    /**
2293
     * {@inheritdoc}
2294
     */
2295 423
    public function walkArithmeticTerm($term)
2296
    {
2297 423
        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 422
        if (! ($term instanceof AST\ArithmeticTerm)) {
2306 400
            return $this->walkArithmeticFactor($term);
2307
        }
2308
2309 47
        return implode(' ', array_map([$this, 'walkArithmeticFactor'], $term->arithmeticFactors));
2310
    }
2311
2312
    /**
2313
     * {@inheritdoc}
2314
     */
2315 423
    public function walkArithmeticFactor($factor)
2316
    {
2317 423
        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 423
        if (! ($factor instanceof AST\ArithmeticFactor)) {
2326 422
            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 423
    public function walkArithmeticPrimary($primary)
2342
    {
2343 423
        if ($primary instanceof AST\SimpleArithmeticExpression) {
2344
            return '(' . $this->walkSimpleArithmeticExpression($primary) . ')';
2345
        }
2346
2347 423
        if ($primary instanceof AST\Node) {
2348 423
            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();
0 ignored issues
show
Bug introduced by
The method getClassName() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

2399
            /** @scrutinizer ignore-call */ 
2400
            $entityClassName = $entityClass->getClassName();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
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