Completed
Push — master ( 7e9096...8f2cd0 )
by Dmitry
08:16
created

Query::batch()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 2
crap 1
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\InvalidParamException;
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 28
            $db = Yii::$app->getDb();
129
        }
130 333
        list($sql, $params) = $db->getQueryBuilder()->build($this);
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::className(),
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::className(),
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 409
    public function all($db = null)
214
    {
215 409
        if ($this->emulateExecution) {
216 9
            return [];
217
        }
218 403
        $rows = $this->createCommand($db)->queryAll();
219 403
        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 395
    public function one($db = null)
255
    {
256 395
        if ($this->emulateExecution) {
257 6
            return false;
258
        }
259
260 389
        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 87
    public function count($q = '*', $db = null)
328
    {
329 87
        if ($this->emulateExecution) {
330 6
            return 0;
331
        }
332
333 87
        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 87
    protected function queryScalar($selectExpression, $db)
422
    {
423 87
        if ($this->emulateExecution) {
424 6
            return null;
425
        }
426
427
        if (
428 87
            !$this->distinct
429 87
            && empty($this->groupBy)
430 87
            && empty($this->having)
431 87
            && empty($this->union)
432
        ) {
433 86
            $select = $this->select;
434 86
            $order = $this->orderBy;
435 86
            $limit = $this->limit;
436 86
            $offset = $this->offset;
437
438 86
            $this->select = [$selectExpression];
439 86
            $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 86
            $this->limit = null;
441 86
            $this->offset = null;
442 86
            $command = $this->createCommand($db);
443
444 86
            $this->select = $select;
445 86
            $this->orderBy = $order;
446 86
            $this->limit = $limit;
447 86
            $this->offset = $offset;
448
449 86
            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 137
    public function getTablesUsedInFrom()
467
    {
468 137
        if (empty($this->from)) {
469
            return [];
470
        }
471
472 137
        if (is_array($this->from)) {
473 101
            $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
        // Clean up table names and aliases
483 131
        $cleanedUpTableNames = [];
484 131
        foreach ($tableNames as $alias => $tableName) {
485 131
            if (is_string($tableName) && !is_string($alias)) {
486
                $pattern = <<<PATTERN
487 113
~
488
^
489
\s*
490
(
491
(?:['"`\[]|{{)
492
.*?
493
(?:['"`\]]|}})
494
|
495
\(.*?\)
496
|
497
.*?
498
)
499
(?:
500
(?:
501
    \s+
502
    (?:as)?
503
    \s*
504
)
505
(
506
   (?:['"`\[]|{{)
507
    .*?
508
    (?:['"`\]]|}})
509
    |
510
    .*?
511
)
512
)?
513
\s*
514
$
515
~iux
516
PATTERN;
517 113
                if (preg_match($pattern, $tableName, $matches)) {
518 113
                    if (isset($matches[2])) {
519 18
                        list(, $tableName, $alias) = $matches;
520
                    } else {
521 107
                        $tableName = $alias = $matches[1];
522
                    }
523
                }
524
            }
525
526
527 131
            if ($tableName instanceof Expression) {
528 12
                if (!is_string($alias)) {
529 6
                    throw new InvalidParamException('To use Expression in from() method, pass it in array format with alias.');
530
                }
531 6
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
532 119
            } elseif ($tableName instanceof self) {
533 6
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
534
            } else {
535 125
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $this->ensureNameQuoted($tableName);
536
            }
537
        }
538
539 125
        return $cleanedUpTableNames;
540
    }
541
542
    /**
543
     * Ensures name is wrapped with {{ and }}
544
     * @param string $name
545
     * @return string
546
     */
547 125
    private function ensureNameQuoted($name)
548
    {
549 125
        $name = str_replace(["'", '"', '`', '[', ']'], '', $name);
550 125
        if ($name && !preg_match('/^{{.*}}$/', $name)) {
551 113
            return '{{' . $name . '}}';
552
        }
553
554 30
        return $name;
555
    }
556
557
    /**
558
     * Sets the SELECT part of the query.
559
     * @param string|array|Expression $columns the columns to be selected.
560
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
561
     * Columns can be prefixed with table names (e.g. "user.id") and/or contain column aliases (e.g. "user.id AS user_id").
562
     * The method will automatically quote the column names unless a column contains some parenthesis
563
     * (which means the column contains a DB expression). A DB expression may also be passed in form of
564
     * an [[Expression]] object.
565
     *
566
     * Note that if you are selecting an expression like `CONCAT(first_name, ' ', last_name)`, you should
567
     * use an array to specify the columns. Otherwise, the expression may be incorrectly split into several parts.
568
     *
569
     * When the columns are specified as an array, you may also use array keys as the column aliases (if a column
570
     * does not need alias, do not use a string key).
571
     *
572
     * Starting from version 2.0.1, you may also select sub-queries as columns by specifying each such column
573
     * as a `Query` instance representing the sub-query.
574
     *
575
     * @param string $option additional option that should be appended to the 'SELECT' keyword. For example,
576
     * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
577
     * @return $this the query object itself
578
     */
579 366
    public function select($columns, $option = null)
580
    {
581 366
        if ($columns instanceof Expression) {
582 3
            $columns = [$columns];
583 363
        } elseif (!is_array($columns)) {
584 104
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
585
        }
586 366
        $this->select = $columns;
587 366
        $this->selectOption = $option;
588 366
        return $this;
589
    }
590
591
    /**
592
     * Add more columns to the SELECT part of the query.
593
     *
594
     * Note, that if [[select]] has not been specified before, you should include `*` explicitly
595
     * if you want to select all remaining columns too:
596
     *
597
     * ```php
598
     * $query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one();
599
     * ```
600
     *
601
     * @param string|array|Expression $columns the columns to add to the select. See [[select()]] for more
602
     * details about the format of this parameter.
603
     * @return $this the query object itself
604
     * @see select()
605
     */
606 9
    public function addSelect($columns)
607
    {
608 9
        if ($columns instanceof Expression) {
609 3
            $columns = [$columns];
610 9
        } elseif (!is_array($columns)) {
611 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
612
        }
613 9
        if ($this->select === null) {
614 3
            $this->select = $columns;
615
        } else {
616 9
            $this->select = array_merge($this->select, $columns);
617
        }
618
619 9
        return $this;
620
    }
621
622
    /**
623
     * Sets the value indicating whether to SELECT DISTINCT or not.
624
     * @param bool $value whether to SELECT DISTINCT or not.
625
     * @return $this the query object itself
626
     */
627 6
    public function distinct($value = true)
628
    {
629 6
        $this->distinct = $value;
630 6
        return $this;
631
    }
632
633
    /**
634
     * Sets the FROM part of the query.
635
     * @param string|array|Expression $tables the table(s) to be selected from. This can be either a string (e.g. `'user'`)
636
     * or an array (e.g. `['user', 'profile']`) specifying one or several table names.
637
     * Table names can contain schema prefixes (e.g. `'public.user'`) and/or table aliases (e.g. `'user u'`).
638
     * The method will automatically quote the table names unless it contains some parenthesis
639
     * (which means the table is given as a sub-query or DB expression).
640
     *
641
     * When the tables are specified as an array, you may also use the array keys as the table aliases
642
     * (if a table does not need alias, do not use a string key).
643
     *
644
     * Use a Query object to represent a sub-query. In this case, the corresponding array key will be used
645
     * as the alias for the sub-query.
646
     *
647
     * To specify the `FROM` part in plain SQL, you may pass an instance of [[Expression]].
648
     *
649
     * Here are some examples:
650
     *
651
     * ```php
652
     * // SELECT * FROM  `user` `u`, `profile`;
653
     * $query = (new \yii\db\Query)->from(['u' => 'user', 'profile']);
654
     *
655
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
656
     * $subquery = (new \yii\db\Query)->from('user')->where(['active' => true])
657
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
658
     *
659
     * // subquery can also be a string with plain SQL wrapped in parenthesis
660
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
661
     * $subquery = "(SELECT * FROM `user` WHERE `active` = 1)";
662
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
663
     * ```
664
     *
665
     * @return $this the query object itself
666
     */
667 402
    public function from($tables)
668
    {
669 402
        if (is_string($tables)) {
670 369
            $tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
671
        }
672 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...
673 402
        return $this;
674
    }
675
676
    /**
677
     * Sets the WHERE part of the query.
678
     *
679
     * The method requires a `$condition` parameter, and optionally a `$params` parameter
680
     * specifying the values to be bound to the query.
681
     *
682
     * The `$condition` parameter should be either a string (e.g. `'id=1'`) or an array.
683
     *
684
     * @inheritdoc
685
     *
686
     * @param string|array|Expression $condition the conditions that should be put in the WHERE part.
687
     * @param array $params the parameters (name => value) to be bound to the query.
688
     * @return $this the query object itself
689
     * @see andWhere()
690
     * @see orWhere()
691
     * @see QueryInterface::where()
692
     */
693 638
    public function where($condition, $params = [])
694
    {
695 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...
696 638
        $this->addParams($params);
697 638
        return $this;
698
    }
699
700
    /**
701
     * Adds an additional WHERE condition to the existing one.
702
     * The new condition and the existing one will be joined using the `AND` operator.
703
     * @param string|array|Expression $condition the new WHERE condition. Please refer to [[where()]]
704
     * on how to specify this parameter.
705
     * @param array $params the parameters (name => value) to be bound to the query.
706
     * @return $this the query object itself
707
     * @see where()
708
     * @see orWhere()
709
     */
710 322
    public function andWhere($condition, $params = [])
711
    {
712 322
        if ($this->where === null) {
713 270
            $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...
714 100
        } elseif (is_array($this->where) && isset($this->where[0]) && strcasecmp($this->where[0], 'and') === 0) {
715 38
            $this->where[] = $condition;
716
        } else {
717 100
            $this->where = ['and', $this->where, $condition];
718
        }
719 322
        $this->addParams($params);
720 322
        return $this;
721
    }
722
723
    /**
724
     * Adds an additional WHERE condition to the existing one.
725
     * The new condition and the existing one will be joined using the `OR` operator.
726
     * @param string|array|Expression $condition the new WHERE condition. Please refer to [[where()]]
727
     * on how to specify this parameter.
728
     * @param array $params the parameters (name => value) to be bound to the query.
729
     * @return $this the query object itself
730
     * @see where()
731
     * @see andWhere()
732
     */
733 7
    public function orWhere($condition, $params = [])
734
    {
735 7
        if ($this->where === null) {
736
            $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...
737
        } else {
738 7
            $this->where = ['or', $this->where, $condition];
739
        }
740 7
        $this->addParams($params);
741 7
        return $this;
742
    }
743
744
    /**
745
     * Adds a filtering condition for a specific column and allow the user to choose a filter operator.
746
     *
747
     * It adds an additional WHERE condition for the given field and determines the comparison operator
748
     * based on the first few characters of the given value.
749
     * The condition is added in the same way as in [[andFilterWhere]] so [[isEmpty()|empty values]] are ignored.
750
     * The new condition and the existing one will be joined using the `AND` operator.
751
     *
752
     * The comparison operator is intelligently determined based on the first few characters in the given value.
753
     * In particular, it recognizes the following operators if they appear as the leading characters in the given value:
754
     *
755
     * - `<`: the column must be less than the given value.
756
     * - `>`: the column must be greater than the given value.
757
     * - `<=`: the column must be less than or equal to the given value.
758
     * - `>=`: the column must be greater than or equal to the given value.
759
     * - `<>`: the column must not be the same as the given value.
760
     * - `=`: the column must be equal to the given value.
761
     * - If none of the above operators is detected, the `$defaultOperator` will be used.
762
     *
763
     * @param string $name the column name.
764
     * @param string $value the column value optionally prepended with the comparison operator.
765
     * @param string $defaultOperator The operator to use, when no operator is given in `$value`.
766
     * Defaults to `=`, performing an exact match.
767
     * @return $this The query object itself
768
     * @since 2.0.8
769
     */
770 3
    public function andFilterCompare($name, $value, $defaultOperator = '=')
771
    {
772 3
        if (preg_match('/^(<>|>=|>|<=|<|=)/', $value, $matches)) {
773 3
            $operator = $matches[1];
774 3
            $value = substr($value, strlen($operator));
775
        } else {
776 3
            $operator = $defaultOperator;
777
        }
778
779 3
        return $this->andFilterWhere([$operator, $name, $value]);
780
    }
781
782
    /**
783
     * Appends a JOIN part to the query.
784
     * The first parameter specifies what type of join it is.
785
     * @param string $type the type of join, such as INNER JOIN, LEFT JOIN.
786
     * @param string|array $table the table to be joined.
787
     *
788
     * Use a string to represent the name of the table to be joined.
789
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
790
     * The method will automatically quote the table name unless it contains some parenthesis
791
     * (which means the table is given as a sub-query or DB expression).
792
     *
793
     * Use an array to represent joining with a sub-query. The array must contain only one element.
794
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
795
     * represents the alias for the sub-query.
796
     *
797
     * @param string|array $on the join condition that should appear in the ON part.
798
     * Please refer to [[where()]] on how to specify this parameter.
799
     *
800
     * Note that the array format of [[where()]] is designed to match columns to values instead of columns to columns, so
801
     * the following would **not** work as expected: `['post.author_id' => 'user.id']`, it would
802
     * match the `post.author_id` column value against the string `'user.id'`.
803
     * It is recommended to use the string syntax here which is more suited for a join:
804
     *
805
     * ```php
806
     * 'post.author_id = user.id'
807
     * ```
808
     *
809
     * @param array $params the parameters (name => value) to be bound to the query.
810
     * @return $this the query object itself
811
     */
812 48
    public function join($type, $table, $on = '', $params = [])
813
    {
814 48
        $this->join[] = [$type, $table, $on];
815 48
        return $this->addParams($params);
816
    }
817
818
    /**
819
     * Appends an INNER JOIN part to the query.
820
     * @param string|array $table the table to be joined.
821
     *
822
     * Use a string to represent the name of the table to be joined.
823
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
824
     * The method will automatically quote the table name unless it contains some parenthesis
825
     * (which means the table is given as a sub-query or DB expression).
826
     *
827
     * Use an array to represent joining with a sub-query. The array must contain only one element.
828
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
829
     * represents the alias for the sub-query.
830
     *
831
     * @param string|array $on the join condition that should appear in the ON part.
832
     * Please refer to [[join()]] on how to specify this parameter.
833
     * @param array $params the parameters (name => value) to be bound to the query.
834
     * @return $this the query object itself
835
     */
836 3
    public function innerJoin($table, $on = '', $params = [])
837
    {
838 3
        $this->join[] = ['INNER JOIN', $table, $on];
839 3
        return $this->addParams($params);
840
    }
841
842
    /**
843
     * Appends a LEFT OUTER JOIN part to the query.
844
     * @param string|array $table the table to be joined.
845
     *
846
     * Use a string to represent the name of the table to be joined.
847
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
848
     * The method will automatically quote the table name unless it contains some parenthesis
849
     * (which means the table is given as a sub-query or DB expression).
850
     *
851
     * Use an array to represent joining with a sub-query. The array must contain only one element.
852
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
853
     * represents the alias for the sub-query.
854
     *
855
     * @param string|array $on the join condition that should appear in the ON part.
856
     * Please refer to [[join()]] on how to specify this parameter.
857
     * @param array $params the parameters (name => value) to be bound to the query
858
     * @return $this the query object itself
859
     */
860 3
    public function leftJoin($table, $on = '', $params = [])
861
    {
862 3
        $this->join[] = ['LEFT JOIN', $table, $on];
863 3
        return $this->addParams($params);
864
    }
865
866
    /**
867
     * Appends a RIGHT OUTER JOIN part to the query.
868
     * @param string|array $table the table to be joined.
869
     *
870
     * Use a string to represent the name of the table to be joined.
871
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
872
     * The method will automatically quote the table name unless it contains some parenthesis
873
     * (which means the table is given as a sub-query or DB expression).
874
     *
875
     * Use an array to represent joining with a sub-query. The array must contain only one element.
876
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
877
     * represents the alias for the sub-query.
878
     *
879
     * @param string|array $on the join condition that should appear in the ON part.
880
     * Please refer to [[join()]] on how to specify this parameter.
881
     * @param array $params the parameters (name => value) to be bound to the query
882
     * @return $this the query object itself
883
     */
884
    public function rightJoin($table, $on = '', $params = [])
885
    {
886
        $this->join[] = ['RIGHT JOIN', $table, $on];
887
        return $this->addParams($params);
888
    }
889
890
    /**
891
     * Sets the GROUP BY part of the query.
892
     * @param string|array|Expression $columns the columns to be grouped by.
893
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
894
     * The method will automatically quote the column names unless a column contains some parenthesis
895
     * (which means the column contains a DB expression).
896
     *
897
     * Note that if your group-by is an expression containing commas, you should always use an array
898
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
899
     * the group-by columns.
900
     *
901
     * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
902
     * @return $this the query object itself
903
     * @see addGroupBy()
904
     */
905 24
    public function groupBy($columns)
906
    {
907 24
        if ($columns instanceof Expression) {
908 3
            $columns = [$columns];
909 24
        } elseif (!is_array($columns)) {
910 24
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
911
        }
912 24
        $this->groupBy = $columns;
913 24
        return $this;
914
    }
915
916
    /**
917
     * Adds additional group-by columns to the existing ones.
918
     * @param string|array $columns additional columns to be grouped by.
919
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
920
     * The method will automatically quote the column names unless a column contains some parenthesis
921
     * (which means the column contains a DB expression).
922
     *
923
     * Note that if your group-by is an expression containing commas, you should always use an array
924
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
925
     * the group-by columns.
926
     *
927
     * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
928
     * @return $this the query object itself
929
     * @see groupBy()
930
     */
931 3
    public function addGroupBy($columns)
932
    {
933 3
        if ($columns instanceof Expression) {
934
            $columns = [$columns];
935 3
        } elseif (!is_array($columns)) {
936 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
937
        }
938 3
        if ($this->groupBy === null) {
939
            $this->groupBy = $columns;
940
        } else {
941 3
            $this->groupBy = array_merge($this->groupBy, $columns);
942
        }
943
944 3
        return $this;
945
    }
946
947
    /**
948
     * Sets the HAVING part of the query.
949
     * @param string|array|Expression $condition the conditions to be put after HAVING.
950
     * Please refer to [[where()]] on how to specify this parameter.
951
     * @param array $params the parameters (name => value) to be bound to the query.
952
     * @return $this the query object itself
953
     * @see andHaving()
954
     * @see orHaving()
955
     */
956 10
    public function having($condition, $params = [])
957
    {
958 10
        $this->having = $condition;
959 10
        $this->addParams($params);
960 10
        return $this;
961
    }
962
963
    /**
964
     * Adds an additional HAVING condition to the existing one.
965
     * The new condition and the existing one will be joined using the `AND` operator.
966
     * @param string|array|Expression $condition the new HAVING condition. Please refer to [[where()]]
967
     * on how to specify this parameter.
968
     * @param array $params the parameters (name => value) to be bound to the query.
969
     * @return $this the query object itself
970
     * @see having()
971
     * @see orHaving()
972
     */
973 3
    public function andHaving($condition, $params = [])
974
    {
975 3
        if ($this->having === null) {
976
            $this->having = $condition;
977
        } else {
978 3
            $this->having = ['and', $this->having, $condition];
979
        }
980 3
        $this->addParams($params);
981 3
        return $this;
982
    }
983
984
    /**
985
     * Adds an additional HAVING condition to the existing one.
986
     * The new condition and the existing one will be joined using the `OR` operator.
987
     * @param string|array|Expression $condition the new HAVING condition. Please refer to [[where()]]
988
     * on how to specify this parameter.
989
     * @param array $params the parameters (name => value) to be bound to the query.
990
     * @return $this the query object itself
991
     * @see having()
992
     * @see andHaving()
993
     */
994 3
    public function orHaving($condition, $params = [])
995
    {
996 3
        if ($this->having === null) {
997
            $this->having = $condition;
998
        } else {
999 3
            $this->having = ['or', $this->having, $condition];
1000
        }
1001 3
        $this->addParams($params);
1002 3
        return $this;
1003
    }
1004
1005
    /**
1006
     * Sets the HAVING part of the query but ignores [[isEmpty()|empty operands]].
1007
     *
1008
     * This method is similar to [[having()]]. The main difference is that this method will
1009
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1010
     * for building query conditions based on filter values entered by users.
1011
     *
1012
     * The following code shows the difference between this method and [[having()]]:
1013
     *
1014
     * ```php
1015
     * // HAVING `age`=:age
1016
     * $query->filterHaving(['name' => null, 'age' => 20]);
1017
     * // HAVING `age`=:age
1018
     * $query->having(['age' => 20]);
1019
     * // HAVING `name` IS NULL AND `age`=:age
1020
     * $query->having(['name' => null, 'age' => 20]);
1021
     * ```
1022
     *
1023
     * Note that unlike [[having()]], you cannot pass binding parameters to this method.
1024
     *
1025
     * @param array $condition the conditions that should be put in the HAVING part.
1026
     * See [[having()]] on how to specify this parameter.
1027
     * @return $this the query object itself
1028
     * @see having()
1029
     * @see andFilterHaving()
1030
     * @see orFilterHaving()
1031
     * @since 2.0.11
1032
     */
1033 6
    public function filterHaving(array $condition)
1034
    {
1035 6
        $condition = $this->filterCondition($condition);
1036 6
        if ($condition !== []) {
1037 6
            $this->having($condition);
1038
        }
1039
1040 6
        return $this;
1041
    }
1042
1043
    /**
1044
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
1045
     * The new condition and the existing one will be joined using the `AND` operator.
1046
     *
1047
     * This method is similar to [[andHaving()]]. The main difference is that this method will
1048
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1049
     * for building query conditions based on filter values entered by users.
1050
     *
1051
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
1052
     * on how to specify this parameter.
1053
     * @return $this the query object itself
1054
     * @see filterHaving()
1055
     * @see orFilterHaving()
1056
     * @since 2.0.11
1057
     */
1058 6
    public function andFilterHaving(array $condition)
1059
    {
1060 6
        $condition = $this->filterCondition($condition);
1061 6
        if ($condition !== []) {
1062
            $this->andHaving($condition);
1063
        }
1064
1065 6
        return $this;
1066
    }
1067
1068
    /**
1069
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
1070
     * The new condition and the existing one will be joined using the `OR` operator.
1071
     *
1072
     * This method is similar to [[orHaving()]]. The main difference is that this method will
1073
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1074
     * for building query conditions based on filter values entered by users.
1075
     *
1076
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
1077
     * on how to specify this parameter.
1078
     * @return $this the query object itself
1079
     * @see filterHaving()
1080
     * @see andFilterHaving()
1081
     * @since 2.0.11
1082
     */
1083 6
    public function orFilterHaving(array $condition)
1084
    {
1085 6
        $condition = $this->filterCondition($condition);
1086 6
        if ($condition !== []) {
1087
            $this->orHaving($condition);
1088
        }
1089
1090 6
        return $this;
1091
    }
1092
1093
    /**
1094
     * Appends a SQL statement using UNION operator.
1095
     * @param string|Query $sql the SQL statement to be appended using UNION
1096
     * @param bool $all TRUE if using UNION ALL and FALSE if using UNION
1097
     * @return $this the query object itself
1098
     */
1099 10
    public function union($sql, $all = false)
1100
    {
1101 10
        $this->union[] = ['query' => $sql, 'all' => $all];
1102 10
        return $this;
1103
    }
1104
1105
    /**
1106
     * Sets the parameters to be bound to the query.
1107
     * @param array $params list of query parameter values indexed by parameter placeholders.
1108
     * For example, `[':name' => 'Dan', ':age' => 31]`.
1109
     * @return $this the query object itself
1110
     * @see addParams()
1111
     */
1112 6
    public function params($params)
1113
    {
1114 6
        $this->params = $params;
1115 6
        return $this;
1116
    }
1117
1118
    /**
1119
     * Adds additional parameters to be bound to the query.
1120
     * @param array $params list of query parameter values indexed by parameter placeholders.
1121
     * For example, `[':name' => 'Dan', ':age' => 31]`.
1122
     * @return $this the query object itself
1123
     * @see params()
1124
     */
1125 882
    public function addParams($params)
1126
    {
1127 882
        if (!empty($params)) {
1128 71
            if (empty($this->params)) {
1129 71
                $this->params = $params;
1130
            } else {
1131 6
                foreach ($params as $name => $value) {
1132 6
                    if (is_int($name)) {
1133
                        $this->params[] = $value;
1134
                    } else {
1135 6
                        $this->params[$name] = $value;
1136
                    }
1137
                }
1138
            }
1139
        }
1140
1141 882
        return $this;
1142
    }
1143
1144
    /**
1145
     * Creates a new Query object and copies its property values from an existing one.
1146
     * The properties being copies are the ones to be used by query builders.
1147
     * @param Query $from the source query object
1148
     * @return Query the new Query object
1149
     */
1150 346
    public static function create($from)
1151
    {
1152 346
        return new self([
1153 346
            'where' => $from->where,
1154 346
            'limit' => $from->limit,
1155 346
            'offset' => $from->offset,
1156 346
            'orderBy' => $from->orderBy,
1157 346
            'indexBy' => $from->indexBy,
1158 346
            'select' => $from->select,
1159 346
            'selectOption' => $from->selectOption,
1160 346
            'distinct' => $from->distinct,
1161 346
            'from' => $from->from,
1162 346
            'groupBy' => $from->groupBy,
1163 346
            'join' => $from->join,
1164 346
            'having' => $from->having,
1165 346
            'union' => $from->union,
1166 346
            'params' => $from->params,
1167
        ]);
1168
    }
1169
}
1170