• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

ICanBoogie / ActiveRecord / 46308876518

29 Nov 2026 08:51PM UTC coverage: 92.874% (+0.4%) from 92.444%
46308876518

push

github

olvlvl
fix(query): correct the results of the aggregates

`count()` returned the count of the first group with `group()`, ignored
`take()` and `SELECT DISTINCT`, and failed with `skip()`. It now counts
the rows that the query returns, with a subquery when needed.

`average()`, `sum()`, `minimum()`, `maximum()`, and `$rc` truncated
decimal values, and the computations failed when no record matched. Their
return types now allow what the databases return.

`count()` and the computations failed on PostgreSQL when the query was
ordered, so the `ORDER BY` clause is no longer rendered where it can't
change the result.

BREAKING CHANGE: `Query::count()` counts the groups of a grouped query,
within the limits of `skip()` and `take()`. `average()` returns `?float`,
`sum()` returns `int|float`, and `minimum()` and `maximum()` return
`int|float|string|null`. `Query::$rc` and `Statement::$rc` can be a
`float`. `skip()` with a computation throws `LogicException`.

20 of 22 new or added lines in 1 file covered. (90.91%)

1955 of 2105 relevant lines covered (92.87%)

75.54 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

84.64
/lib/ActiveRecord/Query.php
1
<?php
2

3
namespace ICanBoogie\ActiveRecord;
4

5
use DateTimeInterface;
6
use ICanBoogie\ActiveRecord;
7
use InvalidArgumentException;
8
use IteratorAggregate;
9
use LogicException;
10
use PDO;
11
use Traversable;
12

13
use function array_map;
14
use function array_merge;
15
use function array_shift;
16
use function count;
17
use function func_get_args;
18
use function func_num_args;
19
use function implode;
20
use function is_array;
21
use function is_numeric;
22
use function is_string;
23
use function preg_match;
24
use function preg_replace;
25
use function substr;
26
use function trigger_error;
27

28
use const PHP_INT_MAX;
29

30
/**
31
 * @template-covariant TRecord of ActiveRecord
32
 *
33
 * @implements IteratorAggregate<TRecord>
34
 *
35
 * The class offers many features to compose model queries. Most query-related
36
 * methods of the {@see Model} class create a {@see Query} object returned for
37
 * further specification, such as filters or limits.
38
 */
39
class Query implements IteratorAggregate
40
{
41
    public const int LIMIT_MAX = PHP_INT_MAX;
42

43
    /**
44
     * Part of the `SELECT` clause.
45
     */
46
    private ?string $select = null;
47

48
    /**
49
     * `JOIN` clauses.
50
     *
51
     * @var non-empty-string[]
52
     */
53
    private array $joins_ = [];
54

55
    /**
56
     * @var non-empty-string[]
57
     */
58
    public array $joins {
59
        get => $this->joins_;
60
    }
61

62
    /**
63
     * Joints arguments.
64
     *
65
     * @var mixed[]
66
     */
67
    private array $joins_args_ = [];
68

69
    /**
70
     * @var mixed[]
71
     */
72
    public array $joins_args {
73
        get => $this->joins_args_;
74
    }
75

76
    /**
77
     * Collected conditions.
78
     *
79
     * @var non-empty-string[]
80
     */
81
    private array $conditions_ = [];
82

83
    /**
84
     * @var non-empty-string[]
85
     */
86
    public array $conditions {
87
        get => $this->conditions_;
88
    }
89

90
    /**
91
     * Arguments for the conditions.
92
     *
93
     * @var mixed[]
94
     */
95
    private array $conditions_args_ = [];
96

97
    /**
98
     * @var mixed[]
99
     */
100
    public array $conditions_args {
101
        get => $this->conditions_args_;
102
    }
103

104
    /**
105
     * Part of the `HAVING` clause.
106
     */
107
    private ?string $having = null;
108

109
    /**
110
     * Arguments to the `HAVING` clause.
111
     *
112
     * @var mixed[]
113
     */
114
    private array $having_args_ = [];
115

116
    /**
117
     * @var mixed[]
118
     */
119
    public array $having_args {
120
        get => $this->having_args_;
121
    }
122

123
    /**
124
     * Returns the arguments to the query, which include joins arguments, conditions arguments,
125
     * and _having_ arguments.
126
     *
127
     * @var mixed[]
128
     */
129
    public array $args {
130
        get => array_merge($this->joins_args_, $this->conditions_args_, $this->having_args_);
131
    }
132

133
    /**
134
     * Part of the `GROUP BY` clause.
135
     */
136
    private ?string $group = null;
137

138
    /**
139
     * Part of the `ORDER BY` clause.
140
     *
141
     * @var mixed[]
142
     */
143
    private array $order = [];
144

145
    /**
146
     * The number of records the skip before fetching.
147
     */
148
    private ?int $skip = null;
149

150
    /**
151
     * The maximum number of records to take when fetching.
152
     */
153
    private ?int $take = null;
154

155
    /**
156
     * Fetch mode.
157
     *
158
     * @var mixed[]
159
     */
160
    private array $mode = [];
161

162
    /**
163
     * The relations to preload on the fetched records, by name.
164
     *
165
     * @var array<string, Relation>
166
     */
167
    private array $includes = [];
168

169
    /**
170
     * @param Model<TRecord> $model The model to query.
171
     */
172
    public function __construct(
173
        public readonly Model $model // @phpstan-ignore generics.variance
174
    )
175
    {
176
    }
158 ✔
177

178
    /**
179
     * Quotes an identifier using the model's connection driver.
180
     */
181
    private function quote_identifier(string $identifier): string
182
    {
183
        return $this->model->connection->quote_identifier($identifier);
119 ✔
184
    }
185

186
    /*
187
     * Rendering
188
     */
189

190
    /**
191
     * Convert the query into a string.
192
     *
193
     * @return string
194
     */
195
    public function __toString(): string
196
    {
197
        return $this->resolve_statement(
105 ✔
198
            $this->render_select() . ' ' .
105 ✔
199
            $this->render_from() .
105 ✔
200
            $this->render_main()
105 ✔
201
        );
105 ✔
202
    }
203

204
    /**
205
     * Render the `SELECT` clause.
206
     *
207
     * Without a {@see select()}, only the columns of the queried record are selected.
208
     *
209
     * @return string
210
     */
211
    private function render_select(): string
212
    {
213
        return 'SELECT ' . ($this->select ?? $this->render_record_select());
105 ✔
214
    }
215

216
    /**
217
     * Renders the columns of the queried record: its table and its parents' tables, which
218
     * `{self_and_related}` joins in, but not the tables added with {@see join()}.
219
     */
220
    private function render_record_select(): string
221
    {
222
        $columns = [];
93 ✔
223

224
        for ($table = $this->model; $table; $table = $table->parent) {
93 ✔
225
            $columns[] = $this->quote_identifier($table->alias) . '.*';
93 ✔
226
        }
227

228
        return implode(', ', $columns);
93 ✔
229
    }
230

231
    /**
232
     * Render the `FROM` clause.
233
     *
234
     * The rendered `FROM` clause might include some JOINS too.
235
     *
236
     * @return string
237
     */
238
    private function render_from(): string
239
    {
240
        return 'FROM {self_and_related}';
136 ✔
241
    }
242

243
    /**
244
     * Renders the `JOIN` clauses.
245
     *
246
     * @return string
247
     */
248
    private function render_joins(): string
249
    {
250
        return implode(' ', $this->joins_);
16 ✔
251
    }
252

253
    /**
254
     * Render the main body of the query, without the `SELECT` and `FROM` clauses.
255
     *
256
     * @param bool $ordered Whether to render the `ORDER` clause.
257
     */
258
    private function render_main(bool $ordered = true): string
259
    {
260
        $query = '';
136 ✔
261

262
        if ($this->joins_) {
136 ✔
263
            $query = ' ' . $this->render_joins();
16 ✔
264
        }
265

266
        $conditions = $this->conditions_;
136 ✔
267

268
        if ($conditions) {
136 ✔
269
            $query .= ' WHERE ' . implode(' AND ', $conditions);
83 ✔
270
        }
271

272
        $group = $this->group;
136 ✔
273

274
        if ($group) {
136 ✔
275
            $query .= ' GROUP BY ' . $group;
12 ✔
276

277
            $having = $this->having;
12 ✔
278

279
            if ($having) {
12 ✔
280
                $query .= ' HAVING ' . $having;
2 ✔
281
            }
282
        }
283

284
        $order = $this->order;
136 ✔
285

286
        if ($ordered && $order) {
136 ✔
287
            $query .= ' ' . $this->render_order($order);
12 ✔
288
        }
289

290
        $skip = $this->skip;
136 ✔
291
        $take = $this->take;
136 ✔
292

293
        if ($skip || $take) {
136 ✔
294
            $query .= ' ' . $this->render_skip_and_take($skip, $take);
54 ✔
295
        }
296

297
        return $query;
136 ✔
298
    }
299

300
    /**
301
     * Render the `ORDER` clause.
302
     *
303
     * @param mixed[] $order
304
     */
305
    private function render_order(array $order): string
306
    {
307
        if (count($order) == 1) {
12 ✔
308
            $raw = $order[0];
11 ✔
309
            assert(is_string($raw));
×
310
            $rendered = preg_replace(
11 ✔
311
                '/-([a-zA-Z0-9_]+)/',
11 ✔
312
                '$1 DESC',
11 ✔
313
                $raw
11 ✔
314
            );
11 ✔
315

316
            return 'ORDER BY ' . $rendered;
11 ✔
317
        }
318

319
        $connection = $this->model->connection;
1 ✔
320

321
        $field = array_shift($order);
1 ✔
322
        assert(is_string($field));
×
323
        $field_values = is_array($order[0]) ? $order[0] : $order;
1 ✔
324
        // @phpstan-ignore-next-line
325
        $field_values = array_map(fn($v) => $connection->quote($v), $field_values);
1 ✔
326

327
        return "ORDER BY FIELD($field, " . implode(', ', $field_values) . ")";
1 ✔
328
    }
329

330
    /**
331
     * Render the `LIMIT` and `OFFSET` clauses.
332
     */
333
    private function render_skip_and_take(?int $skip, ?int $take): string
334
    {
335
        if ($skip && $take) {
54 ✔
336
            return "LIMIT $take OFFSET $skip";
3 ✔
337
        } elseif ($skip) {
52 ✔
338
            return "LIMIT " . self::LIMIT_MAX . " OFFSET $skip";
3 ✔
339
        } elseif ($take) {
49 ✔
340
            return "LIMIT $take";
49 ✔
341
        }
342

343
        return '';
×
344
    }
345

346
    /*
347
     *
348
     */
349

350
    /**
351
     * Resolve the placeholders of a statement.
352
     *
353
     * Note: Currently, the method forwards the statement to the model's resolve_statement() method.
354
     */
355
    private function resolve_statement(string $statement): string
356
    {
357
        return $this->model->resolve_statement($statement);
105 ✔
358
    }
359

360
    /**
361
     * Define the `SELECT` clause.
362
     *
363
     * @param non-empty-string $expression The expression of the `SELECT` clause. e.g. 'nid, title'.
364
     *
365
     * @return $this
366
     */
367
    public function select(string $expression): static
368
    {
369
        $this->select = $expression;
21 ✔
370

371
        return $this;
21 ✔
372
    }
373

374
    /**
375
     * Add a `JOIN` clause.
376
     *
377
     * @param ?non-empty-string $expression
378
     *     A raw `JOIN` clause.
379
     * @param ?Query<ActiveRecord> $query
380
     *     A {@link execute} instance, it is rendered as a string and used as a subquery of the `JOIN` clause.
381
     *     The `$options` parameter can be used to customize the output.
382
     * @param ?class-string<ActiveRecord> $record
383
     *     An ActiveRecord class, its model is joined. Unless `$on` is provided, the join is established from the
384
     *     relations of the queried model to the joined model, or the relations of the joined model to the queried
385
     *     model.
386
     * @param non-empty-string $mode
387
     *     Join mode. Default: "INNER"
388
     * @param ?non-empty-string $as
389
     *     The alias of the joined subquery or model. Default: The alias of the subquery's model, or of the joined
390
     *     model.
391
     * @param ?non-empty-string $on
392
     *     How the join is created. Default: The primary key of the subquery's model with `$query`, resolved from the
393
     *     relations between the models with `$record`.
394
     *
395
     *     - With `$query`, the name of a column.
396
     *     - With `$record`, a column name, which renders as `USING(column)` and must exist on both sides (on the
397
     *       joined model, and on the queried model or a model already joined), or an `ON` expression such as
398
     *       `"a.school_id = b.school_id"`. A value made of word characters only is taken as a column name, anything
399
     *       else as an expression.
400
     *
401
     * @return $this
402
     *
403
     * <pre>
404
     * <?php
405
     *
406
     * # using an ActiveRecord class.
407
     *
408
     * $query->join(record: Comment::class);
409
     *
410
     * # joining a model on a column, after another join.
411
     *
412
     * $query->join(record: PhotoSession::class)->join(record: School::class, on: 'school_id');
413
     *
414
     * # using a subquery
415
     *
416
     * $subquery = get_model('updates')
417
     * ->select('updated_at, $subscriber_id, update_hash')
418
     * ->order('updated_at DESC')
419
     *
420
     * $query->join(query: $subquery, on: 'subscriber_id');
421
     *
422
     * # using a raw clause
423
     *
424
     * $query->join(expression: "INNER JOIN `articles` USING(`nid`)");
425
     * </pre>
426
     */
427
    public function join(
428
        ?string $expression = null,
429
        ?Query $query = null,
430
        ?string $record = null,
431
        string $mode = 'INNER',
432
        ?string $as = null,
433
        ?string $on = null,
434
    ): static {
435
        if ($expression) {
19 ✔
436
            $this->joins_[] = $expression;
10 ✔
437

438
            return $this;
10 ✔
439
        }
440

441
        if ($query) {
9 ✔
442
            $this->join_with_query($query, mode: $mode, as: $as, on: $on);
2 ✔
443

444
            return $this;
2 ✔
445
        }
446

447
        if ($record) {
7 ✔
448
            $model = $this->model->models->model_for_record($record);
7 ✔
449

450
            $this->join_with_model($model, mode: $mode, as: $as, on: $on);
7 ✔
451

452
            return $this;
6 ✔
453
        }
454

455
        throw new LogicException("One of [ expression, query, record ] needs to be defined");
×
456
    }
457

458
    /**
459
     * Join a subquery to the query.
460
     *
461
     * @param Query<ActiveRecord> $query
462
     * @param non-empty-string $mode
463
     *     Join mode. Default: "INNER".
464
     * @param ?non-empty-string $as
465
     *     The alias of the subquery. Default: The query's model alias.
466
     * @param ?non-empty-string $on
467
     *     The column on which the joint is created. Default: The query's model primary key.
468
     */
469
    private function join_with_query(
470
        Query $query,
471
        string $mode = 'INNER',
472
        ?string $as = null,
473
        ?string $on = null,
474
    ): void {
475
        $as ??= $query->model->alias;
2 ✔
476
        $on ??= $query->model->primary;
2 ✔
477

478
        if ($on) {
2 ✔
479
            assert(is_string($on));
×
480

481
            $on = $this->render_join_on($on, $as, $query);
2 ✔
482
        }
483

484
        if ($on) {
2 ✔
485
            $on = ' ' . $on;
2 ✔
486
        }
487

488
        $this->joins_[] = "$mode JOIN($query) " . $this->quote_identifier($as) . "$on";
2 ✔
489
        $this->joins_args_ = array_merge($this->joins_args_, $query->args);
2 ✔
490
    }
491

492
    /**
493
     * Join a model to the query.
494
     *
495
     * Unless `$on` is provided, the join is established from the relations of the queried model to
496
     * the joined model, or the relations of the joined model to the queried model.
497
     *
498
     * @param Model<*> $model
499
     * @param non-empty-string $mode
500
     *     Join mode.
501
     * @param ?non-empty-string $as
502
     *     The alias of the model. Default: The model's alias.
503
     * @param ?non-empty-string $on
504
     *     The column on which the join is created, or an _ON_ expression. Default: Resolved from
505
     *     the relations between the models.
506
     *
507
     * @throws LogicException if the join cannot be established.
508
     */
509
    private function join_with_model(
510
        Model $model,
511
        string $mode = 'INNER',
512
        ?string $as = null,
513
        ?string $on = null,
514
    ): void {
515
        $as ??= $model->alias;
7 ✔
516

517
        if ($on === null) {
7 ✔
518
            $on = $this->resolve_join_on_from_relations($model, $as);
5 ✔
519
        } elseif (preg_match('/^\w+$/', $on)) {
2 ✔
520
            $on = 'USING(' . $this->quote_identifier($on) . ')';
1 ✔
521
        } else {
522
            $on = "ON $on";
1 ✔
523
        }
524

525
        $this->joins_[] = "$mode JOIN " . $this->quote_identifier($model->name)
6 ✔
526
            . ' AS ' . $this->quote_identifier($as)
6 ✔
527
            . ' ' . $on;
6 ✔
528
    }
529

530
    /**
531
     * Resolve the `USING` or `ON` clause joining a model from the relations between the models.
532
     *
533
     * @param Model<*> $model
534
     * @param non-empty-string $as
535
     *
536
     * @throws RelationNotFound if no relation links the models.
537
     * @throws AmbiguousRelation if more than one relation links the models.
538
     * @throws LogicException if the columns cannot be resolved.
539
     */
540
    private function resolve_join_on_from_relations(Model $model, string $as): string
541
    {
542
        $queried = $this->model;
5 ✔
543
        $queried_class = $queried->activerecord_class;
5 ✔
544
        $joined_class = $model->activerecord_class;
5 ✔
545

546
        [ $queried_column, $joined_column ] = $queried->relations->columns_to($model);
5 ✔
547

548
        if (!$model->schema->has_column($joined_column)) {
4 ✔
549
            throw new LogicException("Column `$joined_column` not found in the table of $joined_class. Specify `on`.");
×
550
        }
551

552
        if ($queried_column === $joined_column && $queried->schema->has_column($queried_column)) {
4 ✔
553
            return 'USING(' . $this->quote_identifier($queried_column) . ')';
3 ✔
554
        }
555

556
        // The column might belong to the table of a parent model.
557
        $target = $queried;
1 ✔
558

559
        while ($target instanceof Model && !$target->schema->has_column($queried_column)) {
1 ✔
560
            $target = $target->parent;
×
561
        }
562

563
        if (!$target) {
1 ✔
564
            throw new LogicException(
×
565
                "Unable to resolve column `$queried_column` from model $queried_class. Specify `on`."
×
566
            );
×
567
        }
568

569
        return 'ON ' . $this->quote_identifier($target->alias) . '.' . $this->quote_identifier($queried_column)
1 ✔
570
            . ' = ' . $this->quote_identifier($as) . '.' . $this->quote_identifier($joined_column);
1 ✔
571
    }
572

573
    /**
574
     * Render the `on` join option.
575
     *
576
     * The method tries to determine the best solution between `ON` and `USING`.
577
     *
578
     * @param non-empty-string $column
579
     * @param non-empty-string $as
580
     * @param Query<ActiveRecord> $query
581
     */
582
    private function render_join_on(string $column, string $as, Query $query): string
583
    {
584
        if ($query->model->schema->has_column($column) && $this->model->schema->has_column($column)) {
2 ✔
585
            return 'USING(' . $this->quote_identifier($column) . ')';
2 ✔
586
        }
587

588
        $target = $this->model;
×
589

590
        while ($target instanceof Model) {
×
591
            if ($target->schema->has_column($column)) {
×
592
                break;
×
593
            }
594

595
            $target = $target->parent;
×
596
        }
597

598
        if (!$target) {
×
599
            $model_class = $this->model::class;
×
600

601
            throw new InvalidArgumentException("Unable to resolve column `$column` from model $model_class");
×
602
        }
603

604
        return 'ON ' . $this->quote_identifier($as) . '.' . $this->quote_identifier($column)
×
605
            . ' = ' . $this->quote_identifier($target->alias) . '.' . $this->quote_identifier($column);
×
606
    }
607

608
    /**
609
     * Parses the conditions for the {@see where()} and {@see having()} methods.
610
     *
611
     * {@see DateTimeInterface} conditions are converted to strings.
612
     *
613
     * @param mixed ...$conditions_and_args
614
     *
615
     * @return array{ non-empty-string|null, mixed[] } An array made of the condition string and its arguments.
616
     */
617
    private function deferred_parse_conditions(mixed ...$conditions_and_args): array
618
    {
619
        $conditions = array_shift($conditions_and_args);
90 ✔
620
        $args = $conditions_and_args;
90 ✔
621

622
        if (is_array($conditions)) {
90 ✔
623
            $c = '';
77 ✔
624
            $conditions_args = [];
77 ✔
625

626
            foreach ($conditions as $column => $arg) {
77 ✔
627
                if (is_array($arg) || $arg instanceof self) {
77 ✔
628
                    $joined = '';
37 ✔
629

630
                    if (is_array($arg)) {
37 ✔
631
                        foreach ($arg as $value) {
37 ✔
632
                            // @phpstan-ignore-next-line argument.type
633
                            $joined .= ',' . (is_numeric($value) ? $value : $this->model->connection->quote($value));
37 ✔
634
                        }
635

636
                        $joined = substr($joined, 1);
37 ✔
637
                    } else {
638
                        $joined = (string)$arg;
×
639
                        $conditions_args = array_merge($conditions_args, $arg->args);
×
640
                    }
641

642
                    $negated = $column[0] == '!';
37 ✔
643
                    $identifier = $this->quote_identifier($negated ? substr($column, 1) : $column);
37 ✔
644

645
                    $c .= ' AND ' . $identifier . ($negated ? ' NOT IN(' : ' IN(') . $joined . ')';
37 ✔
646
                } else {
647
                    $conditions_args[] = $arg;
47 ✔
648

649
                    $negated = $column[0] == '!';
47 ✔
650
                    $identifier = $this->quote_identifier($negated ? substr($column, 1) : $column);
47 ✔
651

652
                    $c .= ' AND ' . $identifier . ($negated ? ' != ' : ' = ') . '?';
47 ✔
653
                }
654
            }
655

656
            $conditions = substr($c, 5);
77 ✔
657
        } else {
658
            assert(is_null($conditions) || is_string($conditions));
×
659

660
            $conditions_args = [];
19 ✔
661

662
            if ($args) {
19 ✔
663
                if (is_array($args[0])) {
13 ✔
664
                    $conditions_args = $args[0];
×
665
                } else {
666
                    #
667
                    # We dereference values, otherwise the caller would get a corrupted array.
668
                    #
669
                    foreach ($args as $key => $value) {
13 ✔
670
                        $conditions_args[$key] = $value;
13 ✔
671
                    }
672
                }
673
            }
674
        }
675

676
        $cast = $this->model->connection->driver->cast_value(...);
90 ✔
677
        $conditions_args = array_map($cast, $conditions_args);
90 ✔
678

679
        return [ $conditions ? '(' . $conditions . ')' : null, $conditions_args ];
90 ✔
680
    }
681

682
    /**
683
     * Add conditions to the SQL statement.
684
     *
685
     * Conditions can either be specified as string or array.
686
     *
687
     * 1. Pure string conditions
688
     *
689
     * If you would like to add conditions to your statement, you could specify them in there,
690
     * like `$model->where('order_count = 2');`. This will find all the entries where the
691
     * `order_count` field's value is 2.
692
     *
693
     * 2. Array conditions
694
     *
695
     * Now what if that number could vary, say as an argument from somewhere, or perhaps from the
696
     * user’s level status somewhere? The find then becomes something like:
697
     *
698
     * `$model->where('order_count = ?', 2);`
699
     *
700
     * or
701
     *
702
     * `$model->where([ 'order_count' => 2 ]);`
703
     *
704
     * Or if you want to specify two conditions, you can do it like:
705
     *
706
     * `$model->where('order_count = ? AND locked = ?', 2, false);`
707
     *
708
     * or
709
     *
710
     * `$model->where([ 'order_count' => 2, 'locked' => false ]);`
711
     *
712
     * Or if you want to specify subset conditions:
713
     *
714
     * `$model->where([ 'order_id' => [ 123, 456, 789 ] ]);`
715
     *
716
     * This will return the orders with the `order_id` 123, 456, or 789.
717
     *
718
     * 3. Modifiers
719
     *
720
     * When using the "identifier" => "value" notation, you can switch the comparison method by
721
     * prefixing the identifier with a bang "!"
722
     *
723
     * `$model->where([ '!order_id' => [ 123, 456, 789 ]]);`
724
     *
725
     * This will return the orders with the `order_id` different from 123, 456, and 789.
726
     *
727
     * `$model->where([ '!order_count' => 2 ]);`
728
     *
729
     * This will return the orders with the `order_count` different from 2.
730
     *
731
     * @param mixed ...$conditions_and_args
732
     *
733
     * @return $this
734
     */
735
    public function where(...$conditions_and_args): static
736
    {
737
        [ $conditions, $conditions_args ] = $this->deferred_parse_conditions(...$conditions_and_args);
88 ✔
738

739
        if ($conditions) {
88 ✔
740
            $this->conditions_[] = $conditions;
87 ✔
741

742
            if ($conditions_args) {
87 ✔
743
                $this->conditions_args_ = array_merge($this->conditions_args_, $conditions_args);
53 ✔
744
            }
745
        }
746

747
        return $this;
88 ✔
748
    }
749

750
    /**
751
     * @return $this
752
     * @see self::where()
753
     *
754
     */
755
    public function and(mixed ...$conditions_and_args): static
756
    {
757
        return $this->where(...$conditions_and_args);
3 ✔
758
    }
759

760
    /**
761
     * Defines the `ORDER` clause.
762
     *
763
     * @param string $order_or_field_name The order for the `ORDER` clause e.g.
764
     * 'weight, date DESC', or field to order with, in which case `$field_values` is required.
765
     * @param scalar[]|null $field_values Values of the field specified by `$order_or_field_name`.
766
     *
767
     * @return $this
768
     */
769
    public function order(string $order_or_field_name, mixed $field_values = null): static
770
    {
771
        $this->order = func_get_args();
16 ✔
772

773
        return $this;
16 ✔
774
    }
775

776
    /**
777
     * Defines the `GROUP BY` clause.
778
     *
779
     * @returns $this
780
     */
781
    public function group(string $group): static
782
    {
783
        $this->group = $group;
12 ✔
784

785
        return $this;
12 ✔
786
    }
787

788
    /**
789
     * Defines the `HAVING` clause.
790
     *
791
     * @param mixed ...$conditions_and_args
792
     *
793
     * @return $this
794
     */
795
    public function having(...$conditions_and_args): static
796
    {
797
        [ $having, $having_args ] = $this->deferred_parse_conditions(...$conditions_and_args);
2 ✔
798

799
        assert($having !== null);
×
800

801
        $this->having = $having;
2 ✔
802
        $this->having_args_ = $having_args;
2 ✔
803

804
        return $this;
2 ✔
805
    }
806

807
    /**
808
     * The number of records to skip before fetching.
809
     *
810
     * @return $this
811
     */
812
    public function skip(?int $skip): static
813
    {
814
        $this->skip = $skip;
8 ✔
815

816
        return $this;
8 ✔
817
    }
818

819
    /**
820
     * The number of records to take while fetching.
821
     *
822
     * @return $this
823
     */
824
    public function take(?int $take): static
825
    {
826
        $this->take = $take;
56 ✔
827

828
        return $this;
56 ✔
829
    }
830

831
    /**
832
     * Set the fetch mode for the query.
833
     *
834
     * @param mixed ...$mode
835
     *
836
     * @return $this
837
     *
838
     * @see http://www.php.net/manual/en/pdostatement.setfetchmode.php
839
     */
840
    public function mode(...$mode): static
841
    {
842
        $this->mode = $mode;
2 ✔
843

844
        return $this;
2 ✔
845
    }
846

847
    /**
848
     * Preload relations on the records fetched by {@see all()}, with one query per relation,
849
     * instead of one query per record when the relation is read.
850
     *
851
     * Only {@see all()} preloads, and what relies on it: {@see records()}, {@see record()}, the
852
     * `$all`, `$records` and `$record` properties, and iterating over the query (once per batch).
853
     * {@see one()} and the aggregates ignore the relations.
854
     *
855
     * ```php
856
     * foreach ($cars->query()->includes('brand') as $car) {
857
     *     echo $car->brand->name; // no query
858
     * }
859
     * ```
860
     *
861
     * @param non-empty-string ...$relations Names of relations, as declared on the model or its parents.
862
     *
863
     * @return $this
864
     *
865
     * @throws RelationNotDefined if a relation isn't defined.
866
     * @throws RelationNotPreloadable if a relation can't be preloaded, see {@see Relation::is_preloadable()}.
867
     */
868
    public function includes(string ...$relations): static
869
    {
870
        foreach ($relations as $name) {
19 ✔
871
            $relation = $this->model->relations->resolve($name);
19 ✔
872
            $relation->is_preloadable() or throw new RelationNotPreloadable($relation);
18 ✔
873

874
            $this->includes[$name] = $relation;
17 ✔
875
        }
876

877
        return $this;
17 ✔
878
    }
879

880
    /**
881
     * Prepare the query.
882
     *
883
     * We use the connection's prepare() method because the statement has already been resolved
884
     * during the __toString() method, and we don't want for the statement to be parsed twice.
885
     */
886
    private function prepare(): Statement
887
    {
888
        return $this->model->connection->prepare((string)$this);
87 ✔
889
    }
890

891
    /**
892
     * Return a prepared query.
893
     *
894
     * @deprecated Execute the query with {@see self::all()}, {@see self::one()}, or the other
895
     *     public methods instead. `#[\Deprecated]` cannot target properties, hence `trigger_error()`.
896
     */
897
    public Statement $prepared {
898
        get {
899
            trigger_error(
1 ✔
900
                "Query::\$prepared is deprecated since icanboogie/activerecord 7.0, use all() or one()",
1 ✔
901
                E_USER_DEPRECATED
1 ✔
902
            );
1 ✔
903

904
            return $this->prepare();
1 ✔
905
        }
906
    }
907

908
    /**
909
     * Prepare and executes the query.
910
     */
911
    private function execute(): Statement
912
    {
913
        $statement = $this->prepare();
86 ✔
914
        // @phpstan-ignore-next-line
915
        $statement->execute($this->args);
86 ✔
916

917
        return $statement;
86 ✔
918
    }
919

920
    /*
921
     * FINISHER
922
     */
923

924
    /**
925
     * Resolves fetch mode.
926
     *
927
     * @return array{ 0: int, 1?: mixed, 2?: mixed } Element 0 is a `PDO::FETCH_*` mode, possibly
928
     *     combined with flags.
929
     */
930
    private function resolve_fetch_mode(mixed ...$mode): array
931
    {
932
        if ($mode) {
86 ✔
933
            $args = $mode;
7 ✔
934
        } elseif ($this->mode) {
81 ✔
935
            $args = $this->mode;
×
936
        } elseif ($this->select ?? null) {
81 ✔
937
            $args = [ PDO::FETCH_ASSOC ];
2 ✔
938
        } elseif ($this->model->activerecord_class) {
79 ✔
939
            $args = [ PDO::FETCH_CLASS, $this->model->activerecord_class ];
79 ✔
940
        } else {
941
            $args = [ PDO::FETCH_CLASS, ActiveRecord::class ];
×
942
        }
943

944
        // @phpstan-ignore-next-line
945
        return $args;
86 ✔
946
    }
947

948
    /**
949
     * Execute the query and returns an array of records.
950
     *
951
     * The relations of {@see includes()} are preloaded on the records.
952
     *
953
     * @param mixed ...$mode Fetch mode.
954
     *
955
     * @return array<mixed>
956
     *
957
     * @throws LogicException if relations are included and the fetch mode doesn't produce records,
958
     *     e.g. with {@see select()} or `PDO::FETCH_COLUMN`: there is nothing to attach them to.
959
     */
960
    public function all(...$mode): array
961
    {
962
        $fetch_mode = $this->resolve_fetch_mode(...$mode);
83 ✔
963

964
        if (!$this->includes) {
83 ✔
965
            return $this->execute()->all(...$fetch_mode);
80 ✔
966
        }
967

968
        // The values of the flags depend on the PHP version, so they can't be masked by position.
969
        $base_mode = $fetch_mode[0] & ~(PDO::FETCH_PROPS_LATE | PDO::FETCH_CLASSTYPE);
14 ✔
970

971
        // `FETCH_UNIQUE` is compared as a whole: in PHP 8.4 it includes the bit of `FETCH_GROUP`,
972
        // which nests the records and must be refused.
973
        if ($base_mode !== PDO::FETCH_CLASS && $base_mode !== (PDO::FETCH_CLASS | PDO::FETCH_UNIQUE)) {
14 ✔
974
            throw new LogicException("Relations can only be included when fetching records.");
3 ✔
975
        }
976

977
        /** @var ActiveRecord[] $owners */
978
        $owners = $this->execute()->all(...$fetch_mode);
11 ✔
979

980
        foreach ($this->includes as $relation) {
11 ✔
981
            $relation->preload($owners);
11 ✔
982
        }
983

984
        return $owners;
11 ✔
985
    }
986

987
    /**
988
     * @var TRecord[]|mixed[]
989
     *
990
     * @see self::all()
991
     */
992
    public array $all {
993
        get => $this->all();
994
    }
995

996
    /**
997
     * Execute the query and return the records matching it.
998
     *
999
     * Unlike {@see all()}, which returns whatever the fetch mode produces, the result is typed.
1000
     * The relations of {@see includes()} are preloaded on the records.
1001
     *
1002
     * @return list<TRecord>
1003
     *
1004
     * @throws LogicException if {@see select()} or {@see mode()} was used, since the query might not
1005
     *     produce complete records.
1006
     */
1007
    public function records(): array
1008
    {
1009
        $this->select === null && !$this->mode
81 ✔
1010
            or throw new LogicException("Records can't be fetched with select() or mode(), use all() or one().");
81 ✔
1011

1012
        /** @var list<TRecord> */
1013
        return $this->all();
75 ✔
1014
    }
1015

1016
    /**
1017
     * @var list<TRecord>
1018
     *
1019
     * @see self::records()
1020
     */
1021
    public array $records {
1022
        get => $this->records();
1023
    }
1024

1025
    /**
1026
     * Execute the query and return the first record matching it.
1027
     *
1028
     * The relations of {@see includes()} are preloaded on the record.
1029
     *
1030
     * @return TRecord|null `null` if no record matches the query.
1031
     *
1032
     * @throws LogicException if {@see select()} or {@see mode()} was used, since the query might not
1033
     *     produce complete records.
1034
     */
1035
    public function record(): ?ActiveRecord
1036
    {
1037
        return (clone $this)->take(1)->records()[0] ?? null;
39 ✔
1038
    }
1039

1040
    /**
1041
     * @var TRecord|null
1042
     *
1043
     * @see self::record()
1044
     */
1045
    public ?ActiveRecord $record {
1046
        get => $this->record();
1047
    }
1048

1049
    /**
1050
     * Return the first result of the query and close the cursor.
1051
     *
1052
     * @param mixed ...$mode Fetch node.
1053
     *
1054
     * @return mixed The return value of this function on success depends on the fetch mode. In
1055
     * all cases, FALSE is returned on failure.
1056
     */
1057
    public function one(...$mode): mixed
1058
    {
1059
        $query = (clone $this)->take(1);
3 ✔
1060

1061
        return $query
3 ✔
1062
            ->execute()
3 ✔
1063
            ->mode(...$this->resolve_fetch_mode(...$mode))
3 ✔
1064
            ->one;
3 ✔
1065
    }
1066

1067
    /**
1068
     * @see self::one()
1069
     */
1070
    public mixed $one {
1071
        get => $this->one();
1072
    }
1073

1074
    /**
1075
     * Execute the query and return an array of key/value pairs, where _key_ is the value of
1076
     * the first column and _value_ the value of the second column.
1077
     *
1078
     * @var array<string, string>
1079
     *
1080
     * @see self::pairs()
1081
     */
1082
    public array $pairs {
1083
        // @phpstan-ignore-next-line
1084
        get => $this->all(PDO::FETCH_KEY_PAIR);
1085
    }
1086

1087
    /**
1088
     * Returns the first column of the first row.
1089
     */
1090
    public int|float|string|false|null $rc {
1091
        get => (clone $this)->take(1)->execute()->rc;
1092
    }
1093

1094
    /**
1095
     * Check the existence of records in the model.
1096
     *
1097
     * $model->exists;
1098
     * $model->where('name = "max"')->exists;
1099
     * $model->exists(1);
1100
     * $model->exists(1, 2);
1101
     * $model->exists([ 1, 2 ]);
1102
     *
1103
     * @return bool|array
1104
     */
1105
    public function exists(mixed $key = null) // @phpstan-ignore-line
1106
    {
1107
        if ($key !== null && func_num_args() > 1) {
3 ✔
1108
            $key = func_get_args();
×
1109
        }
1110

1111
        $query = clone $this;
3 ✔
1112

1113
        #
1114
        # Checking if the query matches any record.
1115
        #
1116

1117
        if ($key === null) {
3 ✔
1118
            return !!$query
1 ✔
1119
                ->select('1')
1 ✔
1120
                ->take(1)
1 ✔
1121
                ->rc;
1 ✔
1122
        }
1123

1124
        #
1125
        # Checking if the query matches the specified record keys.
1126
        #
1127

1128
        $primary = $this->model->primary;
2 ✔
1129
        assert(is_string($primary));
×
1130

1131
        $rc = $query
2 ✔
1132
            ->select($this->quote_identifier($primary)) // @phpstan-ignore argument.type
2 ✔
1133
            ->and([ $primary => $key ])
2 ✔
1134
            ->skip(null)
2 ✔
1135
            ->take(null)
2 ✔
1136
            ->all(PDO::FETCH_COLUMN);
2 ✔
1137

1138
        if ($rc && is_array($key)) {
2 ✔
1139
            /** @var array<string> $key */
1140
            $exists = array_fill_keys($key, false);
×
1141

1142
            foreach ($rc as $key) {
×
1143
                // @phpstan-ignore-next-line
1144
                $exists[$key] = true;
×
1145
            }
1146

1147
            if (array_any($exists, fn($v) => !$v)) {
×
1148
                return $exists;
×
1149
            }
1150

1151
            # all true
1152

1153
            return true;
×
1154
        }
1155

1156
        return !empty($rc);
2 ✔
1157
    }
1158

1159
    public bool $exists {
1160
        // @phpstan-ignore-next-line
1161
        get => $this->exists();
1162
    }
1163

1164
    /**
1165
     * Compute a value from a column.
1166
     *
1167
     * @param 'AVG'|'MAX'|'MIN'|'SUM' $method
1168
     * @param non-empty-string $column
1169
     *
1170
     * @throws LogicException if the computation has no result, e.g. with {@see skip()}.
1171
     */
1172
    private function compute(string $method, string $column): int|float|string|null
1173
    {
1174
        // The order doesn't change the result, and PostgreSQL rejects it. With groups however, it
1175
        // decides which one comes first.
1176
        $query = "SELECT $method(" . $this->quote_identifier($column) . ") AS result "
10 ✔
1177
            . $this->render_from() . $this->render_main(ordered: $this->group !== null);
10 ✔
1178
        $result = ($this->model)($query, $this->args)->rc;
10 ✔
1179

1180
        $result !== false
10 ✔
1181
            or throw new LogicException("The computation has no result, check skip() and group().");
10 ✔
1182

1183
        return $result;
9 ✔
1184
    }
1185

1186
    /**
1187
     * Count the rows that the query returns.
1188
     */
1189
    private function count_rows(): int
1190
    {
1191
        $distinct = $this->select !== null && preg_match('/^\s*DISTINCT\b/i', $this->select);
23 ✔
1192
        // The order doesn't change the number of rows, and PostgreSQL rejects it.
1193
        $body = $this->render_from() . $this->render_main(ordered: false);
23 ✔
1194

1195
        if ($this->group || $distinct || $this->skip || $this->take) {
23 ✔
1196
            // The rows of a grouped or distinct query depend on its `SELECT`. Otherwise it's
1197
            // replaced, because MySQL rejects a subquery with two columns of the same name.
1198
            $select = $this->group || $distinct ? $this->select ?? '1' : '1';
13 ✔
1199
            $body = "FROM (SELECT $select $body) AS counted";
13 ✔
1200
        }
1201

1202
        return (int)($this->model)("SELECT COUNT(*) AS count $body", $this->args)->rc;
23 ✔
1203
    }
1204

1205
    /**
1206
     * Count the rows that the query returns: the records matching it, or its groups, within the
1207
     * limits of {@see skip()} and {@see take()}.
1208
     *
1209
     * @param non-empty-string|null $column Deprecated, use {@see count_by_column()}.
1210
     *
1211
     * @return ($column is null ? int : array<int|string, int>)
1212
     */
1213
    public function count(?string $column = null): int|array
1214
    {
1215
        if ($column !== null) {
24 ✔
1216
            // `#[\Deprecated]` cannot target parameters, hence `trigger_error()`.
1217
            trigger_error(
1 ✔
1218
                "Passing a column to Query::count() is deprecated since icanboogie/activerecord 7.0,"
1 ✔
1219
                . " use count_by_column()",
1 ✔
1220
                E_USER_DEPRECATED
1 ✔
1221
            );
1 ✔
1222

1223
            return $this->count_by_column($column);
1 ✔
1224
        }
1225

1226
        return $this->count_rows();
23 ✔
1227
    }
1228

1229
    /**
1230
     * The number of rows that the query returns.
1231
     *
1232
     * @see self::count()
1233
     */
1234
    public int $count {
1235
        get => $this->count();
1236
    }
1237

1238
    /**
1239
     * Count the records matching the query, for each value of a column.
1240
     *
1241
     * @param non-empty-string $column
1242
     *
1243
     * @return array<int|string, int> The number of records, by value of the column. The records
1244
     *     without a value are under the empty string.
1245
     */
1246
    public function count_by_column(string $column): array
1247
    {
1248
        $identifier = $this->quote_identifier($column);
5 ✔
1249
        // The grouping is only for this computation, the query must remain reusable.
1250
        $grouped = (clone $this)->group($identifier);
5 ✔
1251
        // `COUNT(*)`, because `COUNT($column)` doesn't count the records without a value.
1252
        $query = "SELECT $identifier, COUNT(*) AS count " . $this->render_from() . $grouped->render_main();
5 ✔
1253

1254
        /** @var array<int|string, int> */
1255
        return ($this->model)($query, $this->args)->pairs;
5 ✔
1256
    }
1257

1258
    /**
1259
     * Implement the 'AVG' computation.
1260
     *
1261
     * @param non-empty-string $column
1262
     *
1263
     * @return float|null `null` if no record has a value.
1264
     */
1265
    public function average(string $column): ?float
1266
    {
1267
        $average = $this->compute('AVG', $column);
3 ✔
1268

1269
        if ($average === null) {
3 ✔
1270
            return null;
1 ✔
1271
        }
1272

1273
        // MySQL and PostgreSQL return some averages as numeric strings.
NEW
1274
        assert(is_numeric($average));
×
1275

1276
        return (float)$average;
2 ✔
1277
    }
1278

1279
    /**
1280
     * Implement the 'MIN' computation.
1281
     *
1282
     * @param non-empty-string $column
1283
     *
1284
     * @return int|float|string|null The value as returned by the database, `null` if no record has
1285
     *     a value.
1286
     */
1287
    public function minimum(string $column): int|float|string|null
1288
    {
1289
        return $this->compute('MIN', $column);
3 ✔
1290
    }
1291

1292
    /**
1293
     * Implement the 'MAX' computation.
1294
     *
1295
     * @param non-empty-string $column
1296
     *
1297
     * @return int|float|string|null The value as returned by the database, `null` if no record has
1298
     *     a value.
1299
     */
1300
    public function maximum(string $column): int|float|string|null
1301
    {
1302
        return $this->compute('MAX', $column);
4 ✔
1303
    }
1304

1305
    /**
1306
     * Implement the 'SUM' computation.
1307
     *
1308
     * @param non-empty-string $column
1309
     *
1310
     * @return int|float 0 if no record has a value.
1311
     */
1312
    public function sum(string $column): int|float
1313
    {
1314
        $sum = $this->compute('SUM', $column) ?? 0;
6 ✔
1315

NEW
1316
        assert(is_numeric($sum));
×
1317

1318
        // MySQL and PostgreSQL return some sums as numeric strings, `+ 0` makes them numbers.
1319
        return $sum + 0;
5 ✔
1320
    }
1321

1322
    /**
1323
     * Delete the records matching the conditions and range of the query.
1324
     *
1325
     * @param ?string $tables When using a JOIN, `$tables` is used to specify the tables in which
1326
     * records should be deleted. Default: The alias of queried model, only if at least one join
1327
     * clause has been defined using the {@link join()} method.
1328
     *
1329
     * @todo-20140901: reflect on join to add the required tables by default, discarding tables
1330
     * joined with the LEFT mode.
1331
     */
1332
    public function delete(?string $tables = null): Statement
1333
    {
1334
        if (!$tables && $this->joins_) {
×
1335
            $tables = $this->quote_identifier($this->model->alias);
×
1336
        }
1337

1338
        if ($tables) {
×
1339
            $query = "DELETE $tables FROM " . $this->quote_identifier($this->model->name)
×
1340
                . ' AS ' . $this->quote_identifier($this->model->alias);
×
1341
        } else {
1342
            $query = "DELETE FROM " . $this->quote_identifier($this->model->name);
×
1343
        }
1344

1345
        $query .= $this->render_main();
×
1346

1347
        return $this->model->execute($query, $this->args);
×
1348
    }
1349

1350
    #
1351
    # Batches
1352
    #
1353

1354
    public const int DEFAULT_BATCH_SIZE = 1000;
1355

1356
    private int $batch_size = self::DEFAULT_BATCH_SIZE;
1357

1358
    public function batch_size(int $batch_size): static
1359
    {
1360
        $this->batch_size = $batch_size;
2 ✔
1361

1362
        return $this;
2 ✔
1363
    }
1364

1365
    /**
1366
     * Return an iterator for the query.
1367
     */
1368
    public function getIterator(): Traversable
1369
    {
1370
        $skip = $this->skip;
2 ✔
1371
        $take = $this->batch_size;
2 ✔
1372
        $query = (clone $this)->take($take);
2 ✔
1373

1374
        do {
1375
            $all = $query->all();
2 ✔
1376

1377
            foreach ($all as $one) {
2 ✔
1378
                // @phpstan-ignore-next-line
1379
                yield $one;
2 ✔
1380
            }
1381

1382
            if (count($all) < $take) {
2 ✔
1383
                return;
2 ✔
1384
            }
1385

1386
            $skip += $take;
2 ✔
1387
            $query->skip($skip);
2 ✔
1388
        } while (true);
2 ✔
1389
    }
1390
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc