Failed Conditions
Push — master ( 77e3e5...46b695 )
by Michael
26s queued 19s
created

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

Severity
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\ORM;
6
7
use Doctrine\Common\Cache\Cache;
8
use Doctrine\Common\Collections\ArrayCollection;
9
use Doctrine\DBAL\LockMode;
10
use Doctrine\ORM\Internal\Hydration\IterableResult;
11
use Doctrine\ORM\Mapping\ClassMetadata;
12
use Doctrine\ORM\Query\AST\DeleteStatement;
13
use Doctrine\ORM\Query\AST\SelectStatement;
14
use Doctrine\ORM\Query\AST\UpdateStatement;
15
use Doctrine\ORM\Query\Exec\AbstractSqlExecutor;
16
use Doctrine\ORM\Query\Parameter;
17
use Doctrine\ORM\Query\ParameterTypeInferer;
18
use Doctrine\ORM\Query\Parser;
19
use Doctrine\ORM\Query\ParserResult;
20
use Doctrine\ORM\Query\QueryException;
21
use Doctrine\ORM\Utility\HierarchyDiscriminatorResolver;
22
use function array_keys;
23
use function array_values;
24
use function count;
25
use function in_array;
26
use function ksort;
27
use function md5;
28
use function reset;
29
use function serialize;
30
use function sha1;
31
use function stripos;
32
33
/**
34
 * A Query object represents a DQL query.
35
 */
36
final class Query extends AbstractQuery
37
{
38
    /**
39
     * A query object is in CLEAN state when it has NO unparsed/unprocessed DQL parts.
40
     */
41
    public const STATE_CLEAN = 1;
42
43
    /**
44
     * A query object is in state DIRTY when it has DQL parts that have not yet been
45
     * parsed/processed. This is automatically defined as DIRTY when addDqlQueryPart
46
     * is called.
47
     */
48
    public const STATE_DIRTY = 2;
49
50
    /* Query HINTS */
51
52
    /**
53
     * The refresh hint turns any query into a refresh query with the result that
54
     * any local changes in entities are overridden with the fetched values.
55
     *
56
     * @var string
57
     */
58
    public const HINT_REFRESH = 'doctrine.refresh';
59
60
    /**
61
     * @var string
62
     */
63
    public const HINT_CACHE_ENABLED = 'doctrine.cache.enabled';
64
65
    /**
66
     * @var string
67
     */
68
    public const HINT_CACHE_EVICT = 'doctrine.cache.evict';
69
70
    /**
71
     * Internal hint: is set to the proxy entity that is currently triggered for loading
72
     *
73
     * @var string
74
     */
75
    public const HINT_REFRESH_ENTITY = 'doctrine.refresh.entity';
76
77
    /**
78
     * The forcePartialLoad query hint forces a particular query to return
79
     * partial objects.
80
     *
81
     * @var string
82
     * @todo Rename: HINT_OPTIMIZE
83
     */
84
    public const HINT_FORCE_PARTIAL_LOAD = 'doctrine.forcePartialLoad';
85
86
    /**
87
     * The includeMetaColumns query hint causes meta columns like foreign keys and
88
     * discriminator columns to be selected and returned as part of the query result.
89
     *
90
     * This hint does only apply to non-object queries.
91
     *
92
     * @var string
93
     */
94
    public const HINT_INCLUDE_META_COLUMNS = 'doctrine.includeMetaColumns';
95
96
    /**
97
     * An array of class names that implement \Doctrine\ORM\Query\TreeWalker and
98
     * are iterated and executed after the DQL has been parsed into an AST.
99
     *
100
     * @var string
101
     */
102
    public const HINT_CUSTOM_TREE_WALKERS = 'doctrine.customTreeWalkers';
103
104
    /**
105
     * A string with a class name that implements \Doctrine\ORM\Query\TreeWalker
106
     * and is used for generating the target SQL from any DQL AST tree.
107
     *
108
     * @var string
109
     */
110
    public const HINT_CUSTOM_OUTPUT_WALKER = 'doctrine.customOutputWalker';
111
112
    //const HINT_READ_ONLY = 'doctrine.readOnly';
113
114
    /**
115
     * @var string
116
     */
117
    public const HINT_INTERNAL_ITERATION = 'doctrine.internal.iteration';
118
119
    /**
120
     * @var string
121
     */
122
    public const HINT_LOCK_MODE = 'doctrine.lockMode';
123
124
    /**
125
     * The current state of this query.
126
     *
127
     * @var int
128
     */
129
    private $state = self::STATE_CLEAN;
130
131
    /**
132
     * A snapshot of the parameter types the query was parsed with.
133
     *
134
     * @var mixed[]
135
     */
136
    private $parsedTypes = [];
137
138
    /**
139
     * Cached DQL query.
140
     *
141
     * @var string
142
     */
143
    private $dql;
144
145
    /**
146
     * The parser result that holds DQL => SQL information.
147
     *
148
     * @var ParserResult
149
     */
150
    private $parserResult;
151
152
    /**
153
     * The first result to return (the "offset").
154
     *
155
     * @var int
156
     */
157
    private $firstResult;
158
159
    /**
160
     * The maximum number of results to return (the "limit").
161
     *
162
     * @var int|null
163
     */
164
    private $maxResults;
165
166
    /**
167
     * The cache driver used for caching queries.
168
     *
169
     * @var Cache|null
170
     */
171
    private $queryCache;
172
173
    /**
174
     * Whether or not expire the query cache.
175
     *
176
     * @var bool
177
     */
178
    private $expireQueryCache = false;
179
180
    /**
181
     * The query cache lifetime.
182
     *
183
     * @var int
184
     */
185
    private $queryCacheTTL;
186
187
    /**
188
     * Whether to use a query cache, if available. Defaults to TRUE.
189
     *
190
     * @var bool
191
     */
192
    private $useQueryCache = true;
193
194
    /**
195
     * Gets the SQL query/queries that correspond to this DQL query.
196
     *
197
     * @return mixed The built sql query or an array of all sql queries.
198
     *
199
     * @override
200
     */
201 342
    public function getSQL()
202
    {
203 342
        return $this->parse()->getSqlExecutor()->getSqlStatements();
204
    }
205
206
    /**
207
     * Returns the corresponding AST for this DQL query.
208
     *
209
     * @return SelectStatement|UpdateStatement|DeleteStatement
210
     */
211 2
    public function getAST()
212
    {
213 2
        $parser = new Parser($this);
214
215 2
        return $parser->getAST();
216
    }
217
218
    /**
219
     * {@inheritdoc}
220
     */
221 443
    protected function getResultSetMapping()
222
    {
223
        // parse query or load from cache
224 443
        if ($this->resultSetMapping === null) {
225 38
            $this->resultSetMapping = $this->parse()->getResultSetMapping();
226
        }
227
228 440
        return $this->resultSetMapping;
229
    }
230
231
    /**
232
     * Parses the DQL query, if necessary, and stores the parser result.
233
     *
234
     * Note: Populates $this->parserResult as a side-effect.
235
     *
236
     * @return ParserResult
237
     */
238 768
    private function parse()
239
    {
240 768
        $types = [];
241
242 768
        foreach ($this->parameters as $parameter) {
243
            /** @var Query\Parameter $parameter */
244 174
            $types[$parameter->getName()] = $parameter->getType();
245
        }
246
247
        // Return previous parser result if the query and the filter collection are both clean
248 768
        if ($this->state === self::STATE_CLEAN && $this->parsedTypes === $types && $this->em->isFiltersStateClean()) {
249 39
            return $this->parserResult;
250
        }
251
252 768
        $this->state       = self::STATE_CLEAN;
253 768
        $this->parsedTypes = $types;
254
255
        // Check query cache.
256 768
        $queryCache = $this->getQueryCacheDriver();
257 768
        if (! ($this->useQueryCache && $queryCache)) {
258 181
            $parser = new Parser($this);
259
260 181
            $this->parserResult = $parser->parse();
261
262 177
            return $this->parserResult;
263
        }
264
265 587
        $hash   = $this->getQueryCacheId();
266 587
        $cached = $this->expireQueryCache ? false : $queryCache->fetch($hash);
267
268 587
        if ($cached instanceof ParserResult) {
269
            // Cache hit.
270 118
            $this->parserResult = $cached;
271
272 118
            return $this->parserResult;
273
        }
274
275
        // Cache miss.
276 536
        $parser = new Parser($this);
277
278 536
        $this->parserResult = $parser->parse();
279
280 517
        $queryCache->save($hash, $this->parserResult, $this->queryCacheTTL);
281
282 517
        return $this->parserResult;
283
    }
284
285
    /**
286
     * {@inheritdoc}
287
     */
288 458
    protected function doExecute()
289
    {
290 458
        $executor = $this->parse()->getSqlExecutor();
291
292 451
        if ($this->queryCacheProfile) {
293 8
            $executor->setQueryCacheProfile($this->queryCacheProfile);
294
        } else {
295 445
            $executor->removeQueryCacheProfile();
296
        }
297
298 451
        if ($this->resultSetMapping === null) {
299 412
            $this->resultSetMapping = $this->parserResult->getResultSetMapping();
300
        }
301
302
        // Prepare parameters
303 451
        $paramMappings = $this->parserResult->getParameterMappings();
304 451
        $paramCount    = count($this->parameters);
305 451
        $mappingCount  = count($paramMappings);
306
307 451
        if ($paramCount > $mappingCount) {
308 1
            throw QueryException::tooManyParameters($mappingCount, $paramCount);
309
        }
310
311 450
        if ($paramCount < $mappingCount) {
312 1
            throw QueryException::tooFewParameters($mappingCount, $paramCount);
313
        }
314
315
        // evict all cache for the entity region
316 449
        if ($this->hasCache && isset($this->hints[self::HINT_CACHE_EVICT]) && $this->hints[self::HINT_CACHE_EVICT]) {
317 2
            $this->evictEntityCacheRegion();
318
        }
319
320 449
        list($sqlParams, $types) = $this->processParameterMappings($paramMappings);
321
322 448
        $this->evictResultSetCache(
323 448
            $executor,
324 448
            $sqlParams,
325 448
            $types,
326 448
            $this->em->getConnection()->getParams()
327
        );
328
329 448
        return $executor->execute($this->em->getConnection(), $sqlParams, $types);
330
    }
331
332
    /**
333
     * @param mixed[] $sqlParams
334
     * @param mixed[] $types
335
     * @param mixed[] $connectionParams
336
     */
337 448
    private function evictResultSetCache(
338
        AbstractSqlExecutor $executor,
339
        array $sqlParams,
340
        array $types,
341
        array $connectionParams
342
    ) {
343 448
        if ($this->queryCacheProfile === null || ! $this->getExpireResultCache()) {
344 448
            return;
345
        }
346
347 2
        $cacheDriver = $this->queryCacheProfile->getResultCacheDriver();
348 2
        $statements  = (array) $executor->getSqlStatements(); // Type casted since it can either be a string or an array
349
350 2
        foreach ($statements as $statement) {
351 2
            $cacheKeys = $this->queryCacheProfile->generateCacheKeys($statement, $sqlParams, $types, $connectionParams);
352
353 2
            $cacheDriver->delete(reset($cacheKeys));
354
        }
355 2
    }
356
357
    /**
358
     * Evict entity cache region
359
     */
360 2
    private function evictEntityCacheRegion()
361
    {
362 2
        $AST = $this->getAST();
363
364 2
        if ($AST instanceof SelectStatement) {
365
            throw new QueryException('The hint "HINT_CACHE_EVICT" is not valid for select statements.');
366
        }
367
368 2
        $className = ($AST instanceof DeleteStatement)
0 ignored issues
show
$AST is always a sub-type of Doctrine\ORM\Query\AST\DeleteStatement.
Loading history...
369 1
            ? $AST->deleteClause->abstractSchemaName
370 2
            : $AST->updateClause->abstractSchemaName;
371
372 2
        $this->em->getCache()->evictEntityRegion($className);
373 2
    }
374
375
    /**
376
     * Processes query parameter mappings.
377
     *
378
     * @param mixed[] $paramMappings
379
     *
380
     * @return mixed[][]
381
     *
382
     * @throws Query\QueryException
383
     */
384 449
    private function processParameterMappings($paramMappings)
385
    {
386 449
        $sqlParams = [];
387 449
        $types     = [];
388
389 449
        foreach ($this->parameters as $parameter) {
390 162
            $key   = $parameter->getName();
391 162
            $value = $parameter->getValue();
392 162
            $rsm   = $this->getResultSetMapping();
393
394 162
            if (! isset($paramMappings[$key])) {
395 1
                throw QueryException::unknownParameter($key);
396
            }
397
398 161
            if (isset($rsm->metadataParameterMapping[$key]) && $value instanceof ClassMetadata) {
399
                $value = $value->getMetadataValue($rsm->metadataParameterMapping[$key]);
400
            }
401
402 161
            if (isset($rsm->discriminatorParameters[$key]) && $value instanceof ClassMetadata) {
403 3
                $value = array_keys(HierarchyDiscriminatorResolver::resolveDiscriminatorsForClass($value, $this->em));
404
            }
405
406 161
            $value = $this->processParameterValue($value);
407 161
            $type  = ($parameter->getValue() === $value)
408 150
                ? $parameter->getType()
409 161
                : ParameterTypeInferer::inferType($value);
410
411 161
            foreach ($paramMappings[$key] as $position) {
412 161
                $types[$position] = $type;
413
            }
414
415 161
            $sqlPositions      = $paramMappings[$key];
416 161
            $sqlPositionsCount = count($sqlPositions);
417
418
            // optimized multi value sql positions away for now,
419
            // they are not allowed in DQL anyways.
420 161
            $value      = [$value];
421 161
            $countValue = count($value);
422
423 161
            for ($i = 0, $l = $sqlPositionsCount; $i < $l; $i++) {
424 161
                $sqlParams[$sqlPositions[$i]] = $value[($i % $countValue)];
425
            }
426
        }
427
428 448
        if (count($sqlParams) !== count($types)) {
429
            throw QueryException::parameterTypeMismatch();
430
        }
431
432 448
        if ($sqlParams) {
433 161
            ksort($sqlParams);
434 161
            $sqlParams = array_values($sqlParams);
435
436 161
            ksort($types);
437 161
            $types = array_values($types);
438
        }
439
440 448
        return [$sqlParams, $types];
441
    }
442
443
    /**
444
     * Defines a cache driver to be used for caching queries.
445
     *
446
     * @param Cache|null $queryCache Cache driver.
447
     *
448
     * @return Query This query instance.
449
     */
450 6
    public function setQueryCacheDriver($queryCache)
451
    {
452 6
        $this->queryCache = $queryCache;
453
454 6
        return $this;
455
    }
456
457
    /**
458
     * Defines whether the query should make use of a query cache, if available.
459
     *
460
     * @param bool $bool
461
     *
462
     * @return Query This query instance.
463
     */
464 184
    public function useQueryCache($bool)
465
    {
466 184
        $this->useQueryCache = $bool;
467
468 184
        return $this;
469
    }
470
471
    /**
472
     * Returns the cache driver used for query caching.
473
     *
474
     * @return Cache|null The cache driver used for query caching or NULL, if
475
     *                                           this Query does not use query caching.
476
     */
477 768
    public function getQueryCacheDriver()
478
    {
479 768
        if ($this->queryCache) {
480 6
            return $this->queryCache;
481
        }
482
483 762
        return $this->em->getConfiguration()->getQueryCacheImpl();
484
    }
485
486
    /**
487
     * Defines how long the query cache will be active before expire.
488
     *
489
     * @param int $timeToLive How long the cache entry is valid.
490
     *
491
     * @return Query This query instance.
492
     */
493 1
    public function setQueryCacheLifetime($timeToLive)
494
    {
495 1
        if ($timeToLive !== null) {
496 1
            $timeToLive = (int) $timeToLive;
497
        }
498
499 1
        $this->queryCacheTTL = $timeToLive;
500
501 1
        return $this;
502
    }
503
504
    /**
505
     * Retrieves the lifetime of resultset cache.
506
     *
507
     * @return int
508
     */
509
    public function getQueryCacheLifetime()
510
    {
511
        return $this->queryCacheTTL;
512
    }
513
514
    /**
515
     * Defines if the query cache is active or not.
516
     *
517
     * @param bool $expire Whether or not to force query cache expiration.
518
     *
519
     * @return Query This query instance.
520
     */
521 7
    public function expireQueryCache($expire = true)
522
    {
523 7
        $this->expireQueryCache = $expire;
524
525 7
        return $this;
526
    }
527
528
    /**
529
     * Retrieves if the query cache is active or not.
530
     *
531
     * @return bool
532
     */
533
    public function getExpireQueryCache()
534
    {
535
        return $this->expireQueryCache;
536
    }
537
538 220
    public function free()
539
    {
540 220
        parent::free();
541
542 220
        $this->dql   = null;
543 220
        $this->state = self::STATE_CLEAN;
544 220
    }
545
546
    /**
547
     * Sets a DQL query string.
548
     *
549
     * @param string $dqlQuery DQL Query.
550
     *
551
     * @return AbstractQuery
552
     */
553 951
    public function setDQL($dqlQuery)
554
    {
555 951
        if ($dqlQuery !== null) {
556 951
            $this->dql   = $dqlQuery;
557 951
            $this->state = self::STATE_DIRTY;
558
        }
559
560 951
        return $this;
561
    }
562
563
    /**
564
     * Returns the DQL query that is represented by this query object.
565
     *
566
     * @return string DQL query.
567
     */
568 895
    public function getDQL()
569
    {
570 895
        return $this->dql;
571
    }
572
573
    /**
574
     * Returns the state of this query object
575
     * By default the type is Doctrine_ORM_Query_Abstract::STATE_CLEAN but if it appears any unprocessed DQL
576
     * part, it is switched to Doctrine_ORM_Query_Abstract::STATE_DIRTY.
577
     *
578
     * @see AbstractQuery::STATE_CLEAN
579
     * @see AbstractQuery::STATE_DIRTY
580
     *
581
     * @return int The query state.
582
     */
583
    public function getState()
584
    {
585
        return $this->state;
586
    }
587
588
    /**
589
     * Method to check if an arbitrary piece of DQL exists
590
     *
591
     * @param string $dql Arbitrary piece of DQL to check for.
592
     *
593
     * @return bool
594
     */
595
    public function contains($dql)
596
    {
597
        return stripos($this->getDQL(), $dql) !== false;
598
    }
599
600
    /**
601
     * Sets the position of the first result to retrieve (the "offset").
602
     *
603
     * @param int $firstResult The first result to return.
604
     *
605
     * @return Query This query object.
606
     */
607 222
    public function setFirstResult($firstResult)
608
    {
609 222
        $this->firstResult = $firstResult;
610 222
        $this->state       = self::STATE_DIRTY;
611
612 222
        return $this;
613
    }
614
615
    /**
616
     * Gets the position of the first result the query object was set to retrieve (the "offset").
617
     * Returns NULL if {@link setFirstResult} was not applied to this query.
618
     *
619
     * @return int The position of the first result.
620
     */
621 655
    public function getFirstResult()
622
    {
623 655
        return $this->firstResult;
624
    }
625
626
    /**
627
     * Sets the maximum number of results to retrieve (the "limit").
628
     *
629
     * @param int|null $maxResults
630
     *
631
     * @return Query This query object.
632
     */
633 243
    public function setMaxResults($maxResults)
634
    {
635 243
        $this->maxResults = $maxResults;
636 243
        $this->state      = self::STATE_DIRTY;
637
638 243
        return $this;
639
    }
640
641
    /**
642
     * Gets the maximum number of results the query object was set to retrieve (the "limit").
643
     * Returns NULL if {@link setMaxResults} was not applied to this query.
644
     *
645
     * @return int|null Maximum number of results.
646
     */
647 655
    public function getMaxResults()
648
    {
649 655
        return $this->maxResults;
650
    }
651
652
    /**
653
     * Executes the query and returns an IterableResult that can be used to incrementally
654
     * iterated over the result.
655
     *
656
     * @param ArrayCollection|array|Parameter[]|mixed[]|null $parameters    The query parameters.
657
     * @param int                                            $hydrationMode The hydration mode to use.
658
     *
659
     * @return IterableResult
660
     */
661 10
    public function iterate($parameters = null, $hydrationMode = self::HYDRATE_OBJECT)
662
    {
663 10
        $this->setHint(self::HINT_INTERNAL_ITERATION, true);
664
665 10
        return parent::iterate($parameters, $hydrationMode);
666
    }
667
668
    /**
669
     * {@inheritdoc}
670
     */
671 462
    public function setHint($name, $value)
672
    {
673 462
        $this->state = self::STATE_DIRTY;
674
675 462
        return parent::setHint($name, $value);
676
    }
677
678
    /**
679
     * {@inheritdoc}
680
     */
681 358
    public function setHydrationMode($hydrationMode)
682
    {
683 358
        $this->state = self::STATE_DIRTY;
684
685 358
        return parent::setHydrationMode($hydrationMode);
686
    }
687
688
    /**
689
     * Set the lock mode for this Query.
690
     *
691
     * @see \Doctrine\DBAL\LockMode
692
     *
693
     * @param int $lockMode
694
     *
695
     * @return Query
696
     *
697
     * @throws TransactionRequiredException
698
     */
699
    public function setLockMode($lockMode)
700
    {
701
        if (in_array($lockMode, [LockMode::NONE, LockMode::PESSIMISTIC_READ, LockMode::PESSIMISTIC_WRITE], true)) {
702
            if (! $this->em->getConnection()->isTransactionActive()) {
703
                throw TransactionRequiredException::transactionRequired();
704
            }
705
        }
706
707
        $this->setHint(self::HINT_LOCK_MODE, $lockMode);
708
709
        return $this;
710
    }
711
712
    /**
713
     * Get the current lock mode for this query.
714
     *
715
     * @return int|null The current lock mode of this query or NULL if no specific lock mode is set.
716
     */
717
    public function getLockMode()
718
    {
719
        $lockMode = $this->getHint(self::HINT_LOCK_MODE);
720
721
        if ($lockMode === false) {
722
            return null;
723
        }
724
725
        return $lockMode;
726
    }
727
728
    /**
729
     * Generate a cache id for the query cache - reusing the Result-Cache-Id generator.
730
     *
731
     * @return string
732
     */
733 587
    protected function getQueryCacheId()
734
    {
735 587
        ksort($this->hints);
736
737 587
        $platform = $this->getEntityManager()
738 587
            ->getConnection()
739 587
            ->getDatabasePlatform()
740 587
            ->getName();
741
742 587
        return md5(
743 587
            $this->getDQL() . serialize($this->hints) .
744 587
            '&platform=' . $platform .
745 587
            ($this->em->hasFilters() ? $this->em->getFilters()->getHash() : '') .
746 587
            '&firstResult=' . $this->firstResult . '&maxResult=' . $this->maxResults .
747 587
            '&hydrationMode=' . $this->hydrationMode . '&types=' . serialize($this->parsedTypes) . 'DOCTRINE_QUERY_CACHE_SALT'
748
        );
749
    }
750
751
    /**
752
     * {@inheritdoc}
753
     */
754 28
    protected function getHash()
755
    {
756 28
        return sha1(parent::getHash() . '-' . $this->firstResult . '-' . $this->maxResults);
757
    }
758
759
    /**
760
     * Cleanup Query resource when clone is called.
761
     */
762 139
    public function __clone()
763
    {
764 139
        parent::__clone();
765
766 139
        $this->state = self::STATE_DIRTY;
767 139
    }
768
}
769