Debian Codegraph @

vendor/ipl/orm/src/Query.php

raw
1 <?php
2
3 namespace ipl\Orm;
4
5 use ArrayObject;
6 use Generator;
7 use InvalidArgumentException;
8 use ipl\Orm\Common\SortUtil;
9 use ipl\Orm\Compat\FilterProcessor;
10 use ipl\Sql\Connection;
11 use ipl\Sql\ExpressionInterface;
12 use ipl\Sql\LimitOffset;
13 use ipl\Sql\LimitOffsetInterface;
14 use ipl\Sql\OrderBy;
15 use ipl\Sql\OrderByInterface;
16 use ipl\Sql\Select;
17 use ipl\Stdlib\Contract\Filterable;
18 use ipl\Stdlib\Contract\Paginatable;
19 use ipl\Stdlib\Events;
20 use ipl\Stdlib\Filter;
21 use ipl\Stdlib\Filters;
22 use IteratorAggregate;
23 use ReflectionClass;
24 use SplObjectStorage;
25 use Traversable;
26
27 /**
28 * Represents a database query which is associated to a model and a database connection.
29 */
30 class Query implements Filterable, LimitOffsetInterface, OrderByInterface, Paginatable, IteratorAggregate
31 {
32 use Events;
33 use Filters;
34 use LimitOffset;
35 use OrderBy;
36
37 /**
38 * Event raised after assembling a {@link Select} object for the query
39 *
40 * **Example usage:**
41 *
42 * ```
43 * $query->on(Query::ON_SELECT_ASSEMBLED, function (Select $select) {
44 * // ...
45 * });
46 * ```
47 */
48 public const ON_SELECT_ASSEMBLED = 'selectAssembled';
49
50 /** @var ?int Count cache */
51 protected ?int $count = null;
52
53 /** @var Connection Database connection */
54 protected $db;
55
56 /** @var string Class to return results as */
57 protected string $resultSetClass = ResultSet::class;
58
59 /** @var Model Model to query */
60 protected $model;
61
62 /** @var array Columns to select from the model (or its relations). If empty, all columns are selected */
63 protected array $columns = [];
64
65 /** @var array Additional columns to select from the model (or its relations) */
66 protected array $withColumns = [];
67
68 /** @var array Columns not to select from the model (or its relations) */
69 protected array $withoutColumns = [];
70
71 /** @var bool Whether to peek ahead for more results */
72 protected bool $peekAhead = false;
73
74 /** @var ?Resolver Column and relation resolver */
75 protected ?Resolver $resolver = null;
76
77 /** @var ?Select Base SELECT query */
78 protected ?Select $selectBase = null;
79
80 /** @var Relation[] Relations to eager load */
81 protected array $with = [];
82
83 /** @var Relation[] Relations to utilize (join) */
84 protected array $utilize = [];
85
86 /** @var bool Whether to disable the default sorts of the model */
87 protected bool $disableDefaultSort = false;
88
89 /**
90 * Get the database connection
91 *
92 * @return Connection
93 */
94 public function getDb()
95 {
96 return $this->db;
97 }
98
99 /**
100 * Set the database connection
101 *
102 * @param Connection $db
103 *
104 * @return $this
105 */
106 public function setDb(Connection $db): static
107 {
108 $this->db = $db;
109
110 return $this;
111 }
112
113 /**
114 * Get the class to return results as
115 *
116 * @return string
117 */
118 public function getResultSetClass(): string
119 {
120 return $this->resultSetClass;
121 }
122
123 /**
124 * Set the class to return results as
125 *
126 * @param string $class
127 *
128 * @return $this
129 *
130 * @throws InvalidArgumentException If class is not an instance of {@link ResultSet}
131 */
132 public function setResultSetClass(string $class): static
133 {
134 if (! (new ReflectionClass($class))->newInstanceWithoutConstructor() instanceof ResultSet) {
135 throw new InvalidArgumentException(
136 $class . ' must be an instance of ' . ResultSet::class
137 );
138 }
139
140 $this->resultSetClass = $class;
141
142 return $this;
143 }
144
145 /**
146 * Get the model to query
147 *
148 * @return Model
149 */
150 public function getModel()
151 {
152 return $this->model;
153 }
154
155 /**
156 * Set the model to query
157 *
158 * @param Model $model
159 *
160 * @return $this
161 */
162 public function setModel(Model $model): static
163 {
164 $this->model = $model;
165 $this->getResolver()->setAlias($model, $model->getTableAlias());
166
167 return $this;
168 }
169
170 /**
171 * Get the columns to select from the model
172 *
173 * @return array
174 */
175 public function getColumns(): array
176 {
177 return $this->columns;
178 }
179
180 /**
181 * Set the filter of the query
182 *
183 * @param Filter\Chain $filter
184 *
185 * @return $this
186 */
187 public function setFilter(Filter\Chain $filter): static
188 {
189 $this->filter = $filter;
190
191 return $this;
192 }
193
194 /**
195 * Disable default sorts
196 *
197 * Prevents the default sort rules of the source model from being used
198 *
199 * @param bool $disable
200 *
201 * @return $this
202 */
203 public function disableDefaultSort(bool $disable = true): static
204 {
205 $this->disableDefaultSort = $disable;
206
207 return $this;
208 }
209
210 /**
211 * Get whether to not use the default sort rules of the source model
212 *
213 * @return bool
214 */
215 public function defaultSortDisabled(): bool
216 {
217 return $this->disableDefaultSort;
218 }
219
220
221 /**
222 * Set columns to select from the model (or its relations)
223 *
224 * By default, i.e. if you do not specify any columns, all columns of the model and
225 * any relation added via {@see with()} will be selected.
226 * Multiple calls to this method will overwrite the previously specified columns.
227 * If you specify columns from the model's relations, the relations are automatically joined upon querying.
228 * Any of the given columns is guaranteed to be selected even if previously excluded via {@see withoutColumns()}.
229 * Any previously column specified via {@see withColumns()} will not be selected if not part of the given columns.
230 *
231 * @param string|array $columns The column(s) to select
232 *
233 * @return $this
234 */
235 public function columns(string|array $columns): static
236 {
237 $this->columns = (array) $columns;
238 $this->withColumns = [];
239 $this->withoutColumns = [];
240
241 return $this;
242 }
243
244 /**
245 * Set additional columns to select from the model (or its relations)
246 *
247 * Multiple calls to this method will not overwrite the previous set columns but append the columns to the query.
248 * Any of the given columns is guaranteed to be selected even if previously excluded via {@see withoutColumns()}.
249 *
250 * @param string|array $columns The column(s) to select
251 *
252 * @return $this
253 */
254 public function withColumns(string|array $columns): static
255 {
256 $tableName = $this->getModel()->getTableAlias();
257
258 $qualifiedColumns = [];
259 foreach ((array) $columns as $alias => $column) {
260 if (! $column instanceof ExpressionInterface) {
261 $qualifiedColumns[$alias] = $this->getResolver()->qualifyPath($column, $tableName);
262 } else {
263 $qualifiedColumns[$alias] = $column;
264 }
265 }
266
267 $this->withColumns = array_merge($this->withColumns, $qualifiedColumns);
268 $this->withoutColumns = array_diff($this->withoutColumns, array_filter($this->withColumns, 'is_string'));
269
270 return $this;
271 }
272
273 /**
274 * Set columns not to select from the model (or its relations)
275 *
276 * Multiple calls to this method will not overwrite the previous set columns but append the new ones to the set.
277 *
278 * @param string|string[] $columns The column(s) not to select
279 *
280 * @return $this
281 */
282 public function withoutColumns(string|array $columns): static
283 {
284 $tableName = $this->getModel()->getTableAlias();
285
286 $qualifiedColumns = [];
287 foreach ((array) $columns as $column) {
288 if (is_string($column)) {
289 $qualifiedColumns[] = $this->getResolver()->qualifyPath($column, $tableName);
290 }
291 }
292
293 $this->withoutColumns = array_merge($this->withoutColumns, $qualifiedColumns);
294
295 return $this;
296 }
297
298 /**
299 * Get the query's resolver
300 *
301 * @return Resolver
302 */
303 public function getResolver(): Resolver
304 {
305 if ($this->resolver === null) {
306 $this->resolver = new Resolver($this);
307 }
308
309 return $this->resolver;
310 }
311
312 /**
313 * Get the SELECT base query
314 *
315 * @return Select
316 */
317 public function getSelectBase(): Select
318 {
319 if ($this->selectBase === null) {
320 $this->selectBase = new Select();
321
322 $this->selectBase->from([
323 $this->getResolver()->getAlias($this->getModel()) => $this->getModel()->getTableName()
324 ]);
325 }
326
327 return $this->selectBase;
328 }
329
330 /**
331 * Get the relations to eager load
332 *
333 * @return Relation[]
334 */
335 public function getWith(): array
336 {
337 return $this->with;
338 }
339
340 /**
341 * Add a relation to eager load
342 *
343 * @param string|array $relations
344 *
345 * @return $this
346 */
347 public function with(string|array $relations): static
348 {
349 $tableName = $this->getModel()->getTableAlias();
350 foreach ((array) $relations as $relation) {
351 $relation = $this->getResolver()->qualifyPath($relation, $tableName);
352 $this->with[$relation] = $this->getResolver()->resolveRelation($relation);
353 }
354
355 return $this;
356 }
357
358 /**
359 * Remove an eager loaded relation
360 *
361 * @param string|array $relations
362 *
363 * @return $this
364 */
365 public function without(string|array $relations): static
366 {
367 $tableName = $this->getModel()->getTableAlias();
368 foreach ((array) $relations as $relation) {
369 $relation = $this->getResolver()->qualifyPath($relation, $tableName);
370 unset($this->with[$relation]);
371 }
372
373 return $this;
374 }
375
376 /**
377 * Get utilized (joined) relations
378 *
379 * @return Relation[]
380 */
381 public function getUtilize(): array
382 {
383 return $this->utilize;
384 }
385
386 /**
387 * Add a relation to utilize (join)
388 *
389 * @param string $path
390 *
391 * @return $this
392 */
393 public function utilize(string $path): static
394 {
395 $path = $this->getResolver()->qualifyPath($path, $this->getModel()->getTableAlias());
396 $this->utilize[$path] = $this->getResolver()->resolveRelation($path);
397
398 return $this;
399 }
400
401 /**
402 * Remove a utilized (joined) relation
403 *
404 * @param string $path
405 *
406 * @return $this
407 */
408 public function omit(string $path): static
409 {
410 $path = $this->getResolver()->qualifyPath($path, $this->getModel()->getTableAlias());
411 unset($this->utilize[$path]);
412
413 return $this;
414 }
415
416 /**
417 * Assemble and return the SELECT query
418 *
419 * @return Select
420 */
421 public function assembleSelect(): Select
422 {
423 $columns = $this->getColumns();
424 $model = $this->getModel();
425 $resolver = $this->getResolver();
426 $select = clone $this->getSelectBase();
427
428 if (empty($columns)) {
429 $columns = $resolver->getSelectColumns($model);
430
431 foreach ($this->getWith() as $path => $relation) {
432 foreach ($resolver->getSelectColumns($relation->getTarget()) as $alias => $column) {
433 if (is_int($alias)) {
434 $columns[] = "$path.$column";
435 } else {
436 $columns[] = "$path.$alias";
437 }
438 }
439 }
440
441 $columns = array_merge($columns, $this->withColumns);
442 $customAliases = array_flip(array_filter(array_keys($this->withColumns), 'is_string'));
443 } else {
444 $columns = array_merge($columns, $this->withColumns);
445 $customAliases = array_flip(array_filter(array_keys($columns), 'is_string'));
446 }
447
448 $resolved = $this->groupColumnsByTarget($resolver->requireAndResolveColumns($columns));
449 $omitted = $this->groupColumnsByTarget($resolver->requireAndResolveColumns($this->withoutColumns));
450 foreach ($resolved as $target) {
451 $targetColumns = $resolved[$target]->getArrayCopy();
452 if (isset($omitted[$target])) {
453 $toExclude = $omitted[$target]->getArrayCopy();
454 $targetColumns = array_filter($targetColumns, function ($column, $alias) use ($toExclude) {
455 if (is_string($alias) && isset($toExclude[$alias])) {
456 return false;
457 }
458
459 if (is_string($alias)) {
460 return ! in_array($alias, $toExclude, true);
461 }
462
463 return ! in_array($column, $toExclude, true);
464 }, ARRAY_FILTER_USE_BOTH);
465 }
466
467 if (! empty($customAliases)) {
468 $customColumns = array_intersect_key($targetColumns, $customAliases);
469 $targetColumns = array_diff_key($targetColumns, $customAliases);
470
471 $select->columns($resolver->qualifyColumns($customColumns, $target));
472 }
473
474 $select->columns(
475 $resolver->qualifyColumnsAndAliases(
476 $targetColumns,
477 $target,
478 $target !== $model
479 )
480 );
481 }
482
483 $filter = clone $this->getFilter();
484 FilterProcessor::resolveFilter($filter, $this);
485 $where = FilterProcessor::assembleFilter($filter);
486 if ($where) {
487 $select->where(...array_reverse($where));
488 }
489
490 $this->order($select);
491
492 $joinedRelations = [];
493 foreach ($this->getWith() + $this->getUtilize() as $path => $_) {
494 foreach ($resolver->resolveRelations($path) as $relationPath => $relation) {
495 if (isset($joinedRelations[$relationPath])) {
496 continue;
497 }
498
499 foreach ($relation->resolve() as [$source, $target, $relatedKeys]) {
500 /** @var Model $source */
501 /** @var Model $target */
502
503 $sourceAlias = $resolver->getAlias($source);
504 $targetAlias = $resolver->getAlias($target);
505
506 $conditions = [];
507 foreach ($relatedKeys as $fk => $ck) {
508 $conditions[] = sprintf(
509 '%s = %s',
510 $resolver->qualifyColumn($fk, $targetAlias),
511 $resolver->qualifyColumn($ck, $sourceAlias)
512 );
513 }
514
515 $table = [$targetAlias => $target->getTableName()];
516
517 switch ($relation->getJoinType()) {
518 case 'LEFT':
519 $select->joinLeft($table, $conditions);
520
521 break;
522 case 'RIGHT':
523 $select->joinRight($table, $conditions);
524
525 break;
526 case 'INNER':
527 default:
528 $select->join($table, $conditions);
529 }
530 }
531
532 $joinedRelations[$relationPath] = true;
533 }
534 }
535
536 if ($this->hasLimit()) {
537 $limit = $this->getLimit();
538
539 if ($this->peekAhead) {
540 ++$limit;
541 }
542
543 $select->limit($limit);
544 }
545 if ($this->hasOffset()) {
546 $select->offset($this->getOffset());
547 }
548
549 $this->emit(static::ON_SELECT_ASSEMBLED, [$select]);
550
551 return $select;
552 }
553
554 /**
555 * Create and return the hydrator
556 *
557 * @return Hydrator
558 */
559 public function createHydrator(): Hydrator
560 {
561 $hydrator = new Hydrator($this);
562
563 $hydrator->add($this->getModel()->getTableAlias());
564 foreach ($this->getWith() as $path => $_) {
565 $hydrator->add($path);
566 }
567
568 return $hydrator;
569 }
570
571 /**
572 * Derive a new query to load the specified relation from a concrete model
573 *
574 * @param string $relation
575 * @param Model $source
576 *
577 * @return static
578 *
579 * @throws InvalidArgumentException If the relation with the given name does not exist
580 */
581 public function derive($relation, Model $source): static
582 {
583 // TODO: Think of a way to merge derive() and createSubQuery()
584 return $this->createSubQuery(
585 $this->getResolver()->getRelations($source)->get($relation)->getTarget(),
586 $this->getResolver()->qualifyPath($relation, $source->getTableAlias()),
587 $source
588 );
589 }
590
591 /**
592 * Create a sub-query linked to rows of this query
593 *
594 * @param Model $target The model to query
595 * @param string $targetPath The target's absolute relation path
596 * @param ?Model $from The source model
597 * @param bool $link Whether the query should be linked to the parent query
598 *
599 * @return static
600 */
601 public function createSubQuery(Model $target, string $targetPath, ?Model $from = null, bool $link = true): static
602 {
603 $subQuery = (new static())
604 ->setDb($this->getDb())
605 ->setModel($target);
606
607 $sourceParts = array_reverse(explode('.', $targetPath));
608 $sourceParts[0] = $target->getTableAlias();
609
610 $subQueryResolver = $subQuery->getResolver();
611 $sourcePath = join('.', $sourceParts);
612 $subQueryTarget = $subQueryResolver->resolveRelation($sourcePath)->getTarget();
613
614 $subQuery->utilize($sourcePath); // TODO: Don't join if there's a matching foreign key
615
616 if (! $link) {
617 return $subQuery->columns(array_map(function ($keyName) use ($sourcePath) {
618 return "$sourcePath.$keyName";
619 }, (array) $subQueryTarget->getKeyName()));
620 }
621
622 // TODO: Should be done by the caller. Though, that's not possible until we've got a filter abstraction
623 // which allows to post-pone filter column qualification.
624 $subQueryResolver->setAliasPrefix('sub_');
625
626 $resolver = $this->getResolver();
627 $baseAlias = $resolver->getAlias($this->getModel());
628 $sourceAlias = $subQueryResolver->getAlias($subQueryTarget);
629
630 $subQueryConditions = [];
631 foreach ((array) $this->getModel()->getKeyName() as $column) {
632 $fk = $subQueryResolver->qualifyColumn($column, $sourceAlias);
633
634 if (isset($from->$column)) {
635 $subQueryConditions["$fk = ?"] = $resolver
636 ->getBehaviors($from)
637 ->persistProperty($from->$column, $column);
638 } else {
639 $subQueryConditions[] = "$fk = " . $resolver->qualifyColumn($column, $baseAlias);
640 }
641 }
642
643 $subQuery->getSelectBase()->where($subQueryConditions);
644
645 return $subQuery;
646 }
647
648 /**
649 * Dump the query
650 *
651 * @return array
652 */
653 public function dump(): array
654 {
655 return $this->getDb()->getQueryBuilder()->assembleSelect($this->assembleSelect());
656 }
657
658 /**
659 * Execute the query
660 *
661 * @return ResultSet
662 */
663 public function execute(): ResultSet
664 {
665 $class = $this->getResultSetClass();
666 /** @var ResultSet $class Just for type hinting. $class is of course a string */
667
668 return $class::fromQuery($this);
669 }
670
671 /**
672 * Fetch and return the first result
673 *
674 * @return Model|null Null in case there's no result
675 */
676 public function first(): ?Model
677 {
678 return $this->execute()->current();
679 }
680
681 /**
682 * Set whether to peek ahead for more results
683 *
684 * Enabling this causes the current query limit to be increased by one. The potential extra row being yielded will
685 * be removed from the result set. Note that this only applies when fetching multiple results of limited queries.
686 *
687 * @param bool $peekAhead
688 *
689 * @return $this
690 */
691 public function peekAhead(bool $peekAhead = true): static
692 {
693 $this->peekAhead = $peekAhead;
694
695 return $this;
696 }
697
698 /**
699 * Yield the query's results
700 *
701 * @return Generator
702 */
703 public function yieldResults(): Generator
704 {
705 $select = $this->assembleSelect();
706 $stmt = $this->getDb()->select($select);
707 $stmt->setFetchMode(\PDO::FETCH_ASSOC);
708
709 $hydrator = $this->createHydrator();
710 $modelClass = get_class($this->getModel());
711
712 foreach ($stmt as $row) {
713 yield $hydrator->hydrate($row, new $modelClass());
714 }
715 }
716
717 public function count(): int
718 {
719 if ($this->count === null) {
720 $this->count = $this->getDb()->select($this->assembleSelect()->getCountQuery())->fetchColumn(0);
721 }
722
723 return $this->count;
724 }
725
726 public function getIterator(): Traversable
727 {
728 return $this->execute();
729 }
730
731 /**
732 * Group columns from {@link Resolver::requireAndResolveColumns()} by target models
733 *
734 * @param Generator $columns
735 *
736 * @return SplObjectStorage
737 */
738 protected function groupColumnsByTarget(Generator $columns): SplObjectStorage
739 {
740 $columnStorage = new SplObjectStorage();
741
742 foreach ($columns as [$target, $alias, $column]) {
743 if (! $columnStorage->offsetExists($target)) {
744 $resolved = new ArrayObject();
745 $columnStorage->offsetSet($target, $resolved);
746 } else {
747 $resolved = $columnStorage[$target];
748 }
749
750 if (is_int($alias)) {
751 $resolved[] = $column;
752 } else {
753 $resolved[$alias] = $column;
754 }
755 }
756
757 return $columnStorage;
758 }
759
760 /**
761 * Resolve, require and apply ORDER BY columns
762 *
763 * @param Select $select
764 *
765 * @return $this
766 */
767 protected function order(Select $select): static
768 {
769 $orderBy = $this->getOrderBy();
770 $defaultSort = [];
771 if (! $this->defaultSortDisabled()) {
772 $defaultSort = (array) $this->getModel()->getDefaultSort();
773 }
774
775 if (empty($orderBy)) {
776 if (empty($defaultSort)) {
777 return $this;
778 }
779
780 $orderBy = SortUtil::createOrderBy($defaultSort);
781 }
782
783 $columns = [];
784 $directions = [];
785 $orderByResolved = [];
786 $resolver = $this->getResolver();
787 $selectedColumns = $select->getColumns();
788
789 foreach ($orderBy as $part) {
790 [$column, $direction] = $part;
791
792 if (! $column instanceof ExpressionInterface && isset($selectedColumns[$column])) {
793 // If it's a custom alias, we have no other way of knowing it,
794 // unless the caller explicitly uses it in the sort rule.
795 $orderByResolved[] = $part;
796 } else {
797 // Prepare flat ORDER BY column(s) and direction(s) for requireAndResolveColumns()
798 $columns[] = $column;
799 $directions[] = $direction;
800 }
801 }
802
803 foreach ($resolver->requireAndResolveColumns($columns) as [$model, $alias, $column]) {
804 $direction = array_shift($directions);
805 $selectColumns = $resolver->getSelectColumns($model);
806 $tableName = $resolver->getAlias($model);
807
808 if ($column instanceof ExpressionInterface) {
809 if (is_int($alias) && $column instanceof AliasedExpression) {
810 $alias = $column->getAlias();
811 } elseif (is_string($alias) && $model !== $this->getModel()) {
812 $alias = $resolver->qualifyColumnAlias($alias, $tableName);
813 } elseif ($column instanceof ResolvedExpression) {
814 // We are doing this in an else if, since a resolved expression can't be an aliased
815 // expression at the same time and thus doesn't influence the functionality in any way.
816 $column->setColumns($resolver->qualifyColumns($column->getResolvedColumns()));
817 }
818
819 if (is_string($alias) && isset($selectedColumns[$alias])) {
820 // An expression's alias can only be used if the expression is also selected
821 $column = $alias;
822 }
823 } else {
824 if (isset($selectColumns[$column])) {
825 $column = $selectColumns[$column];
826 }
827
828 if (is_string($column)) {
829 $column = $resolver->qualifyColumn($column, $tableName);
830 }
831 }
832
833 $orderByResolved[] = [$column, $direction];
834 }
835
836 $select->orderBy($orderByResolved);
837
838 return $this;
839 }
840
841 public function __clone()
842 {
843 $this->resolver = clone $this->resolver;
844
845 if ($this->filter !== null) {
846 $this->filter = clone $this->filter;
847 }
848
849 if ($this->selectBase !== null) {
850 $this->selectBase = clone $this->selectBase;
851 }
852 }
853 }