Completed
Push — 2.1 ( d5f162...fcc12f )
by
unknown
49:41 queued 41:18
created

Query::groupBy()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 1
crap 3
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use Yii;
11
use yii\base\Component;
12
use yii\base\InvalidConfigException;
13
use yii\base\InvalidArgumentException;
14
15
/**
16
 * Query represents a SELECT SQL statement in a way that is independent of DBMS.
17
 *
18
 * Query provides a set of methods to facilitate the specification of different clauses
19
 * in a SELECT statement. These methods can be chained together.
20
 *
21
 * By calling [[createCommand()]], we can get a [[Command]] instance which can be further
22
 * used to perform/execute the DB query against a database.
23
 *
24
 * For example,
25
 *
26
 * ```php
27
 * $query = new Query;
28
 * // compose the query
29
 * $query->select('id, name')
30
 *     ->from('user')
31
 *     ->limit(10);
32
 * // build and execute the query
33
 * $rows = $query->all();
34
 * // alternatively, you can create DB command and execute it
35
 * $command = $query->createCommand();
36
 * // $command->sql returns the actual SQL
37
 * $rows = $command->queryAll();
38
 * ```
39
 *
40
 * Query internally uses the [[QueryBuilder]] class to generate the SQL statement.
41
 *
42
 * A more detailed usage guide on how to work with Query can be found in the [guide article on Query Builder](guide:db-query-builder).
43
 *
44
 * @property string[] $tablesUsedInFrom Table names indexed by aliases. This property is read-only.
45
 *
46
 * @author Qiang Xue <[email protected]>
47
 * @author Carsten Brandt <[email protected]>
48
 * @since 2.0
49
 */
50
class Query extends Component implements QueryInterface
51
{
52
    use QueryTrait;
53
54
    /**
55
     * @var array the columns being selected. For example, `['id', 'name']`.
56
     * This is used to construct the SELECT clause in a SQL statement. If not set, it means selecting all columns.
57
     * @see select()
58
     */
59
    public $select;
60
    /**
61
     * @var string additional option that should be appended to the 'SELECT' keyword. For example,
62
     * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
63
     */
64
    public $selectOption;
65
    /**
66
     * @var bool whether to select distinct rows of data only. If this is set true,
67
     * the SELECT clause would be changed to SELECT DISTINCT.
68
     */
69
    public $distinct;
70
    /**
71
     * @var array the table(s) to be selected from. For example, `['user', 'post']`.
72
     * This is used to construct the FROM clause in a SQL statement.
73
     * @see from()
74
     */
75
    public $from;
76
    /**
77
     * @var array how to group the query results. For example, `['company', 'department']`.
78
     * This is used to construct the GROUP BY clause in a SQL statement.
79
     */
80
    public $groupBy;
81
    /**
82
     * @var array how to join with other tables. Each array element represents the specification
83
     * of one join which has the following structure:
84
     *
85
     * ```php
86
     * [$joinType, $tableName, $joinCondition]
87
     * ```
88
     *
89
     * For example,
90
     *
91
     * ```php
92
     * [
93
     *     ['INNER JOIN', 'user', 'user.id = author_id'],
94
     *     ['LEFT JOIN', 'team', 'team.id = team_id'],
95
     * ]
96
     * ```
97
     */
98
    public $join;
99
    /**
100
     * @var string|array|Expression the condition to be applied in the GROUP BY clause.
101
     * It can be either a string or an array. Please refer to [[where()]] on how to specify the condition.
102
     */
103
    public $having;
104
    /**
105
     * @var array this is used to construct the UNION clause(s) in a SQL statement.
106
     * Each array element is an array of the following structure:
107
     *
108
     * - `query`: either a string or a [[Query]] object representing a query
109
     * - `all`: boolean, whether it should be `UNION ALL` or `UNION`
110
     */
111
    public $union;
112
    /**
113
     * @var array list of query parameter values indexed by parameter placeholders.
114
     * For example, `[':name' => 'Dan', ':age' => 31]`.
115
     */
116
    public $params = [];
117
118
119
    /**
120
     * Creates a DB command that can be used to execute this query.
121
     * @param Connection $db the database connection used to generate the SQL statement.
122
     * If this parameter is not given, the `db` application component will be used.
123
     * @return Command the created DB command instance.
124
     */
125 333
    public function createCommand($db = null)
126
    {
127 333
        if ($db === null) {
128 31
            $db = Yii::$app->getDb();
129
        }
130 333
        [$sql, $params] = $db->getQueryBuilder()->build($this);
0 ignored issues
show
Bug introduced by
The variable $sql does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $params does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
131
132 333
        return $db->createCommand($sql, $params);
133
    }
134
135
    /**
136
     * Prepares for building SQL.
137
     * This method is called by [[QueryBuilder]] when it starts to build SQL from a query object.
138
     * You may override this method to do some final preparation work when converting a query into a SQL statement.
139
     * @param QueryBuilder $builder
140
     * @return $this a prepared query instance which will be used by [[QueryBuilder]] to build the SQL
141
     */
142 655
    public function prepare($builder)
0 ignored issues
show
Unused Code introduced by
The parameter $builder is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
143
    {
144 655
        return $this;
145
    }
146
147
    /**
148
     * Starts a batch query.
149
     *
150
     * A batch query supports fetching data in batches, which can keep the memory usage under a limit.
151
     * This method will return a [[BatchQueryResult]] object which implements the [[\Iterator]] interface
152
     * and can be traversed to retrieve the data in batches.
153
     *
154
     * For example,
155
     *
156
     * ```php
157
     * $query = (new Query)->from('user');
158
     * foreach ($query->batch() as $rows) {
159
     *     // $rows is an array of 100 or fewer rows from user table
160
     * }
161
     * ```
162
     *
163
     * @param int $batchSize the number of records to be fetched in each batch.
164
     * @param Connection $db the database connection. If not set, the "db" application component will be used.
165
     * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface
166
     * and can be traversed to retrieve the data in batches.
167
     */
168 6
    public function batch($batchSize = 100, $db = null)
169
    {
170 6
        return Yii::createObject([
171 6
            'class' => BatchQueryResult::class,
172 6
            'query' => $this,
173 6
            'batchSize' => $batchSize,
174 6
            'db' => $db,
175
            'each' => false,
176
        ]);
177
    }
178
179
    /**
180
     * Starts a batch query and retrieves data row by row.
181
     *
182
     * This method is similar to [[batch()]] except that in each iteration of the result,
183
     * only one row of data is returned. For example,
184
     *
185
     * ```php
186
     * $query = (new Query)->from('user');
187
     * foreach ($query->each() as $row) {
188
     * }
189
     * ```
190
     *
191
     * @param int $batchSize the number of records to be fetched in each batch.
192
     * @param Connection $db the database connection. If not set, the "db" application component will be used.
193
     * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface
194
     * and can be traversed to retrieve the data in batches.
195
     */
196 3
    public function each($batchSize = 100, $db = null)
197
    {
198 3
        return Yii::createObject([
199 3
            'class' => BatchQueryResult::class,
200 3
            'query' => $this,
201 3
            'batchSize' => $batchSize,
202 3
            'db' => $db,
203
            'each' => true,
204
        ]);
205
    }
206
207
    /**
208
     * Executes the query and returns all results as an array.
209
     * @param Connection $db the database connection used to generate the SQL statement.
210
     * If this parameter is not given, the `db` application component will be used.
211
     * @return array the query results. If the query results in nothing, an empty array will be returned.
212
     */
213 406
    public function all($db = null)
214
    {
215 406
        if ($this->emulateExecution) {
216 9
            return [];
217
        }
218 400
        $rows = $this->createCommand($db)->queryAll();
219 400
        return $this->populate($rows);
220
    }
221
222
    /**
223
     * Converts the raw query results into the format as specified by this query.
224
     * This method is internally used to convert the data fetched from database
225
     * into the format as required by this query.
226
     * @param array $rows the raw query result from database
227
     * @return array the converted query result
228
     */
229 223
    public function populate($rows)
230
    {
231 223
        if ($this->indexBy === null) {
232 223
            return $rows;
233
        }
234 3
        $result = [];
235 3
        foreach ($rows as $row) {
236 3
            if (is_string($this->indexBy)) {
237 3
                $key = $row[$this->indexBy];
238
            } else {
239
                $key = call_user_func($this->indexBy, $row);
240
            }
241 3
            $result[$key] = $row;
242
        }
243
244 3
        return $result;
245
    }
246
247
    /**
248
     * Executes the query and returns a single row of result.
249
     * @param Connection $db the database connection used to generate the SQL statement.
250
     * If this parameter is not given, the `db` application component will be used.
251
     * @return array|bool the first row (in terms of an array) of the query result. False is returned if the query
252
     * results in nothing.
253
     */
254 392
    public function one($db = null)
255
    {
256 392
        if ($this->emulateExecution) {
257 6
            return false;
258
        }
259
260 386
        return $this->createCommand($db)->queryOne();
261
    }
262
263
    /**
264
     * Returns the query result as a scalar value.
265
     * The value returned will be the first column in the first row of the query results.
266
     * @param Connection $db the database connection used to generate the SQL statement.
267
     * If this parameter is not given, the `db` application component will be used.
268
     * @return string|null|false the value of the first column in the first row of the query result.
269
     * False is returned if the query result is empty.
270
     */
271 24
    public function scalar($db = null)
272
    {
273 24
        if ($this->emulateExecution) {
274 6
            return null;
275
        }
276
277 18
        return $this->createCommand($db)->queryScalar();
278
    }
279
280
    /**
281
     * Executes the query and returns the first column of the result.
282
     * @param Connection $db the database connection used to generate the SQL statement.
283
     * If this parameter is not given, the `db` application component will be used.
284
     * @return array the first column of the query result. An empty array is returned if the query results in nothing.
285
     */
286 67
    public function column($db = null)
287
    {
288 67
        if ($this->emulateExecution) {
289 6
            return [];
290
        }
291
292 61
        if ($this->indexBy === null) {
293 55
            return $this->createCommand($db)->queryColumn();
294
        }
295
296 9
        if (is_string($this->indexBy) && is_array($this->select) && count($this->select) === 1) {
297 9
            if (strpos($this->indexBy, '.') === false && count($tables = $this->getTablesUsedInFrom()) > 0) {
298 9
                $this->select[] = key($tables) . '.' . $this->indexBy;
299
            } else {
300
                $this->select[] = $this->indexBy;
301
            }
302
        }
303 9
        $rows = $this->createCommand($db)->queryAll();
304 9
        $results = [];
305 9
        foreach ($rows as $row) {
306 9
            $value = reset($row);
307
308 9
            if ($this->indexBy instanceof \Closure) {
309 3
                $results[call_user_func($this->indexBy, $row)] = $value;
310
            } else {
311 9
                $results[$row[$this->indexBy]] = $value;
312
            }
313
        }
314
315 9
        return $results;
316
    }
317
318
    /**
319
     * Returns the number of records.
320
     * @param string $q the COUNT expression. Defaults to '*'.
321
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
322
     * @param Connection $db the database connection used to generate the SQL statement.
323
     * If this parameter is not given (or null), the `db` application component will be used.
324
     * @return int|string number of records. The result may be a string depending on the
325
     * underlying database engine and to support integer values higher than a 32bit PHP integer can handle.
326
     */
327 90
    public function count($q = '*', $db = null)
328
    {
329 90
        if ($this->emulateExecution) {
330 6
            return 0;
331
        }
332
333 90
        return $this->queryScalar("COUNT($q)", $db);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression $this->queryScalar("COUNT({$q})", $db); of type null|string|false adds false to the return on line 333 which is incompatible with the return type declared by the interface yii\db\QueryInterface::count of type integer. It seems like you forgot to handle an error condition.
Loading history...
334
    }
335
336
    /**
337
     * Returns the sum of the specified column values.
338
     * @param string $q the column name or expression.
339
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
340
     * @param Connection $db the database connection used to generate the SQL statement.
341
     * If this parameter is not given, the `db` application component will be used.
342
     * @return mixed the sum of the specified column values.
343
     */
344 9
    public function sum($q, $db = null)
345
    {
346 9
        if ($this->emulateExecution) {
347 6
            return 0;
348
        }
349
350 3
        return $this->queryScalar("SUM($q)", $db);
351
    }
352
353
    /**
354
     * Returns the average of the specified column values.
355
     * @param string $q the column name or expression.
356
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
357
     * @param Connection $db the database connection used to generate the SQL statement.
358
     * If this parameter is not given, the `db` application component will be used.
359
     * @return mixed the average of the specified column values.
360
     */
361 9
    public function average($q, $db = null)
362
    {
363 9
        if ($this->emulateExecution) {
364 6
            return 0;
365
        }
366
367 3
        return $this->queryScalar("AVG($q)", $db);
368
    }
369
370
    /**
371
     * Returns the minimum of the specified column values.
372
     * @param string $q the column name or expression.
373
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
374
     * @param Connection $db the database connection used to generate the SQL statement.
375
     * If this parameter is not given, the `db` application component will be used.
376
     * @return mixed the minimum of the specified column values.
377
     */
378 9
    public function min($q, $db = null)
379
    {
380 9
        return $this->queryScalar("MIN($q)", $db);
381
    }
382
383
    /**
384
     * Returns the maximum of the specified column values.
385
     * @param string $q the column name or expression.
386
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
387
     * @param Connection $db the database connection used to generate the SQL statement.
388
     * If this parameter is not given, the `db` application component will be used.
389
     * @return mixed the maximum of the specified column values.
390
     */
391 9
    public function max($q, $db = null)
392
    {
393 9
        return $this->queryScalar("MAX($q)", $db);
394
    }
395
396
    /**
397
     * Returns a value indicating whether the query result contains any row of data.
398
     * @param Connection $db the database connection used to generate the SQL statement.
399
     * If this parameter is not given, the `db` application component will be used.
400
     * @return bool whether the query result contains any row of data.
401
     */
402 67
    public function exists($db = null)
403
    {
404 67
        if ($this->emulateExecution) {
405 6
            return false;
406
        }
407 61
        $command = $this->createCommand($db);
408 61
        $params = $command->params;
409 61
        $command->setSql($command->db->getQueryBuilder()->selectExists($command->getSql()));
410 61
        $command->bindValues($params);
411 61
        return (bool) $command->queryScalar();
412
    }
413
414
    /**
415
     * Queries a scalar value by setting [[select]] first.
416
     * Restores the value of select to make this query reusable.
417
     * @param string|Expression $selectExpression
418
     * @param Connection|null $db
419
     * @return bool|string
420
     */
421 90
    protected function queryScalar($selectExpression, $db)
422
    {
423 90
        if ($this->emulateExecution) {
424 6
            return null;
425
        }
426
427
        if (
428 90
            !$this->distinct
429 90
            && empty($this->groupBy)
430 90
            && empty($this->having)
431 90
            && empty($this->union)
432
        ) {
433 89
            $select = $this->select;
434 89
            $order = $this->orderBy;
435 89
            $limit = $this->limit;
436 89
            $offset = $this->offset;
437
438 89
            $this->select = [$selectExpression];
439 89
            $this->orderBy = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $orderBy.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
440 89
            $this->limit = null;
441 89
            $this->offset = null;
442 89
            $command = $this->createCommand($db);
443
444 89
            $this->select = $select;
445 89
            $this->orderBy = $order;
446 89
            $this->limit = $limit;
447 89
            $this->offset = $offset;
448
449 89
            return $command->queryScalar();
450
        }
451
452 7
        return (new self())
453 7
            ->select([$selectExpression])
454 7
            ->from(['c' => $this])
455 7
            ->createCommand($db)
456 7
            ->queryScalar();
457
    }
458
459
    /**
460
     * Returns table names used in [[from]] indexed by aliases.
461
     * Both aliases and names are enclosed into {{ and }}.
462
     * @return string[] table names indexed by aliases
463
     * @throws \yii\base\InvalidConfigException
464
     * @since 2.0.12
465
     */
466 66
    public function getTablesUsedInFrom()
467
    {
468 66
        if (empty($this->from)) {
469
            return [];
470
        }
471
472 66
        if (is_array($this->from)) {
473 30
            $tableNames = $this->from;
474 36
        } elseif (is_string($this->from)) {
475 24
            $tableNames = preg_split('/\s*,\s*/', trim($this->from), -1, PREG_SPLIT_NO_EMPTY);
476 12
        } elseif ($this->from instanceof Expression) {
477 6
            $tableNames = [$this->from];
478
        } else {
479 6
            throw new InvalidConfigException(gettype($this->from) . ' in $from is not supported.');
480
        }
481
482 60
        return $this->cleanUpTableNames($tableNames);
483
    }
484
485
    /**
486
     * Clean up table names and aliases
487
     * Both aliases and names are enclosed into {{ and }}.
488
     * @param array $tableNames non-empty array
489
     * @return string[] table names indexed by aliases
490
     * @since 2.0.14
491
     */
492 131
    protected function cleanUpTableNames($tableNames)
493
    {
494 131
        $cleanedUpTableNames = [];
495 131
        foreach ($tableNames as $alias => $tableName) {
496 131
            if (is_string($tableName) && !is_string($alias)) {
497
                $pattern = <<<PATTERN
498 113
~
499
^
500
\s*
501
(
502
(?:['"`\[]|{{)
503
.*?
504
(?:['"`\]]|}})
505
|
506
\(.*?\)
507
|
508
.*?
509
)
510
(?:
511
(?:
512
    \s+
513
    (?:as)?
514
    \s*
515
)
516
(
517
   (?:['"`\[]|{{)
518
    .*?
519
    (?:['"`\]]|}})
520
    |
521
    .*?
522
)
523
)?
524
\s*
525
$
526
~iux
527
PATTERN;
528 113
                if (preg_match($pattern, $tableName, $matches)) {
529 113
                    if (isset($matches[2])) {
530 18
                        [, $tableName, $alias] = $matches;
531
                    } else {
532 107
                        $tableName = $alias = $matches[1];
533
                    }
534
                }
535
            }
536
537
538 131
            if ($tableName instanceof Expression) {
539 12
                if (!is_string($alias)) {
540 6
                    throw new InvalidArgumentException('To use Expression in from() method, pass it in array format with alias.');
541
                }
542 6
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
543 119
            } elseif ($tableName instanceof self) {
544 6
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
545
            } else {
546 125
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $this->ensureNameQuoted($tableName);
547
            }
548
        }
549
550 125
        return $cleanedUpTableNames;
551
    }
552
553
    /**
554
     * Ensures name is wrapped with {{ and }}
555
     * @param string $name
556
     * @return string
557
     */
558 125
    private function ensureNameQuoted($name)
559
    {
560 125
        $name = str_replace(["'", '"', '`', '[', ']'], '', $name);
561 125
        if ($name && !preg_match('/^{{.*}}$/', $name)) {
562 113
            return '{{' . $name . '}}';
563
        }
564
565 30
        return $name;
566
    }
567
568
    /**
569
     * Sets the SELECT part of the query.
570
     * @param string|array|Expression $columns the columns to be selected.
571
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
572
     * Columns can be prefixed with table names (e.g. "user.id") and/or contain column aliases (e.g. "user.id AS user_id").
573
     * The method will automatically quote the column names unless a column contains some parenthesis
574
     * (which means the column contains a DB expression). A DB expression may also be passed in form of
575
     * an [[Expression]] object.
576
     *
577
     * Note that if you are selecting an expression like `CONCAT(first_name, ' ', last_name)`, you should
578
     * use an array to specify the columns. Otherwise, the expression may be incorrectly split into several parts.
579
     *
580
     * When the columns are specified as an array, you may also use array keys as the column aliases (if a column
581
     * does not need alias, do not use a string key).
582
     *
583
     * Starting from version 2.0.1, you may also select sub-queries as columns by specifying each such column
584
     * as a `Query` instance representing the sub-query.
585
     *
586
     * @param string $option additional option that should be appended to the 'SELECT' keyword. For example,
587
     * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
588
     * @return $this the query object itself
589
     */
590 363
    public function select($columns, $option = null)
591
    {
592 363
        if ($columns instanceof Expression) {
593 3
            $columns = [$columns];
594 360
        } elseif (!is_array($columns)) {
595 101
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
596
        }
597 363
        $this->select = $columns;
598 363
        $this->selectOption = $option;
599 363
        return $this;
600
    }
601
602
    /**
603
     * Add more columns to the SELECT part of the query.
604
     *
605
     * Note, that if [[select]] has not been specified before, you should include `*` explicitly
606
     * if you want to select all remaining columns too:
607
     *
608
     * ```php
609
     * $query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one();
610
     * ```
611
     *
612
     * @param string|array|Expression $columns the columns to add to the select. See [[select()]] for more
613
     * details about the format of this parameter.
614
     * @return $this the query object itself
615
     * @see select()
616
     */
617 9
    public function addSelect($columns)
618
    {
619 9
        if ($columns instanceof Expression) {
620 3
            $columns = [$columns];
621 9
        } elseif (!is_array($columns)) {
622 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
623
        }
624 9
        if ($this->select === null) {
625 3
            $this->select = $columns;
626
        } else {
627 9
            $this->select = array_merge($this->select, $columns);
628
        }
629
630 9
        return $this;
631
    }
632
633
    /**
634
     * Sets the value indicating whether to SELECT DISTINCT or not.
635
     * @param bool $value whether to SELECT DISTINCT or not.
636
     * @return $this the query object itself
637
     */
638 6
    public function distinct($value = true)
639
    {
640 6
        $this->distinct = $value;
641 6
        return $this;
642
    }
643
644
    /**
645
     * Sets the FROM part of the query.
646
     * @param string|array|Expression $tables the table(s) to be selected from. This can be either a string (e.g. `'user'`)
647
     * or an array (e.g. `['user', 'profile']`) specifying one or several table names.
648
     * Table names can contain schema prefixes (e.g. `'public.user'`) and/or table aliases (e.g. `'user u'`).
649
     * The method will automatically quote the table names unless it contains some parenthesis
650
     * (which means the table is given as a sub-query or DB expression).
651
     *
652
     * When the tables are specified as an array, you may also use the array keys as the table aliases
653
     * (if a table does not need alias, do not use a string key).
654
     *
655
     * Use a Query object to represent a sub-query. In this case, the corresponding array key will be used
656
     * as the alias for the sub-query.
657
     *
658
     * To specify the `FROM` part in plain SQL, you may pass an instance of [[Expression]].
659
     *
660
     * Here are some examples:
661
     *
662
     * ```php
663
     * // SELECT * FROM  `user` `u`, `profile`;
664
     * $query = (new \yii\db\Query)->from(['u' => 'user', 'profile']);
665
     *
666
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
667
     * $subquery = (new \yii\db\Query)->from('user')->where(['active' => true])
668
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
669
     *
670
     * // subquery can also be a string with plain SQL wrapped in parenthesis
671
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
672
     * $subquery = "(SELECT * FROM `user` WHERE `active` = 1)";
673
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
674
     * ```
675
     *
676
     * @return $this the query object itself
677
     */
678 402
    public function from($tables)
679
    {
680 402
        if (is_string($tables)) {
681 369
            $tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
682
        }
683 402
        $this->from = $tables;
0 ignored issues
show
Documentation Bug introduced by
It seems like $tables can also be of type object<yii\db\Expression>. However, the property $from is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
684 402
        return $this;
685
    }
686
687
    /**
688
     * Sets the WHERE part of the query.
689
     *
690
     * The method requires a `$condition` parameter, and optionally a `$params` parameter
691
     * specifying the values to be bound to the query.
692
     *
693
     * The `$condition` parameter should be either a string (e.g. `'id=1'`) or an array.
694
     *
695
     * @inheritdoc
696
     *
697
     * @param string|array|Expression $condition the conditions that should be put in the WHERE part.
698
     * @param array $params the parameters (name => value) to be bound to the query.
699
     * @return $this the query object itself
700
     * @see andWhere()
701
     * @see orWhere()
702
     * @see QueryInterface::where()
703
     */
704 638
    public function where($condition, $params = [])
705
    {
706 638
        $this->where = $condition;
0 ignored issues
show
Documentation Bug introduced by
It seems like $condition can also be of type object<yii\db\Expression>. However, the property $where is declared as type string|array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
707 638
        $this->addParams($params);
708 638
        return $this;
709
    }
710
711
    /**
712
     * Adds an additional WHERE condition to the existing one.
713
     * The new condition and the existing one will be joined using the `AND` operator.
714
     * @param string|array|Expression $condition the new WHERE condition. Please refer to [[where()]]
715
     * on how to specify this parameter.
716
     * @param array $params the parameters (name => value) to be bound to the query.
717
     * @return $this the query object itself
718
     * @see where()
719
     * @see orWhere()
720
     */
721 321
    public function andWhere($condition, $params = [])
722
    {
723 321
        if ($this->where === null) {
724 267
            $this->where = $condition;
0 ignored issues
show
Documentation Bug introduced by
It seems like $condition can also be of type object<yii\db\Expression>. However, the property $where is declared as type string|array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
725 102
        } elseif (is_array($this->where) && isset($this->where[0]) && strcasecmp($this->where[0], 'and') === 0) {
726 38
            $this->where[] = $condition;
727
        } else {
728 102
            $this->where = ['and', $this->where, $condition];
729
        }
730 321
        $this->addParams($params);
731 321
        return $this;
732
    }
733
734
    /**
735
     * Adds an additional WHERE condition to the existing one.
736
     * The new condition and the existing one will be joined using the `OR` operator.
737
     * @param string|array|Expression $condition the new WHERE condition. Please refer to [[where()]]
738
     * on how to specify this parameter.
739
     * @param array $params the parameters (name => value) to be bound to the query.
740
     * @return $this the query object itself
741
     * @see where()
742
     * @see andWhere()
743
     */
744 7
    public function orWhere($condition, $params = [])
745
    {
746 7
        if ($this->where === null) {
747
            $this->where = $condition;
0 ignored issues
show
Documentation Bug introduced by
It seems like $condition can also be of type object<yii\db\Expression>. However, the property $where is declared as type string|array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
748
        } else {
749 7
            $this->where = ['or', $this->where, $condition];
750
        }
751 7
        $this->addParams($params);
752 7
        return $this;
753
    }
754
755
    /**
756
     * Adds a filtering condition for a specific column and allow the user to choose a filter operator.
757
     *
758
     * It adds an additional WHERE condition for the given field and determines the comparison operator
759
     * based on the first few characters of the given value.
760
     * The condition is added in the same way as in [[andFilterWhere]] so [[isEmpty()|empty values]] are ignored.
761
     * The new condition and the existing one will be joined using the `AND` operator.
762
     *
763
     * The comparison operator is intelligently determined based on the first few characters in the given value.
764
     * In particular, it recognizes the following operators if they appear as the leading characters in the given value:
765
     *
766
     * - `<`: the column must be less than the given value.
767
     * - `>`: the column must be greater than the given value.
768
     * - `<=`: the column must be less than or equal to the given value.
769
     * - `>=`: the column must be greater than or equal to the given value.
770
     * - `<>`: the column must not be the same as the given value.
771
     * - `=`: the column must be equal to the given value.
772
     * - If none of the above operators is detected, the `$defaultOperator` will be used.
773
     *
774
     * @param string $name the column name.
775
     * @param string $value the column value optionally prepended with the comparison operator.
776
     * @param string $defaultOperator The operator to use, when no operator is given in `$value`.
777
     * Defaults to `=`, performing an exact match.
778
     * @return $this The query object itself
779
     * @since 2.0.8
780
     */
781 3
    public function andFilterCompare($name, $value, $defaultOperator = '=')
782
    {
783 3
        if (preg_match('/^(<>|>=|>|<=|<|=)/', $value, $matches)) {
784 3
            $operator = $matches[1];
785 3
            $value = substr($value, strlen($operator));
786
        } else {
787 3
            $operator = $defaultOperator;
788
        }
789
790 3
        return $this->andFilterWhere([$operator, $name, $value]);
791
    }
792
793
    /**
794
     * Appends a JOIN part to the query.
795
     * The first parameter specifies what type of join it is.
796
     * @param string $type the type of join, such as INNER JOIN, LEFT JOIN.
797
     * @param string|array $table the table to be joined.
798
     *
799
     * Use a string to represent the name of the table to be joined.
800
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
801
     * The method will automatically quote the table name unless it contains some parenthesis
802
     * (which means the table is given as a sub-query or DB expression).
803
     *
804
     * Use an array to represent joining with a sub-query. The array must contain only one element.
805
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
806
     * represents the alias for the sub-query.
807
     *
808
     * @param string|array $on the join condition that should appear in the ON part.
809
     * Please refer to [[where()]] on how to specify this parameter.
810
     *
811
     * Note that the array format of [[where()]] is designed to match columns to values instead of columns to columns, so
812
     * the following would **not** work as expected: `['post.author_id' => 'user.id']`, it would
813
     * match the `post.author_id` column value against the string `'user.id'`.
814
     * It is recommended to use the string syntax here which is more suited for a join:
815
     *
816
     * ```php
817
     * 'post.author_id = user.id'
818
     * ```
819
     *
820
     * @param array $params the parameters (name => value) to be bound to the query.
821
     * @return $this the query object itself
822
     */
823 48
    public function join($type, $table, $on = '', $params = [])
824
    {
825 48
        $this->join[] = [$type, $table, $on];
826 48
        return $this->addParams($params);
827
    }
828
829
    /**
830
     * Appends an INNER JOIN part to the query.
831
     * @param string|array $table the table to be joined.
832
     *
833
     * Use a string to represent the name of the table to be joined.
834
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
835
     * The method will automatically quote the table name unless it contains some parenthesis
836
     * (which means the table is given as a sub-query or DB expression).
837
     *
838
     * Use an array to represent joining with a sub-query. The array must contain only one element.
839
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
840
     * represents the alias for the sub-query.
841
     *
842
     * @param string|array $on the join condition that should appear in the ON part.
843
     * Please refer to [[join()]] on how to specify this parameter.
844
     * @param array $params the parameters (name => value) to be bound to the query.
845
     * @return $this the query object itself
846
     */
847 3
    public function innerJoin($table, $on = '', $params = [])
848
    {
849 3
        $this->join[] = ['INNER JOIN', $table, $on];
850 3
        return $this->addParams($params);
851
    }
852
853
    /**
854
     * Appends a LEFT OUTER JOIN part to the query.
855
     * @param string|array $table the table to be joined.
856
     *
857
     * Use a string to represent the name of the table to be joined.
858
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
859
     * The method will automatically quote the table name unless it contains some parenthesis
860
     * (which means the table is given as a sub-query or DB expression).
861
     *
862
     * Use an array to represent joining with a sub-query. The array must contain only one element.
863
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
864
     * represents the alias for the sub-query.
865
     *
866
     * @param string|array $on the join condition that should appear in the ON part.
867
     * Please refer to [[join()]] on how to specify this parameter.
868
     * @param array $params the parameters (name => value) to be bound to the query
869
     * @return $this the query object itself
870
     */
871 3
    public function leftJoin($table, $on = '', $params = [])
872
    {
873 3
        $this->join[] = ['LEFT JOIN', $table, $on];
874 3
        return $this->addParams($params);
875
    }
876
877
    /**
878
     * Appends a RIGHT OUTER JOIN part to the query.
879
     * @param string|array $table the table to be joined.
880
     *
881
     * Use a string to represent the name of the table to be joined.
882
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
883
     * The method will automatically quote the table name unless it contains some parenthesis
884
     * (which means the table is given as a sub-query or DB expression).
885
     *
886
     * Use an array to represent joining with a sub-query. The array must contain only one element.
887
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
888
     * represents the alias for the sub-query.
889
     *
890
     * @param string|array $on the join condition that should appear in the ON part.
891
     * Please refer to [[join()]] on how to specify this parameter.
892
     * @param array $params the parameters (name => value) to be bound to the query
893
     * @return $this the query object itself
894
     */
895
    public function rightJoin($table, $on = '', $params = [])
896
    {
897
        $this->join[] = ['RIGHT JOIN', $table, $on];
898
        return $this->addParams($params);
899
    }
900
901
    /**
902
     * Sets the GROUP BY part of the query.
903
     * @param string|array|Expression $columns the columns to be grouped by.
904
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
905
     * The method will automatically quote the column names unless a column contains some parenthesis
906
     * (which means the column contains a DB expression).
907
     *
908
     * Note that if your group-by is an expression containing commas, you should always use an array
909
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
910
     * the group-by columns.
911
     *
912
     * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
913
     * @return $this the query object itself
914
     * @see addGroupBy()
915
     */
916 24
    public function groupBy($columns)
917
    {
918 24
        if ($columns instanceof Expression) {
919 3
            $columns = [$columns];
920 24
        } elseif (!is_array($columns)) {
921 24
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
922
        }
923 24
        $this->groupBy = $columns;
924 24
        return $this;
925
    }
926
927
    /**
928
     * Adds additional group-by columns to the existing ones.
929
     * @param string|array $columns additional columns to be grouped by.
930
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
931
     * The method will automatically quote the column names unless a column contains some parenthesis
932
     * (which means the column contains a DB expression).
933
     *
934
     * Note that if your group-by is an expression containing commas, you should always use an array
935
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
936
     * the group-by columns.
937
     *
938
     * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
939
     * @return $this the query object itself
940
     * @see groupBy()
941
     */
942 3
    public function addGroupBy($columns)
943
    {
944 3
        if ($columns instanceof Expression) {
945
            $columns = [$columns];
946 3
        } elseif (!is_array($columns)) {
947 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
948
        }
949 3
        if ($this->groupBy === null) {
950
            $this->groupBy = $columns;
951
        } else {
952 3
            $this->groupBy = array_merge($this->groupBy, $columns);
953
        }
954
955 3
        return $this;
956
    }
957
958
    /**
959
     * Sets the HAVING part of the query.
960
     * @param string|array|Expression $condition the conditions to be put after HAVING.
961
     * Please refer to [[where()]] on how to specify this parameter.
962
     * @param array $params the parameters (name => value) to be bound to the query.
963
     * @return $this the query object itself
964
     * @see andHaving()
965
     * @see orHaving()
966
     */
967 10
    public function having($condition, $params = [])
968
    {
969 10
        $this->having = $condition;
970 10
        $this->addParams($params);
971 10
        return $this;
972
    }
973
974
    /**
975
     * Adds an additional HAVING condition to the existing one.
976
     * The new condition and the existing one will be joined using the `AND` operator.
977
     * @param string|array|Expression $condition the new HAVING condition. Please refer to [[where()]]
978
     * on how to specify this parameter.
979
     * @param array $params the parameters (name => value) to be bound to the query.
980
     * @return $this the query object itself
981
     * @see having()
982
     * @see orHaving()
983
     */
984 3
    public function andHaving($condition, $params = [])
985
    {
986 3
        if ($this->having === null) {
987
            $this->having = $condition;
988
        } else {
989 3
            $this->having = ['and', $this->having, $condition];
990
        }
991 3
        $this->addParams($params);
992 3
        return $this;
993
    }
994
995
    /**
996
     * Adds an additional HAVING condition to the existing one.
997
     * The new condition and the existing one will be joined using the `OR` operator.
998
     * @param string|array|Expression $condition the new HAVING condition. Please refer to [[where()]]
999
     * on how to specify this parameter.
1000
     * @param array $params the parameters (name => value) to be bound to the query.
1001
     * @return $this the query object itself
1002
     * @see having()
1003
     * @see andHaving()
1004
     */
1005 3
    public function orHaving($condition, $params = [])
1006
    {
1007 3
        if ($this->having === null) {
1008
            $this->having = $condition;
1009
        } else {
1010 3
            $this->having = ['or', $this->having, $condition];
1011
        }
1012 3
        $this->addParams($params);
1013 3
        return $this;
1014
    }
1015
1016
    /**
1017
     * Sets the HAVING part of the query but ignores [[isEmpty()|empty operands]].
1018
     *
1019
     * This method is similar to [[having()]]. The main difference is that this method will
1020
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1021
     * for building query conditions based on filter values entered by users.
1022
     *
1023
     * The following code shows the difference between this method and [[having()]]:
1024
     *
1025
     * ```php
1026
     * // HAVING `age`=:age
1027
     * $query->filterHaving(['name' => null, 'age' => 20]);
1028
     * // HAVING `age`=:age
1029
     * $query->having(['age' => 20]);
1030
     * // HAVING `name` IS NULL AND `age`=:age
1031
     * $query->having(['name' => null, 'age' => 20]);
1032
     * ```
1033
     *
1034
     * Note that unlike [[having()]], you cannot pass binding parameters to this method.
1035
     *
1036
     * @param array $condition the conditions that should be put in the HAVING part.
1037
     * See [[having()]] on how to specify this parameter.
1038
     * @return $this the query object itself
1039
     * @see having()
1040
     * @see andFilterHaving()
1041
     * @see orFilterHaving()
1042
     * @since 2.0.11
1043
     */
1044 6
    public function filterHaving(array $condition)
1045
    {
1046 6
        $condition = $this->filterCondition($condition);
1047 6
        if ($condition !== []) {
1048 6
            $this->having($condition);
1049
        }
1050
1051 6
        return $this;
1052
    }
1053
1054
    /**
1055
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
1056
     * The new condition and the existing one will be joined using the `AND` operator.
1057
     *
1058
     * This method is similar to [[andHaving()]]. The main difference is that this method will
1059
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1060
     * for building query conditions based on filter values entered by users.
1061
     *
1062
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
1063
     * on how to specify this parameter.
1064
     * @return $this the query object itself
1065
     * @see filterHaving()
1066
     * @see orFilterHaving()
1067
     * @since 2.0.11
1068
     */
1069 6
    public function andFilterHaving(array $condition)
1070
    {
1071 6
        $condition = $this->filterCondition($condition);
1072 6
        if ($condition !== []) {
1073
            $this->andHaving($condition);
1074
        }
1075
1076 6
        return $this;
1077
    }
1078
1079
    /**
1080
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
1081
     * The new condition and the existing one will be joined using the `OR` operator.
1082
     *
1083
     * This method is similar to [[orHaving()]]. The main difference is that this method will
1084
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1085
     * for building query conditions based on filter values entered by users.
1086
     *
1087
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
1088
     * on how to specify this parameter.
1089
     * @return $this the query object itself
1090
     * @see filterHaving()
1091
     * @see andFilterHaving()
1092
     * @since 2.0.11
1093
     */
1094 6
    public function orFilterHaving(array $condition)
1095
    {
1096 6
        $condition = $this->filterCondition($condition);
1097 6
        if ($condition !== []) {
1098
            $this->orHaving($condition);
1099
        }
1100
1101 6
        return $this;
1102
    }
1103
1104
    /**
1105
     * Appends a SQL statement using UNION operator.
1106
     * @param string|Query $sql the SQL statement to be appended using UNION
1107
     * @param bool $all TRUE if using UNION ALL and FALSE if using UNION
1108
     * @return $this the query object itself
1109
     */
1110 10
    public function union($sql, $all = false)
1111
    {
1112 10
        $this->union[] = ['query' => $sql, 'all' => $all];
1113 10
        return $this;
1114
    }
1115
1116
    /**
1117
     * Sets the parameters to be bound to the query.
1118
     * @param array $params list of query parameter values indexed by parameter placeholders.
1119
     * For example, `[':name' => 'Dan', ':age' => 31]`.
1120
     * @return $this the query object itself
1121
     * @see addParams()
1122
     */
1123 6
    public function params($params)
1124
    {
1125 6
        $this->params = $params;
1126 6
        return $this;
1127
    }
1128
1129
    /**
1130
     * Adds additional parameters to be bound to the query.
1131
     * @param array $params list of query parameter values indexed by parameter placeholders.
1132
     * For example, `[':name' => 'Dan', ':age' => 31]`.
1133
     * @return $this the query object itself
1134
     * @see params()
1135
     */
1136 879
    public function addParams($params)
1137
    {
1138 879
        if (!empty($params)) {
1139 71
            if (empty($this->params)) {
1140 71
                $this->params = $params;
1141
            } else {
1142 6
                foreach ($params as $name => $value) {
1143 6
                    if (is_int($name)) {
1144
                        $this->params[] = $value;
1145
                    } else {
1146 6
                        $this->params[$name] = $value;
1147
                    }
1148
                }
1149
            }
1150
        }
1151
1152 879
        return $this;
1153
    }
1154
1155
    /**
1156
     * Creates a new Query object and copies its property values from an existing one.
1157
     * The properties being copies are the ones to be used by query builders.
1158
     * @param Query $from the source query object
1159
     * @return Query the new Query object
1160
     */
1161 343
    public static function create($from)
1162
    {
1163 343
        return new self([
1164 343
            'where' => $from->where,
1165 343
            'limit' => $from->limit,
1166 343
            'offset' => $from->offset,
1167 343
            'orderBy' => $from->orderBy,
1168 343
            'indexBy' => $from->indexBy,
1169 343
            'select' => $from->select,
1170 343
            'selectOption' => $from->selectOption,
1171 343
            'distinct' => $from->distinct,
1172 343
            'from' => $from->from,
1173 343
            'groupBy' => $from->groupBy,
1174 343
            'join' => $from->join,
1175 343
            'having' => $from->having,
1176 343
            'union' => $from->union,
1177 343
            'params' => $from->params,
1178
        ]);
1179
    }
1180
}
1181