Passed
Push — master ( b9880b...e1bb9e )
by Guilherme
09:04
created

SqlWalker::walkCoalesceExpression()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 11
rs 10
c 0
b 0
f 0
ccs 6
cts 6
cp 1
crap 2
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
180
     */
181
    public function getQuery()
182
    {
183
        return $this->query;
184
    }
185
186
    /**
187
     * Gets the Connection used by the walker.
188
     *
189
     * @return Connection
190
     */
191 51
    public function getConnection()
192
    {
193 51
        return $this->conn;
194
    }
195
196
    /**
197
     * Gets the EntityManager used by the walker.
198
     *
199
     * @return EntityManagerInterface
200
     */
201 23
    public function getEntityManager()
202
    {
203 23
        return $this->em;
204
    }
205
206
    /**
207
     * Gets the information about a single query component.
208
     *
209
     * @param string $dqlAlias The DQL alias.
210
     *
211
     * @return mixed[][]
212
     */
213 18
    public function getQueryComponent($dqlAlias)
214
    {
215 18
        return $this->queryComponents[$dqlAlias];
216
    }
217
218
    /**
219
     * {@inheritdoc}
220
     */
221
    public function getQueryComponents()
222
    {
223
        return $this->queryComponents;
224
    }
225
226
    /**
227
     * {@inheritdoc}
228
     */
229 1
    public function setQueryComponent($dqlAlias, array $queryComponent)
230
    {
231 1
        $requiredKeys = ['metadata', 'parent', 'relation', 'map', 'nestingLevel', 'token'];
232
233 1
        if (array_diff($requiredKeys, array_keys($queryComponent))) {
234 1
            throw QueryException::invalidQueryComponent($dqlAlias);
235
        }
236
237
        $this->queryComponents[$dqlAlias] = $queryComponent;
238
    }
239
240
    /**
241
     * {@inheritdoc}
242
     */
243 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 483
            $this->query->getHydrationMode() === Query::HYDRATE_OBJECT
720
        ) || (
721 310
            $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 185
                continue;
796
            }
797
798
            // Add foreign key columns of subclasses
799 351
            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 137
    public function walkFunction($function)
1140
    {
1141 137
        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 126
                $columnAlias = $this->getSQLColumnAlias();
1380 126
                $resultAlias = $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
1381
1382 126
                $sql .= $expr->dispatch($this) . ' AS ' . $columnAlias;
1383
1384 126
                $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
1385
1386 126
                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 126
                    $this->rsm->addScalarResult($columnAlias, $resultAlias, Type::getType('string'));
1390
                }
1391 126
                break;
1392
1393 521
            case $expr instanceof AST\Subselect:
1394 17
                $columnAlias = $this->getSQLColumnAlias();
1395 17
                $resultAlias = $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
1396
1397 17
                $sql .= '(' . $this->walkSubselect($expr) . ') AS ' . $columnAlias;
1398
1399 17
                $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
1400
1401 17
                if (! $hidden) {
1402
                    // We cannot resolve field type here; assume 'string'.
1403 14
                    $this->rsm->addScalarResult($columnAlias, $resultAlias, Type::getType('string'));
1404
                }
1405 17
                break;
1406
1407 516
            case $expr instanceof AST\NewObjectExpression:
1408 20
                $sql .= $this->walkNewObject($expr, $selectExpression->fieldIdentificationVariable);
1409 20
                break;
1410
1411
            default:
1412
                // IdentificationVariable or PartialObjectExpression
1413 496
                if ($expr instanceof AST\PartialObjectExpression) {
1414 15
                    $dqlAlias        = $expr->identificationVariable;
1415 15
                    $partialFieldSet = $expr->partialFieldSet;
1416
                } else {
1417 491
                    $dqlAlias        = $expr;
1418 491
                    $partialFieldSet = [];
1419
                }
1420
1421 496
                $queryComp   = $this->queryComponents[$dqlAlias];
1422 496
                $class       = $queryComp['metadata'];
1423 496
                $resultAlias = $selectExpression->fieldIdentificationVariable ?: null;
1424
1425 496
                if (! isset($this->selectedClasses[$dqlAlias])) {
1426 496
                    $this->selectedClasses[$dqlAlias] = [
1427 496
                        'class'       => $class,
1428 496
                        'dqlAlias'    => $dqlAlias,
1429 496
                        'resultAlias' => $resultAlias,
1430
                    ];
1431
                }
1432
1433 496
                $sqlParts = [];
1434
1435
                // Select all fields from the queried class
1436 496
                foreach ($class->getDeclaredPropertiesIterator() as $fieldName => $property) {
1437 496
                    if (! ($property instanceof FieldMetadata)) {
1438 443
                        continue;
1439
                    }
1440
1441 495
                    if ($partialFieldSet && ! in_array($fieldName, $partialFieldSet, true)) {
1442 13
                        continue;
1443
                    }
1444
1445 494
                    $columnAlias = $this->getSQLColumnAlias();
1446 494
                    $col         = sprintf(
1447 494
                        '%s.%s',
1448 494
                        $this->getSQLTableAlias($property->getTableName(), $dqlAlias),
1449 494
                        $this->platform->quoteIdentifier($property->getColumnName())
1450
                    );
1451
1452 494
                    $sqlParts[] = sprintf(
1453 494
                        '%s AS %s',
1454 494
                        $property->getType()->convertToPHPValueSQL($col, $this->platform),
1455 494
                        $columnAlias
1456
                    );
1457
1458 494
                    $this->scalarResultAliasMap[$resultAlias][] = $columnAlias;
1459
1460 494
                    $this->rsm->addFieldResult($dqlAlias, $columnAlias, $fieldName, $class->getClassName());
1461
                }
1462
1463
                // Add any additional fields of subclasses (excluding inherited fields)
1464
                // 1) on Single Table Inheritance: always, since its marginal overhead
1465
                // 2) on Class Table Inheritance only if partial objects are disallowed,
1466
                //    since it requires outer joining subtables.
1467 496
                if ($class->inheritanceType === InheritanceType::SINGLE_TABLE || ! $this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD)) {
1468 403
                    foreach ($class->getSubClasses() as $subClassName) {
1469 51
                        $subClass = $this->em->getClassMetadata($subClassName);
1470
1471 51
                        foreach ($subClass->getDeclaredPropertiesIterator() as $fieldName => $property) {
1472 51
                            if (! ($property instanceof FieldMetadata)) {
1473 39
                                continue;
1474
                            }
1475
1476 51
                            if ($subClass->isInheritedProperty($fieldName) || ($partialFieldSet && ! in_array($fieldName, $partialFieldSet, true))) {
1477 51
                                continue;
1478
                            }
1479
1480 38
                            $columnAlias = $this->getSQLColumnAlias();
1481 38
                            $col         = sprintf(
1482 38
                                '%s.%s',
1483 38
                                $this->getSQLTableAlias($property->getTableName(), $dqlAlias),
1484 38
                                $this->platform->quoteIdentifier($property->getColumnName())
1485
                            );
1486
1487 38
                            $sqlParts[] = sprintf(
1488 38
                                '%s AS %s',
1489 38
                                $property->getType()->convertToPHPValueSQL($col, $this->platform),
1490 38
                                $columnAlias
1491
                            );
1492
1493 38
                            $this->scalarResultAliasMap[$resultAlias][] = $columnAlias;
1494
1495 38
                            $this->rsm->addFieldResult($dqlAlias, $columnAlias, $fieldName, $subClassName);
1496
                        }
1497
                    }
1498
                }
1499
1500 496
                $sql .= implode(', ', $sqlParts);
1501
        }
1502
1503 652
        return $sql;
1504
    }
1505
1506
    /**
1507
     * {@inheritdoc}
1508
     */
1509
    public function walkQuantifiedExpression($qExpr)
1510
    {
1511
        return ' ' . strtoupper($qExpr->type) . '(' . $this->walkSubselect($qExpr->subselect) . ')';
1512
    }
1513
1514
    /**
1515
     * {@inheritdoc}
1516
     */
1517 35
    public function walkSubselect($subselect)
1518
    {
1519 35
        $useAliasesBefore  = $this->useSqlTableAliases;
1520 35
        $rootAliasesBefore = $this->rootAliases;
1521
1522 35
        $this->rootAliases        = []; // reset the rootAliases for the subselect
1523 35
        $this->useSqlTableAliases = true;
1524
1525 35
        $sql  = $this->walkSimpleSelectClause($subselect->simpleSelectClause);
1526 35
        $sql .= $this->walkSubselectFromClause($subselect->subselectFromClause);
1527 35
        $sql .= $this->walkWhereClause($subselect->whereClause);
1528
1529 35
        $sql .= $subselect->groupByClause ? $this->walkGroupByClause($subselect->groupByClause) : '';
1530 35
        $sql .= $subselect->havingClause ? $this->walkHavingClause($subselect->havingClause) : '';
1531 35
        $sql .= $subselect->orderByClause ? $this->walkOrderByClause($subselect->orderByClause) : '';
1532
1533 35
        $this->rootAliases        = $rootAliasesBefore; // put the main aliases back
1534 35
        $this->useSqlTableAliases = $useAliasesBefore;
1535
1536 35
        return $sql;
1537
    }
1538
1539
    /**
1540
     * {@inheritdoc}
1541
     */
1542 35
    public function walkSubselectFromClause($subselectFromClause)
1543
    {
1544 35
        $identificationVarDecls = $subselectFromClause->identificationVariableDeclarations;
1545 35
        $sqlParts               = [];
1546
1547 35
        foreach ($identificationVarDecls as $subselectIdVarDecl) {
1548 35
            $sqlParts[] = $this->walkIdentificationVariableDeclaration($subselectIdVarDecl);
1549
        }
1550
1551 35
        return ' FROM ' . implode(', ', $sqlParts);
1552
    }
1553
1554
    /**
1555
     * {@inheritdoc}
1556
     */
1557 35
    public function walkSimpleSelectClause($simpleSelectClause)
1558
    {
1559 35
        return 'SELECT' . ($simpleSelectClause->isDistinct ? ' DISTINCT' : '')
1560 35
            . $this->walkSimpleSelectExpression($simpleSelectClause->simpleSelectExpression);
1561
    }
1562
1563
    /**
1564
     * @return string
1565
     */
1566 22
    public function walkParenthesisExpression(AST\ParenthesisExpression $parenthesisExpression)
1567
    {
1568 22
        return sprintf('(%s)', $parenthesisExpression->expression->dispatch($this));
1569
    }
1570
1571
    /**
1572
     * @param AST\NewObjectExpression $newObjectExpression
1573
     * @param string|null             $newObjectResultAlias
1574
     *
1575
     * @return string The SQL.
1576
     */
1577 20
    public function walkNewObject($newObjectExpression, $newObjectResultAlias = null)
1578
    {
1579 20
        $sqlSelectExpressions = [];
1580 20
        $objIndex             = $newObjectResultAlias ?: $this->newObjectCounter++;
1581
1582 20
        foreach ($newObjectExpression->args as $argIndex => $e) {
1583 20
            $resultAlias = $this->scalarResultCounter++;
1584 20
            $columnAlias = $this->getSQLColumnAlias();
1585 20
            $fieldType   = Type::getType('string');
1586
1587
            switch (true) {
1588 20
                case $e instanceof AST\NewObjectExpression:
1589
                    $sqlSelectExpressions[] = $e->dispatch($this);
1590
                    break;
1591
1592 20
                case $e instanceof AST\Subselect:
1593 1
                    $sqlSelectExpressions[] = '(' . $e->dispatch($this) . ') AS ' . $columnAlias;
1594 1
                    break;
1595
1596 20
                case $e instanceof AST\PathExpression:
1597 20
                    $dqlAlias  = $e->identificationVariable;
1598 20
                    $qComp     = $this->queryComponents[$dqlAlias];
1599 20
                    $class     = $qComp['metadata'];
1600 20
                    $fieldType = $class->getProperty($e->field)->getType();
1601
1602 20
                    $sqlSelectExpressions[] = trim((string) $e->dispatch($this)) . ' AS ' . $columnAlias;
1603 20
                    break;
1604
1605 6
                case $e instanceof AST\Literal:
1606 1
                    switch ($e->type) {
1607 1
                        case AST\Literal::BOOLEAN:
1608 1
                            $fieldType = Type::getType('boolean');
1609 1
                            break;
1610
1611 1
                        case AST\Literal::NUMERIC:
1612 1
                            $fieldType = Type::getType(is_float($e->value) ? 'float' : 'integer');
1613 1
                            break;
1614
                    }
1615
1616 1
                    $sqlSelectExpressions[] = trim((string) $e->dispatch($this)) . ' AS ' . $columnAlias;
1617 1
                    break;
1618
1619
                default:
1620 5
                    $sqlSelectExpressions[] = trim((string) $e->dispatch($this)) . ' AS ' . $columnAlias;
1621 5
                    break;
1622
            }
1623
1624 20
            $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
1625 20
            $this->rsm->addScalarResult($columnAlias, $resultAlias, $fieldType);
1626
1627 20
            $this->rsm->newObjectMappings[$columnAlias] = [
1628 20
                'className' => $newObjectExpression->className,
1629 20
                'objIndex'  => $objIndex,
1630 20
                'argIndex'  => $argIndex,
1631
            ];
1632
        }
1633
1634 20
        return implode(', ', $sqlSelectExpressions);
1635
    }
1636
1637
    /**
1638
     * {@inheritdoc}
1639
     */
1640 35
    public function walkSimpleSelectExpression($simpleSelectExpression)
1641
    {
1642 35
        $expr = $simpleSelectExpression->expression;
1643 35
        $sql  = ' ';
1644
1645
        switch (true) {
1646 35
            case $expr instanceof AST\PathExpression:
1647 9
                $sql .= $this->walkPathExpression($expr);
1648 9
                break;
1649
1650 26
            case $expr instanceof AST\Subselect:
1651
                $alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
1652
1653
                $columnAlias                        = 'sclr' . $this->aliasCounter++;
1654
                $this->scalarResultAliasMap[$alias] = $columnAlias;
1655
1656
                $sql .= '(' . $this->walkSubselect($expr) . ') AS ' . $columnAlias;
1657
                break;
1658
1659 26
            case $expr instanceof AST\Functions\FunctionNode:
1660 11
            case $expr instanceof AST\SimpleArithmeticExpression:
1661 10
            case $expr instanceof AST\ArithmeticTerm:
1662 9
            case $expr instanceof AST\ArithmeticFactor:
1663 9
            case $expr instanceof AST\Literal:
1664 7
            case $expr instanceof AST\NullIfExpression:
1665 7
            case $expr instanceof AST\CoalesceExpression:
1666 7
            case $expr instanceof AST\GeneralCaseExpression:
1667 5
            case $expr instanceof AST\SimpleCaseExpression:
1668 23
                $alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
1669
1670 23
                $columnAlias                        = $this->getSQLColumnAlias();
1671 23
                $this->scalarResultAliasMap[$alias] = $columnAlias;
1672
1673 23
                $sql .= $expr->dispatch($this) . ' AS ' . $columnAlias;
1674 23
                break;
1675
1676 3
            case $expr instanceof AST\ParenthesisExpression:
1677 1
                $sql .= $this->walkParenthesisExpression($expr);
1678 1
                break;
1679
1680
            default: // IdentificationVariable
1681 2
                $sql .= $this->walkEntityIdentificationVariable($expr);
1682 2
                break;
1683
        }
1684
1685 35
        return $sql;
1686
    }
1687
1688
    /**
1689
     * {@inheritdoc}
1690
     */
1691 82
    public function walkAggregateExpression($aggExpression)
1692
    {
1693 82
        return $aggExpression->functionName . '(' . ($aggExpression->isDistinct ? 'DISTINCT ' : '')
1694 82
            . $this->walkSimpleArithmeticExpression($aggExpression->pathExpression) . ')';
1695
    }
1696
1697
    /**
1698
     * {@inheritdoc}
1699
     */
1700 27
    public function walkGroupByClause($groupByClause)
1701
    {
1702 27
        $sqlParts = [];
1703
1704 27
        foreach ($groupByClause->groupByItems as $groupByItem) {
1705 27
            $sqlParts[] = $this->walkGroupByItem($groupByItem);
1706
        }
1707
1708 27
        return ' GROUP BY ' . implode(', ', $sqlParts);
1709
    }
1710
1711
    /**
1712
     * {@inheritdoc}
1713
     */
1714 27
    public function walkGroupByItem($groupByItem)
1715
    {
1716
        // StateFieldPathExpression
1717 27
        if (! is_string($groupByItem)) {
1718 14
            return $this->walkPathExpression($groupByItem);
1719
        }
1720
1721
        // ResultVariable
1722 13
        if (isset($this->queryComponents[$groupByItem]['resultVariable'])) {
1723 2
            $resultVariable = $this->queryComponents[$groupByItem]['resultVariable'];
1724
1725 2
            if ($resultVariable instanceof AST\PathExpression) {
1726 1
                return $this->walkPathExpression($resultVariable);
1727
            }
1728
1729 1
            if (isset($resultVariable->pathExpression)) {
1730
                return $this->walkPathExpression($resultVariable->pathExpression);
1731
            }
1732
1733 1
            return $this->walkResultVariable($groupByItem);
1734
        }
1735
1736
        // IdentificationVariable
1737
        /** @var ClassMetadata $classMetadata */
1738 11
        $classMetadata = $this->queryComponents[$groupByItem]['metadata'];
1739 11
        $sqlParts      = [];
1740
1741 11
        foreach ($classMetadata->getDeclaredPropertiesIterator() as $property) {
1742
            switch (true) {
1743 11
                case $property instanceof FieldMetadata:
1744 11
                    $type       = AST\PathExpression::TYPE_STATE_FIELD;
1745 11
                    $item       = new AST\PathExpression($type, $groupByItem, $property->getName());
1746 11
                    $item->type = $type;
1747
1748 11
                    $sqlParts[] = $this->walkPathExpression($item);
1749 11
                    break;
1750
1751 11
                case $property instanceof ToOneAssociationMetadata && $property->isOwningSide():
1752 7
                    $type       = AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION;
1753 7
                    $item       = new AST\PathExpression($type, $groupByItem, $property->getName());
1754 7
                    $item->type = $type;
1755
1756 7
                    $sqlParts[] = $this->walkPathExpression($item);
1757 7
                    break;
1758
            }
1759
        }
1760
1761 11
        return implode(', ', $sqlParts);
1762
    }
1763
1764
    /**
1765
     * {@inheritdoc}
1766
     */
1767 37
    public function walkDeleteClause(AST\DeleteClause $deleteClause)
1768
    {
1769 37
        $class     = $this->em->getClassMetadata($deleteClause->abstractSchemaName);
1770 37
        $tableName = $class->getTableName();
1771 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...
1772
1773 37
        $this->setSQLTableAlias($tableName, $tableName, $deleteClause->aliasIdentificationVariable);
1774
1775 37
        $this->rootAliases[] = $deleteClause->aliasIdentificationVariable;
1776
1777 37
        return $sql;
1778
    }
1779
1780
    /**
1781
     * {@inheritdoc}
1782
     */
1783 24
    public function walkUpdateClause($updateClause)
1784
    {
1785 24
        $class     = $this->em->getClassMetadata($updateClause->abstractSchemaName);
1786 24
        $tableName = $class->getTableName();
1787 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...
1788
1789 24
        $this->setSQLTableAlias($tableName, $tableName, $updateClause->aliasIdentificationVariable);
1790 24
        $this->rootAliases[] = $updateClause->aliasIdentificationVariable;
1791
1792 24
        return $sql . ' SET ' . implode(', ', array_map([$this, 'walkUpdateItem'], $updateClause->updateItems));
1793
    }
1794
1795
    /**
1796
     * {@inheritdoc}
1797
     */
1798 28
    public function walkUpdateItem($updateItem)
1799
    {
1800 28
        $useTableAliasesBefore    = $this->useSqlTableAliases;
1801 28
        $this->useSqlTableAliases = false;
1802
1803 28
        $sql      = $this->walkPathExpression($updateItem->pathExpression) . ' = ';
1804 28
        $newValue = $updateItem->newValue;
1805
1806
        switch (true) {
1807 28
            case $newValue instanceof AST\Node:
1808 27
                $sql .= $newValue->dispatch($this);
1809 27
                break;
1810
1811 1
            case $newValue === null:
1812 1
                $sql .= 'NULL';
1813 1
                break;
1814
1815
            default:
1816
                $sql .= $this->conn->quote($newValue);
1817
                break;
1818
        }
1819
1820 28
        $this->useSqlTableAliases = $useTableAliasesBefore;
1821
1822 28
        return $sql;
1823
    }
1824
1825
    /**
1826
     * {@inheritdoc}
1827
     */
1828 709
    public function walkWhereClause($whereClause)
1829
    {
1830 709
        $condSql  = $whereClause !== null ? $this->walkConditionalExpression($whereClause->conditionalExpression) : '';
1831 706
        $discrSql = $this->generateDiscriminatorColumnConditionSQL($this->rootAliases);
1832
1833 706
        if ($this->em->hasFilters()) {
1834 41
            $filterClauses = [];
1835 41
            foreach ($this->rootAliases as $dqlAlias) {
1836 41
                $class      = $this->queryComponents[$dqlAlias]['metadata'];
1837 41
                $tableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
1838 41
                $filterExpr = $this->generateFilterConditionSQL($class, $tableAlias);
1839
1840 41
                if ($filterExpr) {
1841 6
                    $filterClauses[] = $filterExpr;
1842
                }
1843
            }
1844
1845 41
            if ($filterClauses) {
1846 6
                if ($condSql) {
1847 2
                    $condSql = '(' . $condSql . ') AND ';
1848
                }
1849
1850 6
                $condSql .= implode(' AND ', $filterClauses);
1851
            }
1852
        }
1853
1854 706
        if ($condSql) {
1855 348
            return ' WHERE ' . (! $discrSql ? $condSql : '(' . $condSql . ') AND ' . $discrSql);
1856
        }
1857
1858 435
        if ($discrSql) {
1859 24
            return ' WHERE ' . $discrSql;
1860
        }
1861
1862 415
        return '';
1863
    }
1864
1865
    /**
1866
     * {@inheritdoc}
1867
     */
1868 381
    public function walkConditionalExpression($condExpr)
1869
    {
1870
        // Phase 2 AST optimization: Skip processing of ConditionalExpression
1871
        // if only one ConditionalTerm is defined
1872 381
        if (! ($condExpr instanceof AST\ConditionalExpression)) {
1873 325
            return $this->walkConditionalTerm($condExpr);
1874
        }
1875
1876 74
        return implode(' OR ', array_map([$this, 'walkConditionalTerm'], $condExpr->conditionalTerms));
1877
    }
1878
1879
    /**
1880
     * {@inheritdoc}
1881
     */
1882 381
    public function walkConditionalTerm($condTerm)
1883
    {
1884
        // Phase 2 AST optimization: Skip processing of ConditionalTerm
1885
        // if only one ConditionalFactor is defined
1886 381
        if (! ($condTerm instanceof AST\ConditionalTerm)) {
1887 311
            return $this->walkConditionalFactor($condTerm);
1888
        }
1889
1890 93
        return implode(' AND ', array_map([$this, 'walkConditionalFactor'], $condTerm->conditionalFactors));
1891
    }
1892
1893
    /**
1894
     * {@inheritdoc}
1895
     */
1896 381
    public function walkConditionalFactor($factor)
1897
    {
1898
        // Phase 2 AST optimization: Skip processing of ConditionalFactor
1899
        // if only one ConditionalPrimary is defined
1900 381
        return ! ($factor instanceof AST\ConditionalFactor)
1901 378
            ? $this->walkConditionalPrimary($factor)
1902 378
            : ($factor->not ? 'NOT ' : '') . $this->walkConditionalPrimary($factor->conditionalPrimary);
1903
    }
1904
1905
    /**
1906
     * {@inheritdoc}
1907
     */
1908 381
    public function walkConditionalPrimary($primary)
1909
    {
1910 381
        if ($primary->isSimpleConditionalExpression()) {
1911 381
            return $primary->simpleConditionalExpression->dispatch($this);
1912
        }
1913
1914 25
        if ($primary->isConditionalExpression()) {
1915 25
            $condExpr = $primary->conditionalExpression;
1916
1917 25
            return '(' . $this->walkConditionalExpression($condExpr) . ')';
1918
        }
1919
1920
        return '';
1921
    }
1922
1923
    /**
1924
     * {@inheritdoc}
1925
     */
1926 5
    public function walkExistsExpression($existsExpr)
1927
    {
1928 5
        $sql = $existsExpr->not ? 'NOT ' : '';
1929
1930 5
        $sql .= 'EXISTS (' . $this->walkSubselect($existsExpr->subselect) . ')';
1931
1932 5
        return $sql;
1933
    }
1934
1935
    /**
1936
     * {@inheritdoc}
1937
     */
1938 7
    public function walkCollectionMemberExpression($collMemberExpr)
1939
    {
1940 7
        $sql  = $collMemberExpr->not ? 'NOT ' : '';
1941 7
        $sql .= 'EXISTS (SELECT 1 FROM ';
1942
1943 7
        $entityExpr   = $collMemberExpr->entityExpression;
1944 7
        $collPathExpr = $collMemberExpr->collectionValuedPathExpression;
1945
1946 7
        $fieldName = $collPathExpr->field;
1947 7
        $dqlAlias  = $collPathExpr->identificationVariable;
1948
1949 7
        $class = $this->queryComponents[$dqlAlias]['metadata'];
1950
1951
        switch (true) {
1952
            // InputParameter
1953 7
            case $entityExpr instanceof AST\InputParameter:
1954 4
                $dqlParamKey = $entityExpr->name;
1955 4
                $entitySql   = '?';
1956 4
                break;
1957
1958
            // SingleValuedAssociationPathExpression | IdentificationVariable
1959 3
            case $entityExpr instanceof AST\PathExpression:
1960 3
                $entitySql = $this->walkPathExpression($entityExpr);
1961 3
                break;
1962
1963
            default:
1964
                throw new BadMethodCallException('Not implemented');
1965
        }
1966
1967 7
        $association       = $class->getProperty($fieldName);
1968 7
        $targetClass       = $this->em->getClassMetadata($association->getTargetEntity());
1969 7
        $owningAssociation = $association->isOwningSide()
1970 6
            ? $association
1971 7
            : $targetClass->getProperty($association->getMappedBy());
1972
1973 7
        if ($association instanceof OneToManyAssociationMetadata) {
1974 1
            $targetTableName  = $targetClass->table->getQuotedQualifiedName($this->platform);
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...
1975 1
            $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName());
1976 1
            $sourceTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
1977
1978 1
            $sql .= $targetTableName . ' ' . $targetTableAlias . ' WHERE ';
1979
1980 1
            $sqlParts = [];
1981
1982 1
            foreach ($owningAssociation->getJoinColumns() as $joinColumn) {
1983 1
                $sqlParts[] = sprintf(
1984 1
                    '%s.%s = %s.%s',
1985 1
                    $sourceTableAlias,
1986 1
                    $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName()),
1987 1
                    $targetTableAlias,
1988 1
                    $this->platform->quoteIdentifier($joinColumn->getColumnName())
1989
                );
1990
            }
1991
1992 1
            foreach ($targetClass->getIdentifierColumns($this->em) as $targetColumn) {
1993 1
                $quotedTargetColumnName = $this->platform->quoteIdentifier($targetColumn->getColumnName());
1994
1995 1
                if (isset($dqlParamKey)) {
1996 1
                    $this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++);
1997
                }
1998
1999 1
                $sqlParts[] = $targetTableAlias . '.' . $quotedTargetColumnName . ' = ' . $entitySql;
2000
            }
2001
2002 1
            $sql .= implode(' AND ', $sqlParts);
2003
        } else { // many-to-many
2004
            // SQL table aliases
2005 6
            $joinTable        = $owningAssociation->getJoinTable();
2006 6
            $joinTableName    = $joinTable->getQuotedQualifiedName($this->platform);
2007 6
            $joinTableAlias   = $this->getSQLTableAlias($joinTable->getName());
2008 6
            $targetTableName  = $targetClass->table->getQuotedQualifiedName($this->platform);
2009 6
            $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName());
2010 6
            $sourceTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
2011
2012
            // join to target table
2013 6
            $sql .= $joinTableName . ' ' . $joinTableAlias . ' INNER JOIN ' . $targetTableName . ' ' . $targetTableAlias . ' ON ';
2014
2015
            // join conditions
2016 6
            $joinSqlParts = [];
2017 6
            $joinColumns  = $association->isOwningSide()
2018 6
                ? $joinTable->getInverseJoinColumns()
2019 6
                : $joinTable->getJoinColumns();
2020
2021 6
            foreach ($joinColumns as $joinColumn) {
2022 6
                $quotedColumnName           = $this->platform->quoteIdentifier($joinColumn->getColumnName());
2023 6
                $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName());
2024
2025 6
                $joinSqlParts[] = sprintf(
2026 6
                    '%s.%s = %s.%s',
2027 6
                    $joinTableAlias,
2028 6
                    $quotedColumnName,
2029 6
                    $targetTableAlias,
2030 6
                    $quotedReferencedColumnName
2031
                );
2032
            }
2033
2034 6
            $sql .= implode(' AND ', $joinSqlParts);
2035 6
            $sql .= ' WHERE ';
2036
2037 6
            $sqlParts    = [];
2038 6
            $joinColumns = $association->isOwningSide()
2039 6
                ? $joinTable->getJoinColumns()
2040 6
                : $joinTable->getInverseJoinColumns();
2041
2042 6
            foreach ($joinColumns as $joinColumn) {
2043 6
                $quotedColumnName           = $this->platform->quoteIdentifier($joinColumn->getColumnName());
2044 6
                $quotedReferencedColumnName = $this->platform->quoteIdentifier($joinColumn->getReferencedColumnName());
2045
2046 6
                $sqlParts[] = sprintf(
2047 6
                    '%s.%s = %s.%s',
2048 6
                    $joinTableAlias,
2049 6
                    $quotedColumnName,
2050 6
                    $sourceTableAlias,
2051 6
                    $quotedReferencedColumnName
2052
                );
2053
            }
2054
2055 6
            foreach ($targetClass->getIdentifierColumns($this->em) as $targetColumn) {
2056 6
                $quotedTargetColumnName = $this->platform->quoteIdentifier($targetColumn->getColumnName());
2057
2058 6
                if (isset($dqlParamKey)) {
2059 3
                    $this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++);
2060
                }
2061
2062 6
                $sqlParts[] = $targetTableAlias . '.' . $quotedTargetColumnName . ' = ' . $entitySql;
2063
            }
2064
2065 6
            $sql .= implode(' AND ', $sqlParts);
2066
        }
2067
2068 7
        return $sql . ')';
2069
    }
2070
2071
    /**
2072
     * {@inheritdoc}
2073
     */
2074 3
    public function walkEmptyCollectionComparisonExpression($emptyCollCompExpr)
2075
    {
2076 3
        $sizeFunc                           = new AST\Functions\SizeFunction('size');
2077 3
        $sizeFunc->collectionPathExpression = $emptyCollCompExpr->expression;
2078
2079 3
        return $sizeFunc->getSql($this) . ($emptyCollCompExpr->not ? ' > 0' : ' = 0');
2080
    }
2081
2082
    /**
2083
     * {@inheritdoc}
2084
     */
2085 13
    public function walkNullComparisonExpression($nullCompExpr)
2086
    {
2087 13
        $expression = $nullCompExpr->expression;
2088 13
        $comparison = ' IS' . ($nullCompExpr->not ? ' NOT' : '') . ' NULL';
2089
2090
        // Handle ResultVariable
2091 13
        if (is_string($expression) && isset($this->queryComponents[$expression]['resultVariable'])) {
2092 2
            return $this->walkResultVariable($expression) . $comparison;
2093
        }
2094
2095
        // Handle InputParameter mapping inclusion to ParserResult
2096 11
        if ($expression instanceof AST\InputParameter) {
2097
            return $this->walkInputParameter($expression) . $comparison;
2098
        }
2099
2100 11
        return $expression->dispatch($this) . $comparison;
2101
    }
2102
2103
    /**
2104
     * {@inheritdoc}
2105
     */
2106 88
    public function walkInExpression($inExpr)
2107
    {
2108 88
        $sql = $this->walkArithmeticExpression($inExpr->expression) . ($inExpr->not ? ' NOT' : '') . ' IN (';
2109
2110 87
        $sql .= $inExpr->subselect
2111 7
            ? $this->walkSubselect($inExpr->subselect)
2112 87
            : implode(', ', array_map([$this, 'walkInParameter'], $inExpr->literals));
2113
2114 87
        $sql .= ')';
2115
2116 87
        return $sql;
2117
    }
2118
2119
    /**
2120
     * {@inheritdoc}
2121
     *
2122
     * @throws QueryException
2123
     */
2124 14
    public function walkInstanceOfExpression($instanceOfExpr)
2125
    {
2126 14
        $dqlAlias         = $instanceOfExpr->identificationVariable;
2127 14
        $class            = $this->queryComponents[$dqlAlias]['metadata'];
2128 14
        $discrClass       = $this->em->getClassMetadata($class->getRootClassName());
2129 14
        $discrColumn      = $class->discriminatorColumn;
2130 14
        $discrColumnType  = $discrColumn->getType();
2131 14
        $quotedColumnName = $this->platform->quoteIdentifier($discrColumn->getColumnName());
2132 14
        $sqlTableAlias    = $this->useSqlTableAliases
2133 14
            ? $this->getSQLTableAlias($discrColumn->getTableName(), $dqlAlias) . '.'
2134 14
            : '';
2135
2136 14
        return sprintf(
2137 14
            '%s %sIN %s',
2138 14
            $discrColumnType->convertToDatabaseValueSQL($sqlTableAlias . $quotedColumnName, $this->platform),
2139 14
            ($instanceOfExpr->not ? 'NOT ' : ''),
2140 14
            $this->getChildDiscriminatorsFromClassMetadata($discrClass, $instanceOfExpr)
2141
        );
2142
    }
2143
2144
    /**
2145
     * {@inheritdoc}
2146
     */
2147 80
    public function walkInParameter($inParam)
2148
    {
2149 80
        return $inParam instanceof AST\InputParameter
2150 71
            ? $this->walkInputParameter($inParam)
2151 80
            : $this->walkLiteral($inParam);
2152
    }
2153
2154
    /**
2155
     * {@inheritdoc}
2156
     */
2157 163
    public function walkLiteral($literal)
2158
    {
2159 163
        switch ($literal->type) {
2160 163
            case AST\Literal::STRING:
2161 54
                return $this->conn->quote($literal->value);
2162 123
            case AST\Literal::BOOLEAN:
2163 8
                return $this->conn->getDatabasePlatform()->convertBooleans(strtolower($literal->value) === 'true');
2164 116
            case AST\Literal::NUMERIC:
2165 116
                return $literal->value;
2166
            default:
2167
                throw QueryException::invalidLiteral($literal);
2168
        }
2169
    }
2170
2171
    /**
2172
     * {@inheritdoc}
2173
     */
2174 6
    public function walkBetweenExpression($betweenExpr)
2175
    {
2176 6
        $sql = $this->walkArithmeticExpression($betweenExpr->expression);
2177
2178 6
        if ($betweenExpr->not) {
2179 2
            $sql .= ' NOT';
2180
        }
2181
2182 6
        $sql .= ' BETWEEN ' . $this->walkArithmeticExpression($betweenExpr->leftBetweenExpression)
2183 6
            . ' AND ' . $this->walkArithmeticExpression($betweenExpr->rightBetweenExpression);
2184
2185 6
        return $sql;
2186
    }
2187
2188
    /**
2189
     * {@inheritdoc}
2190
     */
2191 9
    public function walkLikeExpression($likeExpr)
2192
    {
2193 9
        $stringExpr = $likeExpr->stringExpression;
2194 9
        $leftExpr   = is_string($stringExpr) && isset($this->queryComponents[$stringExpr]['resultVariable'])
2195 1
            ? $this->walkResultVariable($stringExpr)
2196 9
            : $stringExpr->dispatch($this);
2197
2198 9
        $sql = $leftExpr . ($likeExpr->not ? ' NOT' : '') . ' LIKE ';
2199
2200 9
        if ($likeExpr->stringPattern instanceof AST\InputParameter) {
2201 3
            $sql .= $this->walkInputParameter($likeExpr->stringPattern);
2202 7
        } elseif ($likeExpr->stringPattern instanceof AST\Functions\FunctionNode) {
2203 2
            $sql .= $this->walkFunction($likeExpr->stringPattern);
2204 7
        } elseif ($likeExpr->stringPattern instanceof AST\PathExpression) {
2205 2
            $sql .= $this->walkPathExpression($likeExpr->stringPattern);
2206
        } else {
2207 7
            $sql .= $this->walkLiteral($likeExpr->stringPattern);
2208
        }
2209
2210 9
        if ($likeExpr->escapeChar) {
2211 1
            $sql .= ' ESCAPE ' . $this->walkLiteral($likeExpr->escapeChar);
2212
        }
2213
2214 9
        return $sql;
2215
    }
2216
2217
    /**
2218
     * {@inheritdoc}
2219
     */
2220 5
    public function walkStateFieldPathExpression($stateFieldPathExpression)
2221
    {
2222 5
        return $this->walkPathExpression($stateFieldPathExpression);
2223
    }
2224
2225
    /**
2226
     * {@inheritdoc}
2227
     */
2228 269
    public function walkComparisonExpression($compExpr)
2229
    {
2230 269
        $leftExpr  = $compExpr->leftExpression;
2231 269
        $rightExpr = $compExpr->rightExpression;
2232 269
        $sql       = '';
2233
2234 269
        $sql .= $leftExpr instanceof AST\Node
2235 269
            ? $leftExpr->dispatch($this)
2236 268
            : (is_numeric($leftExpr) ? $leftExpr : $this->conn->quote($leftExpr));
2237
2238 268
        $sql .= ' ' . $compExpr->operator . ' ';
2239
2240 268
        $sql .= $rightExpr instanceof AST\Node
2241 266
            ? $rightExpr->dispatch($this)
2242 268
            : (is_numeric($rightExpr) ? $rightExpr : $this->conn->quote($rightExpr));
2243
2244 268
        return $sql;
2245
    }
2246
2247
    /**
2248
     * {@inheritdoc}
2249
     */
2250 224
    public function walkInputParameter($inputParam)
2251
    {
2252 224
        $this->parserResult->addParameterMapping($inputParam->name, $this->sqlParamIndex++);
2253
2254 224
        $parameter = $this->query->getParameter($inputParam->name);
2255
2256 224
        if ($parameter) {
2257 147
            $type = $parameter->getType();
2258
2259 147
            if (Type::hasType($type)) {
2260 60
                return Type::getType($type)->convertToDatabaseValueSQL('?', $this->platform);
2261
            }
2262
        }
2263
2264 172
        return '?';
2265
    }
2266
2267
    /**
2268
     * {@inheritdoc}
2269
     */
2270 337
    public function walkArithmeticExpression($arithmeticExpr)
2271
    {
2272 337
        return $arithmeticExpr->isSimpleArithmeticExpression()
2273 337
            ? $this->walkSimpleArithmeticExpression($arithmeticExpr->simpleArithmeticExpression)
2274 335
            : '(' . $this->walkSubselect($arithmeticExpr->subselect) . ')';
2275
    }
2276
2277
    /**
2278
     * {@inheritdoc}
2279
     */
2280 402
    public function walkSimpleArithmeticExpression($simpleArithmeticExpr)
2281
    {
2282 402
        if (! ($simpleArithmeticExpr instanceof AST\SimpleArithmeticExpression)) {
2283 351
            return $this->walkArithmeticTerm($simpleArithmeticExpr);
2284
        }
2285
2286 77
        return implode(' ', array_map([$this, 'walkArithmeticTerm'], $simpleArithmeticExpr->arithmeticTerms));
2287
    }
2288
2289
    /**
2290
     * {@inheritdoc}
2291
     */
2292 423
    public function walkArithmeticTerm($term)
2293
    {
2294 423
        if (is_string($term)) {
2295 21
            return isset($this->queryComponents[$term])
2296 6
                ? $this->walkResultVariable($this->queryComponents[$term]['token']['value'])
2297 21
                : $term;
2298
        }
2299
2300
        // Phase 2 AST optimization: Skip processing of ArithmeticTerm
2301
        // if only one ArithmeticFactor is defined
2302 422
        if (! ($term instanceof AST\ArithmeticTerm)) {
2303 400
            return $this->walkArithmeticFactor($term);
2304
        }
2305
2306 47
        return implode(' ', array_map([$this, 'walkArithmeticFactor'], $term->arithmeticFactors));
2307
    }
2308
2309
    /**
2310
     * {@inheritdoc}
2311
     */
2312 423
    public function walkArithmeticFactor($factor)
2313
    {
2314 423
        if (is_string($factor)) {
2315 47
            return isset($this->queryComponents[$factor])
2316 2
                ? $this->walkResultVariable($this->queryComponents[$factor]['token']['value'])
2317 47
                : $factor;
2318
        }
2319
2320
        // Phase 2 AST optimization: Skip processing of ArithmeticFactor
2321
        // if only one ArithmeticPrimary is defined
2322 423
        if (! ($factor instanceof AST\ArithmeticFactor)) {
2323 422
            return $this->walkArithmeticPrimary($factor);
2324
        }
2325
2326 3
        $sign = $factor->isNegativeSigned() ? '-' : ($factor->isPositiveSigned() ? '+' : '');
2327
2328 3
        return $sign . $this->walkArithmeticPrimary($factor->arithmeticPrimary);
2329
    }
2330
2331
    /**
2332
     * Walks down an ArithmeticPrimary that represents an AST node, thereby generating the appropriate SQL.
2333
     *
2334
     * @param mixed $primary
2335
     *
2336
     * @return string The SQL.
2337
     */
2338 423
    public function walkArithmeticPrimary($primary)
2339
    {
2340 423
        if ($primary instanceof AST\SimpleArithmeticExpression) {
2341
            return '(' . $this->walkSimpleArithmeticExpression($primary) . ')';
2342
        }
2343
2344 423
        if ($primary instanceof AST\Node) {
2345 423
            return $primary->dispatch($this);
2346
        }
2347
2348
        return $this->walkEntityIdentificationVariable($primary);
2349
    }
2350
2351
    /**
2352
     * {@inheritdoc}
2353
     */
2354 22
    public function walkStringPrimary($stringPrimary)
2355
    {
2356 22
        return is_string($stringPrimary)
2357
            ? $this->conn->quote($stringPrimary)
2358 22
            : $stringPrimary->dispatch($this);
2359
    }
2360
2361
    /**
2362
     * {@inheritdoc}
2363
     */
2364 32
    public function walkResultVariable($resultVariable)
2365
    {
2366 32
        $resultAlias = $this->scalarResultAliasMap[$resultVariable];
2367
2368 32
        if (is_array($resultAlias)) {
2369 1
            return implode(', ', $resultAlias);
2370
        }
2371
2372 31
        return $resultAlias;
2373
    }
2374
2375
    /**
2376
     * @return string The list in parentheses of valid child discriminators from the given class
2377
     *
2378
     * @throws QueryException
2379
     */
2380 14
    private function getChildDiscriminatorsFromClassMetadata(ClassMetadata $rootClass, AST\InstanceOfExpression $instanceOfExpr) : string
2381
    {
2382 14
        $sqlParameterList = [];
2383 14
        $discriminators   = [];
2384
2385 14
        foreach ($instanceOfExpr->value as $parameter) {
2386 14
            if ($parameter instanceof AST\InputParameter) {
2387 4
                $this->rsm->discriminatorParameters[$parameter->name] = $parameter->name;
2388
2389 4
                $sqlParameterList[] = $this->walkInputParameter($parameter);
2390
2391 4
                continue;
2392
            }
2393
2394
            // Get name from ClassMetadata to resolve aliases.
2395 10
            $entityClass     = $this->em->getClassMetadata($parameter);
2396 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

2396
            /** @scrutinizer ignore-call */ 
2397
            $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...
2397
2398 10
            if ($entityClassName !== $rootClass->getClassName()) {
2399 7
                if (! $entityClass->getReflectionClass()->isSubclassOf($rootClass->getClassName())) {
2400 1
                    throw QueryException::instanceOfUnrelatedClass($entityClassName, $rootClass->getClassName());
2401
                }
2402
            }
2403
2404 9
            $discriminators += HierarchyDiscriminatorResolver::resolveDiscriminatorsForClass($entityClass, $this->em);
2405
        }
2406
2407 13
        foreach (array_keys($discriminators) as $discriminator) {
2408 9
            $sqlParameterList[] = $this->conn->quote($discriminator);
2409
        }
2410
2411 13
        return '(' . implode(', ', $sqlParameterList) . ')';
2412
    }
2413
}
2414