summaryrefslogtreecommitdiffstats
path: root/vendor/ipl/orm/src/Query.php
blob: 0e19dd1b75b9d59d25969dd18205fc0bba821398 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
<?php

namespace ipl\Orm;

use ArrayObject;
use Generator;
use InvalidArgumentException;
use ipl\Orm\Common\SortUtil;
use ipl\Orm\Compat\FilterProcessor;
use ipl\Sql\Connection;
use ipl\Sql\ExpressionInterface;
use ipl\Sql\LimitOffset;
use ipl\Sql\LimitOffsetInterface;
use ipl\Sql\OrderBy;
use ipl\Sql\OrderByInterface;
use ipl\Sql\Select;
use ipl\Stdlib\Contract\Filterable;
use ipl\Stdlib\Contract\Paginatable;
use ipl\Stdlib\Events;
use ipl\Stdlib\Filter;
use ipl\Stdlib\Filters;
use IteratorAggregate;
use ReflectionClass;
use SplObjectStorage;
use Traversable;

/**
 * Represents a database query which is associated to a model and a database connection.
 */
class Query implements Filterable, LimitOffsetInterface, OrderByInterface, Paginatable, IteratorAggregate
{
    use Events;
    use Filters;
    use LimitOffset;
    use OrderBy;

    /**
     * Event raised after assembling a {@link Select} object for the query
     *
     * **Example usage:**
     *
     * ```
     * $query->on(Query::ON_SELECT_ASSEMBLED, function (Select $select) {
     *     // ...
     * });
     * ```
     */
    const ON_SELECT_ASSEMBLED = 'selectAssembled';

    /** @var int Count cache */
    protected $count;

    /** @var Connection Database connection */
    protected $db;

    /** @var string Class to return results as */
    protected $resultSetClass = ResultSet::class;

    /** @var Model Model to query */
    protected $model;

    /** @var array Columns to select from the model (or its relations). If empty, all columns are selected */
    protected $columns = [];

    /** @var array Additional columns to select from the model (or its relations) */
    protected $withColumns = [];

    /** @var array Columns not to select from the model (or its relations) */
    protected $withoutColumns = [];

    /** @var bool Whether to peek ahead for more results */
    protected $peekAhead = false;

    /** @var Resolver Column and relation resolver */
    protected $resolver;

    /** @var Select Base SELECT query */
    protected $selectBase;

    /** @var Relation[] Relations to eager load */
    protected $with = [];

    /** @var Relation[] Relations to utilize (join) */
    protected $utilize = [];

    /** @var bool Whether to disable the default sorts of the model */
    protected $disableDefaultSort = false;

    /**
     * Get the database connection
     *
     * @return Connection
     */
    public function getDb()
    {
        return $this->db;
    }

    /**
     * Set the database connection
     *
     * @param Connection $db
     *
     * @return $this
     */
    public function setDb(Connection $db)
    {
        $this->db = $db;

        return $this;
    }

    /**
     * Get the class to return results as
     *
     * @return string
     */
    public function getResultSetClass()
    {
        return $this->resultSetClass;
    }

    /**
     * Set the class to return results as
     *
     * @param string $class
     *
     * @return $this
     *
     * @throws InvalidArgumentException If class is not an instance of {@link ResultSet}
     */
    public function setResultSetClass($class)
    {
        if (! is_string($class)) {
            throw new InvalidArgumentException('Argument $class must be a string');
        }

        if (! (new ReflectionClass($class))->newInstanceWithoutConstructor() instanceof ResultSet) {
            throw new InvalidArgumentException(
                $class . ' must be an instance of ' . ResultSet::class
            );
        }

        $this->resultSetClass = $class;

        return $this;
    }

    /**
     * Get the model to query
     *
     * @return Model
     */
    public function getModel()
    {
        return $this->model;
    }

    /**
     * Set the model to query
     *
     * @param $model
     *
     * @return $this
     */
    public function setModel(Model $model)
    {
        $this->model = $model;
        $this->getResolver()->setAlias($model, $model->getTableAlias());

        return $this;
    }

    /**
     * Get the columns to select from the model
     *
     * @return array
     */
    public function getColumns()
    {
        return $this->columns;
    }

    /**
     * Set the filter of the query
     *
     * @param Filter\Chain $filter
     *
     * @return $this
     */
    public function setFilter(Filter\Chain $filter)
    {
        $this->filter = $filter;

        return $this;
    }

    /**
     * Disable default sorts
     *
     * Prevents the default sort rules of the source model from being used
     *
     * @param bool $disable
     *
     * @return $this
     */
    public function disableDefaultSort($disable = true)
    {
        $this->disableDefaultSort = (bool) $disable;

        return $this;
    }

    /**
     * Get whether to not use the default sort rules of the source model
     *
     * @return bool
     */
    public function defaultSortDisabled()
    {
        return $this->disableDefaultSort;
    }


    /**
     * Set columns to select from the model (or its relations)
     *
     * By default, i.e. if you do not specify any columns, all columns of the model and
     * any relation added via {@see with()} will be selected.
     * Multiple calls to this method will overwrite the previously specified columns.
     * If you specify columns from the model's relations, the relations are automatically joined upon querying.
     * Any of the given columns is guaranteed to be selected even if previously excluded via {@see withoutColumns()}.
     * Any previously column specified via {@see withColumns()} will not be selected if not part of the given columns.
     *
     * @param string|array $columns The column(s) to select
     *
     * @return $this
     */
    public function columns($columns)
    {
        $this->columns = (array) $columns;
        $this->withColumns = [];
        $this->withoutColumns = [];

        return $this;
    }

    /**
     * Set additional columns to select from the model (or its relations)
     *
     * Multiple calls to this method will not overwrite the previous set columns but append the columns to the query.
     * Any of the given columns is guaranteed to be selected even if previously excluded via {@see withoutColumns()}.
     *
     * @param string|array $columns The column(s) to select
     *
     * @return $this
     */
    public function withColumns($columns)
    {
        $tableName = $this->getModel()->getTableAlias();

        $qualifiedColumns = [];
        foreach ((array) $columns as $alias => $column) {
            if (! $column instanceof ExpressionInterface) {
                $qualifiedColumns[$alias] = $this->getResolver()->qualifyPath($column, $tableName);
            } else {
                $qualifiedColumns[$alias] = $column;
            }
        }

        $this->withColumns = array_merge($this->withColumns, $qualifiedColumns);
        $this->withoutColumns = array_diff($this->withoutColumns, array_filter($this->withColumns, 'is_string'));

        return $this;
    }

    /**
     * Set columns not to select from the model (or its relations)
     *
     * Multiple calls to this method will not overwrite the previous set columns but append the new ones to the set.
     *
     * @param string|string[] $columns The column(s) not to select
     *
     * @return $this
     */
    public function withoutColumns($columns): self
    {
        $tableName = $this->getModel()->getTableAlias();

        $qualifiedColumns = [];
        foreach ((array) $columns as $column) {
            if (is_string($column)) {
                $qualifiedColumns[] = $this->getResolver()->qualifyPath($column, $tableName);
            }
        }

        $this->withoutColumns = array_merge($this->withoutColumns, $qualifiedColumns);

        return $this;
    }

    /**
     * Get the query's resolver
     *
     * @return Resolver
     */
    public function getResolver()
    {
        if ($this->resolver === null) {
            $this->resolver = new Resolver($this);
        }

        return $this->resolver;
    }

    /**
     * Get the SELECT base query
     *
     * @return Select
     */
    public function getSelectBase()
    {
        if ($this->selectBase === null) {
            $this->selectBase = new Select();

            $this->selectBase->from([
                $this->getResolver()->getAlias($this->getModel()) => $this->getModel()->getTableName()
            ]);
        }

        return $this->selectBase;
    }

    /**
     * Get the relations to eager load
     *
     * @return Relation[]
     */
    public function getWith()
    {
        return $this->with;
    }

    /**
     * Add a relation to eager load
     *
     * @param string|array $relations
     *
     * @return $this
     */
    public function with($relations)
    {
        $tableName = $this->getModel()->getTableAlias();
        foreach ((array) $relations as $relation) {
            $relation = $this->getResolver()->qualifyPath($relation, $tableName);
            $this->with[$relation] = $this->getResolver()->resolveRelation($relation);
        }

        return $this;
    }

    /**
     * Remove an eager loaded relation
     *
     * @param string|array $relations
     *
     * @return $this
     */
    public function without($relations)
    {
        $tableName = $this->getModel()->getTableAlias();
        foreach ((array) $relations as $relation) {
            $relation = $this->getResolver()->qualifyPath($relation, $tableName);
            unset($this->with[$relation]);
        }

        return $this;
    }

    /**
     * Get utilized (joined) relations
     *
     * @return Relation[]
     */
    public function getUtilize()
    {
        return $this->utilize;
    }

    /**
     * Add a relation to utilize (join)
     *
     * @param string $path
     *
     * @return $this
     */
    public function utilize($path)
    {
        $path = $this->getResolver()->qualifyPath($path, $this->getModel()->getTableAlias());
        $this->utilize[$path] = $this->getResolver()->resolveRelation($path);

        return $this;
    }

    /**
     * Remove a utilized (joined) relation
     *
     * @param string $path
     *
     * @return $this
     */
    public function omit($path)
    {
        $path = $this->getResolver()->qualifyPath($path, $this->getModel()->getTableAlias());
        unset($this->utilize[$path]);

        return $this;
    }

    /**
     * Assemble and return the SELECT query
     *
     * @return Select
     */
    public function assembleSelect()
    {
        $columns = $this->getColumns();
        $model = $this->getModel();
        $resolver = $this->getResolver();
        $select = clone $this->getSelectBase();

        if (empty($columns)) {
            $columns = $resolver->getSelectColumns($model);

            foreach ($this->getWith() as $path => $relation) {
                foreach ($resolver->getSelectColumns($relation->getTarget()) as $alias => $column) {
                    if (is_int($alias)) {
                        $columns[] = "$path.$column";
                    } else {
                        $columns[] = "$path.$alias";
                    }
                }
            }

            $columns = array_merge($columns, $this->withColumns);
            $customAliases = array_flip(array_filter(array_keys($this->withColumns), 'is_string'));
        } else {
            $columns = array_merge($columns, $this->withColumns);
            $customAliases = array_flip(array_filter(array_keys($columns), 'is_string'));
        }

        $resolved = $this->groupColumnsByTarget($resolver->requireAndResolveColumns($columns));
        $omitted = $this->groupColumnsByTarget($resolver->requireAndResolveColumns($this->withoutColumns));
        foreach ($resolved as $target) {
            $targetColumns = $resolved[$target]->getArrayCopy();
            if (isset($omitted[$target])) {
                $targetColumns = array_diff($targetColumns, $omitted[$target]->getArrayCopy());
            }

            if (! empty($customAliases)) {
                $customColumns = array_intersect_key($targetColumns, $customAliases);
                $targetColumns = array_diff_key($targetColumns, $customAliases);

                $select->columns($resolver->qualifyColumns($customColumns, $target));
            }

            $select->columns(
                $resolver->qualifyColumnsAndAliases(
                    $targetColumns,
                    $target,
                    $target !== $model
                )
            );
        }

        $filter = clone $this->getFilter();
        FilterProcessor::resolveFilter($filter, $this);
        $where = FilterProcessor::assembleFilter($filter);
        if ($where) {
            $select->where(...array_reverse($where));
        }

        $joinedRelations = [];
        foreach ($this->getWith() + $this->getUtilize() as $path => $_) {
            foreach ($resolver->resolveRelations($path) as $relationPath => $relation) {
                if (isset($joinedRelations[$relationPath])) {
                    continue;
                }

                foreach ($relation->resolve() as list($source, $target, $relatedKeys)) {
                    /** @var Model $source */
                    /** @var Model $target */

                    $sourceAlias = $resolver->getAlias($source);
                    $targetAlias = $resolver->getAlias($target);

                    $conditions = [];
                    foreach ($relatedKeys as $fk => $ck) {
                        $conditions[] = sprintf(
                            '%s = %s',
                            $resolver->qualifyColumn($fk, $targetAlias),
                            $resolver->qualifyColumn($ck, $sourceAlias)
                        );
                    }

                    $table = [$targetAlias => $target->getTableName()];

                    switch ($relation->getJoinType()) {
                        case 'LEFT':
                            $select->joinLeft($table, $conditions);

                            break;
                        case 'RIGHT':
                            $select->joinRight($table, $conditions);

                            break;
                        case 'INNER':
                        default:
                            $select->join($table, $conditions);
                    }
                }

                $joinedRelations[$relationPath] = true;
            }
        }

        if ($this->hasLimit()) {
            $limit = $this->getLimit();

            if ($this->peekAhead) {
                ++$limit;
            }

            $select->limit($limit);
        }
        if ($this->hasOffset()) {
            $select->offset($this->getOffset());
        }

        $this->order($select);

        $this->emit(static::ON_SELECT_ASSEMBLED, [$select]);

        return $select;
    }

    /**
     * Create and return the hydrator
     *
     * @return Hydrator
     */
    public function createHydrator()
    {
        $hydrator = new Hydrator($this);

        $hydrator->add($this->getModel()->getTableAlias());
        foreach ($this->getWith() as $path => $_) {
            $hydrator->add($path);
        }

        return $hydrator;
    }

    /**
     * Derive a new query to load the specified relation from a concrete model
     *
     * @param string $relation
     * @param Model  $source
     *
     * @return static
     *
     * @throws InvalidArgumentException If the relation with the given name does not exist
     */
    public function derive($relation, Model $source)
    {
        // TODO: Think of a way to merge derive() and createSubQuery()
        return $this->createSubQuery(
            $this->getResolver()->getRelations($source)->get($relation)->getTarget(),
            $this->getResolver()->qualifyPath($relation, $source->getTableAlias()),
            $source
        );
    }

    /**
     * Create a sub-query linked to rows of this query
     *
     * @param Model $target The model to query
     * @param string $targetPath The target's absolute relation path
     * @param ?Model $from The source model
     * @param bool $link Whether the query should be linked to the parent query
     *
     * @return static
     */
    public function createSubQuery(Model $target, $targetPath, Model $from = null, bool $link = true)
    {
        $subQuery = (new static())
            ->setDb($this->getDb())
            ->setModel($target);

        $sourceParts = array_reverse(explode('.', $targetPath));
        $sourceParts[0] = $target->getTableAlias();

        $subQueryResolver = $subQuery->getResolver();
        $sourcePath = join('.', $sourceParts);
        $subQueryTarget = $subQueryResolver->resolveRelation($sourcePath)->getTarget();

        $subQuery->utilize($sourcePath); // TODO: Don't join if there's a matching foreign key

        if (! $link) {
            return $subQuery->columns(array_map(function ($keyName) use ($sourcePath) {
                return "$sourcePath.$keyName";
            }, (array) $subQueryTarget->getKeyName()));
        }

        // TODO: Should be done by the caller. Though, that's not possible until we've got a filter abstraction
        //       which allows to post-pone filter column qualification.
        $subQueryResolver->setAliasPrefix('sub_');

        $resolver = $this->getResolver();
        $baseAlias = $resolver->getAlias($this->getModel());
        $sourceAlias = $subQueryResolver->getAlias($subQueryTarget);

        $subQueryConditions = [];
        foreach ((array) $this->getModel()->getKeyName() as $column) {
            $fk = $subQueryResolver->qualifyColumn($column, $sourceAlias);

            if (isset($from->$column)) {
                $subQueryConditions["$fk = ?"] = $resolver
                    ->getBehaviors($from)
                    ->persistProperty($from->$column, $column);
            } else {
                $subQueryConditions[] = "$fk = " . $resolver->qualifyColumn($column, $baseAlias);
            }
        }

        $subQuery->getSelectBase()->where($subQueryConditions);

        return $subQuery;
    }

    /**
     * Dump the query
     *
     * @return array
     */
    public function dump()
    {
        return $this->getDb()->getQueryBuilder()->assembleSelect($this->assembleSelect());
    }

    /**
     * Execute the query
     *
     * @return ResultSet
     */
    public function execute()
    {
        $class = $this->getResultSetClass();
        /** @var ResultSet $class Just for type hinting. $class is of course a string */

        return $class::fromQuery($this);
    }

    /**
     * Fetch and return the first result
     *
     * @return Model|null Null in case there's no result
     */
    public function first()
    {
        return $this->execute()->current();
    }

    /**
     * Set whether to peek ahead for more results
     *
     * Enabling this causes the current query limit to be increased by one. The potential extra row being yielded will
     * be removed from the result set. Note that this only applies when fetching multiple results of limited queries.
     *
     * @param bool $peekAhead
     *
     * @return $this
     */
    public function peekAhead($peekAhead = true)
    {
        $this->peekAhead = (bool) $peekAhead;

        return $this;
    }

    /**
     * Yield the query's results
     *
     * @return \Generator
     */
    public function yieldResults()
    {
        $select = $this->assembleSelect();
        $stmt = $this->getDb()->select($select);
        $stmt->setFetchMode(\PDO::FETCH_ASSOC);

        $hydrator = $this->createHydrator();
        $modelClass = get_class($this->getModel());

        foreach ($stmt as $row) {
            yield $hydrator->hydrate($row, new $modelClass());
        }
    }

    public function count(): int
    {
        if ($this->count === null) {
            $this->count = $this->getDb()->select($this->assembleSelect()->getCountQuery())->fetchColumn(0);
        }

        return $this->count;
    }

    public function getIterator(): Traversable
    {
        return $this->execute();
    }

    /**
     * Group columns from {@link Resolver::requireAndResolveColumns()} by target models
     *
     * @param Generator $columns
     *
     * @return SplObjectStorage
     */
    protected function groupColumnsByTarget(Generator $columns)
    {
        $columnStorage = new SplObjectStorage();

        foreach ($columns as list($target, $alias, $column)) {
            if (! $columnStorage->contains($target)) {
                $resolved = new ArrayObject();
                $columnStorage->attach($target, $resolved);
            } else {
                $resolved = $columnStorage[$target];
            }

            if (is_int($alias)) {
                $resolved[] = $column;
            } else {
                $resolved[$alias] = $column;
            }
        }

        return $columnStorage;
    }

    /**
     * Resolve, require and apply ORDER BY columns
     *
     * @param Select $select
     *
     * @return $this
     */
    protected function order(Select $select)
    {
        $orderBy = $this->getOrderBy();
        $defaultSort = [];
        if (! $this->defaultSortDisabled()) {
            $defaultSort = (array) $this->getModel()->getDefaultSort();
        }

        if (empty($orderBy)) {
            if (empty($defaultSort)) {
                return $this;
            }

            $orderBy = SortUtil::createOrderBy($defaultSort);
        }

        $columns = [];
        $directions = [];
        $orderByResolved = [];
        $resolver = $this->getResolver();
        $selectedColumns = $select->getColumns();

        foreach ($orderBy as $part) {
            list($column, $direction) = $part;

            if (! $column instanceof ExpressionInterface && isset($selectedColumns[$column])) {
                // If it's a custom alias, we have no other way of knowing it,
                // unless the caller explicitly uses it in the sort rule.
                $orderByResolved[] = $part;
            } else {
                // Prepare flat ORDER BY column(s) and direction(s) for requireAndResolveColumns()
                $columns[] = $column;
                $directions[] = $direction;
            }
        }

        foreach ($resolver->requireAndResolveColumns($columns) as list($model, $alias, $column)) {
            $direction = array_shift($directions);
            $selectColumns = $resolver->getSelectColumns($model);
            $tableName = $resolver->getAlias($model);

            if ($column instanceof ExpressionInterface) {
                if (is_int($alias) && $column instanceof AliasedExpression) {
                    $alias = $column->getAlias();
                } elseif (is_string($alias) && $model !== $this->getModel()) {
                    $alias = $resolver->qualifyColumnAlias($alias, $tableName);
                } elseif ($column instanceof ResolvedExpression) {
                    // We are doing this in an else if, since a resolved expression can't be an aliased
                    // expression at the same time and thus doesn't influence the functionality in any way.
                    $column->setColumns($resolver->qualifyColumns($column->getResolvedColumns()));
                }

                if (is_string($alias) && isset($selectedColumns[$alias])) {
                    // An expression's alias can only be used if the expression is also selected
                    $column = $alias;
                }
            } else {
                if (isset($selectColumns[$column])) {
                    $column = $selectColumns[$column];
                }

                if (is_string($column)) {
                    $column = $resolver->qualifyColumn($column, $tableName);
                }
            }

            $orderByResolved[] = [$column, $direction];
        }

        $select->orderBy($orderByResolved);

        return $this;
    }

    public function __clone()
    {
        $this->resolver = clone $this->resolver;

        if ($this->filter !== null) {
            $this->filter = clone $this->filter;
        }

        if ($this->selectBase !== null) {
            $this->selectBase = clone $this->selectBase;
        }
    }
}