1 | <?php |
||||
2 | /** |
||||
3 | * @link https://www.yiiframework.com/ |
||||
4 | * @copyright Copyright (c) 2008 Yii Software LLC |
||||
5 | * @license https://www.yiiframework.com/license/ |
||||
6 | */ |
||||
7 | |||||
8 | namespace yii\db; |
||||
9 | |||||
10 | use Yii; |
||||
11 | use yii\base\Component; |
||||
12 | use yii\base\InvalidArgumentException; |
||||
13 | use yii\helpers\ArrayHelper; |
||||
14 | use yii\base\InvalidConfigException; |
||||
15 | |||||
16 | /** |
||||
17 | * Query represents a SELECT SQL statement in a way that is independent of DBMS. |
||||
18 | * |
||||
19 | * Query provides a set of methods to facilitate the specification of different clauses |
||||
20 | * in a SELECT statement. These methods can be chained together. |
||||
21 | * |
||||
22 | * By calling [[createCommand()]], we can get a [[Command]] instance which can be further |
||||
23 | * used to perform/execute the DB query against a database. |
||||
24 | * |
||||
25 | * For example, |
||||
26 | * |
||||
27 | * ```php |
||||
28 | * $query = new Query; |
||||
29 | * // compose the query |
||||
30 | * $query->select('id, name') |
||||
31 | * ->from('user') |
||||
32 | * ->limit(10); |
||||
33 | * // build and execute the query |
||||
34 | * $rows = $query->all(); |
||||
35 | * // alternatively, you can create DB command and execute it |
||||
36 | * $command = $query->createCommand(); |
||||
37 | * // $command->sql returns the actual SQL |
||||
38 | * $rows = $command->queryAll(); |
||||
39 | * ``` |
||||
40 | * |
||||
41 | * Query internally uses the [[QueryBuilder]] class to generate the SQL statement. |
||||
42 | * |
||||
43 | * 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). |
||||
44 | * |
||||
45 | * @property-read string[] $tablesUsedInFrom Table names indexed by aliases. |
||||
46 | * |
||||
47 | * @author Qiang Xue <[email protected]> |
||||
48 | * @author Carsten Brandt <[email protected]> |
||||
49 | * @since 2.0 |
||||
50 | */ |
||||
51 | class Query extends Component implements QueryInterface, ExpressionInterface |
||||
52 | { |
||||
53 | use QueryTrait; |
||||
54 | |||||
55 | /** |
||||
56 | * @var array|null the columns being selected. For example, `['id', 'name']`. |
||||
57 | * This is used to construct the SELECT clause in a SQL statement. If not set, it means selecting all columns. |
||||
58 | * @see select() |
||||
59 | */ |
||||
60 | public $select; |
||||
61 | /** |
||||
62 | * @var string|null additional option that should be appended to the 'SELECT' keyword. For example, |
||||
63 | * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used. |
||||
64 | */ |
||||
65 | public $selectOption; |
||||
66 | /** |
||||
67 | * @var bool whether to select distinct rows of data only. If this is set true, |
||||
68 | * the SELECT clause would be changed to SELECT DISTINCT. |
||||
69 | */ |
||||
70 | public $distinct = false; |
||||
71 | /** |
||||
72 | * @var array|null the table(s) to be selected from. For example, `['user', 'post']`. |
||||
73 | * This is used to construct the FROM clause in a SQL statement. |
||||
74 | * @see from() |
||||
75 | */ |
||||
76 | public $from; |
||||
77 | /** |
||||
78 | * @var array|null how to group the query results. For example, `['company', 'department']`. |
||||
79 | * This is used to construct the GROUP BY clause in a SQL statement. |
||||
80 | */ |
||||
81 | public $groupBy; |
||||
82 | /** |
||||
83 | * @var array|null how to join with other tables. Each array element represents the specification |
||||
84 | * of one join which has the following structure: |
||||
85 | * |
||||
86 | * ```php |
||||
87 | * [$joinType, $tableName, $joinCondition] |
||||
88 | * ``` |
||||
89 | * |
||||
90 | * For example, |
||||
91 | * |
||||
92 | * ```php |
||||
93 | * [ |
||||
94 | * ['INNER JOIN', 'user', 'user.id = author_id'], |
||||
95 | * ['LEFT JOIN', 'team', 'team.id = team_id'], |
||||
96 | * ] |
||||
97 | * ``` |
||||
98 | */ |
||||
99 | public $join; |
||||
100 | /** |
||||
101 | * @var string|array|ExpressionInterface|null the condition to be applied in the GROUP BY clause. |
||||
102 | * It can be either a string or an array. Please refer to [[where()]] on how to specify the condition. |
||||
103 | */ |
||||
104 | public $having; |
||||
105 | /** |
||||
106 | * @var array|null this is used to construct the UNION clause(s) in a SQL statement. |
||||
107 | * Each array element is an array of the following structure: |
||||
108 | * |
||||
109 | * - `query`: either a string or a [[Query]] object representing a query |
||||
110 | * - `all`: boolean, whether it should be `UNION ALL` or `UNION` |
||||
111 | */ |
||||
112 | public $union; |
||||
113 | /** |
||||
114 | * @var array|null this is used to construct the WITH section in a SQL query. |
||||
115 | * Each array element is an array of the following structure: |
||||
116 | * |
||||
117 | * - `query`: either a string or a [[Query]] object representing a query |
||||
118 | * - `alias`: string, alias of query for further usage |
||||
119 | * - `recursive`: boolean, whether it should be `WITH RECURSIVE` or `WITH` |
||||
120 | * @see withQuery() |
||||
121 | * @since 2.0.35 |
||||
122 | */ |
||||
123 | public $withQueries; |
||||
124 | /** |
||||
125 | * @var array|null list of query parameter values indexed by parameter placeholders. |
||||
126 | * For example, `[':name' => 'Dan', ':age' => 31]`. |
||||
127 | */ |
||||
128 | public $params = []; |
||||
129 | /** |
||||
130 | * @var int|bool|null the default number of seconds that query results can remain valid in cache. |
||||
131 | * Use 0 to indicate that the cached data will never expire. |
||||
132 | * Use a negative number to indicate that query cache should not be used. |
||||
133 | * Use boolean `true` to indicate that [[Connection::queryCacheDuration]] should be used. |
||||
134 | * @see cache() |
||||
135 | * @since 2.0.14 |
||||
136 | */ |
||||
137 | public $queryCacheDuration; |
||||
138 | /** |
||||
139 | * @var \yii\caching\Dependency|null the dependency to be associated with the cached query result for this query |
||||
140 | * @see cache() |
||||
141 | * @since 2.0.14 |
||||
142 | */ |
||||
143 | public $queryCacheDependency; |
||||
144 | |||||
145 | |||||
146 | /** |
||||
147 | * Creates a DB command that can be used to execute this query. |
||||
148 | * @param Connection|null $db the database connection used to generate the SQL statement. |
||||
149 | * If this parameter is not given, the `db` application component will be used. |
||||
150 | * @return Command the created DB command instance. |
||||
151 | */ |
||||
152 | 15 | public function createCommand($db = null) |
|||
153 | { |
||||
154 | 15 | if ($db === null) { |
|||
155 | $db = Yii::$app->getDb(); |
||||
156 | } |
||||
157 | 15 | list($sql, $params) = $db->getQueryBuilder()->build($this); |
|||
158 | |||||
159 | 15 | $command = $db->createCommand($sql, $params); |
|||
160 | 15 | $this->setCommandCache($command); |
|||
161 | |||||
162 | 15 | return $command; |
|||
163 | } |
||||
164 | |||||
165 | /** |
||||
166 | * Prepares for building SQL. |
||||
167 | * This method is called by [[QueryBuilder]] when it starts to build SQL from a query object. |
||||
168 | * You may override this method to do some final preparation work when converting a query into a SQL statement. |
||||
169 | * @param QueryBuilder $builder |
||||
170 | * @return $this a prepared query instance which will be used by [[QueryBuilder]] to build the SQL |
||||
171 | */ |
||||
172 | 15 | public function prepare($builder) |
|||
0 ignored issues
–
show
|
|||||
173 | { |
||||
174 | 15 | return $this; |
|||
175 | } |
||||
176 | |||||
177 | /** |
||||
178 | * Starts a batch query. |
||||
179 | * |
||||
180 | * A batch query supports fetching data in batches, which can keep the memory usage under a limit. |
||||
181 | * This method will return a [[BatchQueryResult]] object which implements the [[\Iterator]] interface |
||||
182 | * and can be traversed to retrieve the data in batches. |
||||
183 | * |
||||
184 | * For example, |
||||
185 | * |
||||
186 | * ```php |
||||
187 | * $query = (new Query)->from('user'); |
||||
188 | * foreach ($query->batch() as $rows) { |
||||
189 | * // $rows is an array of 100 or fewer rows from user table |
||||
190 | * } |
||||
191 | * ``` |
||||
192 | * |
||||
193 | * @param int $batchSize the number of records to be fetched in each batch. |
||||
194 | * @param Connection|null $db the database connection. If not set, the "db" application component will be used. |
||||
195 | * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface |
||||
196 | * and can be traversed to retrieve the data in batches. |
||||
197 | */ |
||||
198 | public function batch($batchSize = 100, $db = null) |
||||
199 | { |
||||
200 | return Yii::createObject([ |
||||
201 | 'class' => BatchQueryResult::class, |
||||
202 | 'query' => $this, |
||||
203 | 'batchSize' => $batchSize, |
||||
204 | 'db' => $db, |
||||
205 | 'each' => false, |
||||
206 | ]); |
||||
207 | } |
||||
208 | |||||
209 | /** |
||||
210 | * Starts a batch query and retrieves data row by row. |
||||
211 | * |
||||
212 | * This method is similar to [[batch()]] except that in each iteration of the result, |
||||
213 | * only one row of data is returned. For example, |
||||
214 | * |
||||
215 | * ```php |
||||
216 | * $query = (new Query)->from('user'); |
||||
217 | * foreach ($query->each() as $row) { |
||||
218 | * } |
||||
219 | * ``` |
||||
220 | * |
||||
221 | * @param int $batchSize the number of records to be fetched in each batch. |
||||
222 | * @param Connection|null $db the database connection. If not set, the "db" application component will be used. |
||||
223 | * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface |
||||
224 | * and can be traversed to retrieve the data in batches. |
||||
225 | */ |
||||
226 | public function each($batchSize = 100, $db = null) |
||||
227 | { |
||||
228 | return Yii::createObject([ |
||||
229 | 'class' => BatchQueryResult::class, |
||||
230 | 'query' => $this, |
||||
231 | 'batchSize' => $batchSize, |
||||
232 | 'db' => $db, |
||||
233 | 'each' => true, |
||||
234 | ]); |
||||
235 | } |
||||
236 | |||||
237 | /** |
||||
238 | * Executes the query and returns all results as an array. |
||||
239 | * @param Connection|null $db the database connection used to generate the SQL statement. |
||||
240 | * If this parameter is not given, the `db` application component will be used. |
||||
241 | * @return array the query results. If the query results in nothing, an empty array will be returned. |
||||
242 | */ |
||||
243 | 4 | public function all($db = null) |
|||
244 | { |
||||
245 | 4 | if ($this->emulateExecution) { |
|||
246 | return []; |
||||
247 | } |
||||
248 | |||||
249 | 4 | $rows = $this->createCommand($db)->queryAll(); |
|||
250 | |||||
251 | 4 | return $this->populate($rows); |
|||
252 | } |
||||
253 | |||||
254 | /** |
||||
255 | * Converts the raw query results into the format as specified by this query. |
||||
256 | * This method is internally used to convert the data fetched from database |
||||
257 | * into the format as required by this query. |
||||
258 | * @param array $rows the raw query result from database |
||||
259 | * @return array the converted query result |
||||
260 | */ |
||||
261 | 8 | public function populate($rows) |
|||
262 | { |
||||
263 | 8 | if ($this->indexBy === null) { |
|||
264 | 8 | return $rows; |
|||
265 | } |
||||
266 | $result = []; |
||||
267 | foreach ($rows as $row) { |
||||
268 | $result[ArrayHelper::getValue($row, $this->indexBy)] = $row; |
||||
269 | } |
||||
270 | |||||
271 | return $result; |
||||
272 | } |
||||
273 | |||||
274 | /** |
||||
275 | * Executes the query and returns a single row of result. |
||||
276 | * @param Connection|null $db the database connection used to generate the SQL statement. |
||||
277 | * If this parameter is not given, the `db` application component will be used. |
||||
278 | * @return array|bool the first row (in terms of an array) of the query result. False is returned if the query |
||||
279 | * results in nothing. |
||||
280 | */ |
||||
281 | 11 | public function one($db = null) |
|||
282 | { |
||||
283 | 11 | if ($this->emulateExecution) { |
|||
284 | return false; |
||||
285 | } |
||||
286 | |||||
287 | 11 | return $this->createCommand($db)->queryOne(); |
|||
288 | } |
||||
289 | |||||
290 | /** |
||||
291 | * Returns the query result as a scalar value. |
||||
292 | * The value returned will be the first column in the first row of the query results. |
||||
293 | * @param Connection|null $db the database connection used to generate the SQL statement. |
||||
294 | * If this parameter is not given, the `db` application component will be used. |
||||
295 | * @return string|int|null|false the value of the first column in the first row of the query result. |
||||
296 | * False is returned if the query result is empty. |
||||
297 | */ |
||||
298 | public function scalar($db = null) |
||||
299 | { |
||||
300 | if ($this->emulateExecution) { |
||||
301 | return null; |
||||
302 | } |
||||
303 | |||||
304 | return $this->createCommand($db)->queryScalar(); |
||||
305 | } |
||||
306 | |||||
307 | /** |
||||
308 | * Executes the query and returns the first column of the result. |
||||
309 | * @param Connection|null $db the database connection used to generate the SQL statement. |
||||
310 | * If this parameter is not given, the `db` application component will be used. |
||||
311 | * @return array the first column of the query result. An empty array is returned if the query results in nothing. |
||||
312 | */ |
||||
313 | public function column($db = null) |
||||
314 | { |
||||
315 | if ($this->emulateExecution) { |
||||
316 | return []; |
||||
317 | } |
||||
318 | |||||
319 | if ($this->indexBy === null) { |
||||
320 | return $this->createCommand($db)->queryColumn(); |
||||
321 | } |
||||
322 | |||||
323 | if (is_string($this->indexBy) && is_array($this->select) && count($this->select) === 1) { |
||||
324 | if (strpos($this->indexBy, '.') === false && count($tables = $this->getTablesUsedInFrom()) > 0) { |
||||
325 | $this->select[] = key($tables) . '.' . $this->indexBy; |
||||
326 | } else { |
||||
327 | $this->select[] = $this->indexBy; |
||||
328 | } |
||||
329 | } |
||||
330 | $rows = $this->createCommand($db)->queryAll(); |
||||
331 | $results = []; |
||||
332 | $column = null; |
||||
333 | if (is_string($this->indexBy)) { |
||||
334 | if (($dotPos = strpos($this->indexBy, '.')) === false) { |
||||
335 | $column = $this->indexBy; |
||||
336 | } else { |
||||
337 | $column = substr($this->indexBy, $dotPos + 1); |
||||
338 | } |
||||
339 | } |
||||
340 | foreach ($rows as $row) { |
||||
341 | $value = reset($row); |
||||
342 | |||||
343 | if ($this->indexBy instanceof \Closure) { |
||||
344 | $results[call_user_func($this->indexBy, $row)] = $value; |
||||
345 | } else { |
||||
346 | $results[$row[$column]] = $value; |
||||
347 | } |
||||
348 | } |
||||
349 | |||||
350 | return $results; |
||||
351 | } |
||||
352 | |||||
353 | /** |
||||
354 | * Returns the number of records. |
||||
355 | * @param string $q the COUNT expression. Defaults to '*'. |
||||
356 | * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression. |
||||
357 | * @param Connection|null $db the database connection used to generate the SQL statement. |
||||
358 | * If this parameter is not given (or null), the `db` application component will be used. |
||||
359 | * @return int|string|null number of records. The result may be a string depending on the |
||||
360 | * underlying database engine and to support integer values higher than a 32bit PHP integer can handle. |
||||
361 | */ |
||||
362 | 12 | public function count($q = '*', $db = null) |
|||
363 | { |
||||
364 | 12 | if ($this->emulateExecution) { |
|||
365 | return 0; |
||||
366 | } |
||||
367 | |||||
368 | 12 | return $this->queryScalar("COUNT($q)", $db); |
|||
369 | } |
||||
370 | |||||
371 | /** |
||||
372 | * Returns the sum of the specified column values. |
||||
373 | * @param string $q the column name or expression. |
||||
374 | * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression. |
||||
375 | * @param Connection|null $db the database connection used to generate the SQL statement. |
||||
376 | * If this parameter is not given, the `db` application component will be used. |
||||
377 | * @return mixed the sum of the specified column values. |
||||
378 | */ |
||||
379 | public function sum($q, $db = null) |
||||
380 | { |
||||
381 | if ($this->emulateExecution) { |
||||
382 | return 0; |
||||
383 | } |
||||
384 | |||||
385 | return $this->queryScalar("SUM($q)", $db); |
||||
386 | } |
||||
387 | |||||
388 | /** |
||||
389 | * Returns the average of the specified column values. |
||||
390 | * @param string $q the column name or expression. |
||||
391 | * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression. |
||||
392 | * @param Connection|null $db the database connection used to generate the SQL statement. |
||||
393 | * If this parameter is not given, the `db` application component will be used. |
||||
394 | * @return mixed the average of the specified column values. |
||||
395 | */ |
||||
396 | public function average($q, $db = null) |
||||
397 | { |
||||
398 | if ($this->emulateExecution) { |
||||
399 | return 0; |
||||
400 | } |
||||
401 | |||||
402 | return $this->queryScalar("AVG($q)", $db); |
||||
403 | } |
||||
404 | |||||
405 | /** |
||||
406 | * Returns the minimum of the specified column values. |
||||
407 | * @param string $q the column name or expression. |
||||
408 | * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression. |
||||
409 | * @param Connection|null $db the database connection used to generate the SQL statement. |
||||
410 | * If this parameter is not given, the `db` application component will be used. |
||||
411 | * @return mixed the minimum of the specified column values. |
||||
412 | */ |
||||
413 | public function min($q, $db = null) |
||||
414 | { |
||||
415 | return $this->queryScalar("MIN($q)", $db); |
||||
416 | } |
||||
417 | |||||
418 | /** |
||||
419 | * Returns the maximum of the specified column values. |
||||
420 | * @param string $q the column name or expression. |
||||
421 | * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression. |
||||
422 | * @param Connection|null $db the database connection used to generate the SQL statement. |
||||
423 | * If this parameter is not given, the `db` application component will be used. |
||||
424 | * @return mixed the maximum of the specified column values. |
||||
425 | */ |
||||
426 | public function max($q, $db = null) |
||||
427 | { |
||||
428 | return $this->queryScalar("MAX($q)", $db); |
||||
429 | } |
||||
430 | |||||
431 | /** |
||||
432 | * Returns a value indicating whether the query result contains any row of data. |
||||
433 | * @param Connection|null $db the database connection used to generate the SQL statement. |
||||
434 | * If this parameter is not given, the `db` application component will be used. |
||||
435 | * @return bool whether the query result contains any row of data. |
||||
436 | */ |
||||
437 | 7 | public function exists($db = null) |
|||
438 | { |
||||
439 | 7 | if ($this->emulateExecution) { |
|||
440 | return false; |
||||
441 | } |
||||
442 | 7 | $command = $this->createCommand($db); |
|||
443 | 7 | $params = $command->params; |
|||
444 | 7 | $command->setSql($command->db->getQueryBuilder()->selectExists($command->getSql())); |
|||
445 | 7 | $command->bindValues($params); |
|||
446 | 7 | return (bool) $command->queryScalar(); |
|||
447 | } |
||||
448 | |||||
449 | /** |
||||
450 | * Queries a scalar value by setting [[select]] first. |
||||
451 | * Restores the value of select to make this query reusable. |
||||
452 | * @param string|ExpressionInterface $selectExpression |
||||
453 | * @param Connection|null $db the database connection used to execute the query. |
||||
454 | * @return bool|string|null |
||||
455 | * @throws \Throwable if can't create command |
||||
456 | */ |
||||
457 | 12 | protected function queryScalar($selectExpression, $db) |
|||
458 | { |
||||
459 | 12 | if ($this->emulateExecution) { |
|||
460 | return null; |
||||
461 | } |
||||
462 | |||||
463 | if ( |
||||
464 | 12 | !$this->distinct |
|||
465 | 12 | && empty($this->groupBy) |
|||
466 | 12 | && empty($this->having) |
|||
467 | 12 | && empty($this->union) |
|||
468 | ) { |
||||
469 | 12 | $select = $this->select; |
|||
470 | 12 | $order = $this->orderBy; |
|||
471 | 12 | $limit = $this->limit; |
|||
472 | 12 | $offset = $this->offset; |
|||
473 | |||||
474 | 12 | $this->select = [$selectExpression]; |
|||
475 | 12 | $this->orderBy = null; |
|||
476 | 12 | $this->limit = null; |
|||
477 | 12 | $this->offset = null; |
|||
478 | |||||
479 | 12 | $e = null; |
|||
480 | try { |
||||
481 | 12 | $command = $this->createCommand($db); |
|||
482 | } catch (\Exception $e) { |
||||
483 | // throw it later (for PHP < 7.0) |
||||
484 | } catch (\Throwable $e) { |
||||
485 | // throw it later |
||||
486 | } |
||||
487 | |||||
488 | 12 | $this->select = $select; |
|||
489 | 12 | $this->orderBy = $order; |
|||
490 | 12 | $this->limit = $limit; |
|||
491 | 12 | $this->offset = $offset; |
|||
492 | |||||
493 | 12 | if ($e !== null) { |
|||
494 | throw $e; |
||||
495 | } |
||||
496 | |||||
497 | 12 | return $command->queryScalar(); |
|||
498 | } |
||||
499 | |||||
500 | $command = (new self()) |
||||
501 | ->select([$selectExpression]) |
||||
502 | ->from(['c' => $this]) |
||||
503 | ->createCommand($db); |
||||
504 | $this->setCommandCache($command); |
||||
505 | |||||
506 | return $command->queryScalar(); |
||||
507 | } |
||||
508 | |||||
509 | /** |
||||
510 | * Returns table names used in [[from]] indexed by aliases. |
||||
511 | * Both aliases and names are enclosed into {{ and }}. |
||||
512 | * @return string[] table names indexed by aliases |
||||
513 | * @throws \yii\base\InvalidConfigException |
||||
514 | * @since 2.0.12 |
||||
515 | */ |
||||
516 | public function getTablesUsedInFrom() |
||||
517 | { |
||||
518 | if (empty($this->from)) { |
||||
519 | return []; |
||||
520 | } |
||||
521 | |||||
522 | if (is_array($this->from)) { |
||||
0 ignored issues
–
show
|
|||||
523 | $tableNames = $this->from; |
||||
524 | } elseif (is_string($this->from)) { |
||||
525 | $tableNames = preg_split('/\s*,\s*/', trim($this->from), -1, PREG_SPLIT_NO_EMPTY); |
||||
526 | } elseif ($this->from instanceof Expression) { |
||||
527 | $tableNames = [$this->from]; |
||||
528 | } else { |
||||
529 | throw new InvalidConfigException(gettype($this->from) . ' in $from is not supported.'); |
||||
530 | } |
||||
531 | |||||
532 | return $this->cleanUpTableNames($tableNames); |
||||
533 | } |
||||
534 | |||||
535 | /** |
||||
536 | * Clean up table names and aliases |
||||
537 | * Both aliases and names are enclosed into {{ and }}. |
||||
538 | * @param array $tableNames non-empty array |
||||
539 | * @return string[] table names indexed by aliases |
||||
540 | * @since 2.0.14 |
||||
541 | */ |
||||
542 | 9 | protected function cleanUpTableNames($tableNames) |
|||
543 | { |
||||
544 | 9 | $cleanedUpTableNames = []; |
|||
545 | 9 | foreach ($tableNames as $alias => $tableName) { |
|||
546 | 9 | if (is_string($tableName) && !is_string($alias)) { |
|||
547 | 9 | $pattern = <<<PATTERN |
|||
548 | ~ |
||||
549 | ^ |
||||
550 | \s* |
||||
551 | ( |
||||
552 | (?:['"`\[]|{{) |
||||
553 | .*? |
||||
554 | (?:['"`\]]|}}) |
||||
555 | | |
||||
556 | \(.*?\) |
||||
557 | | |
||||
558 | .*? |
||||
559 | ) |
||||
560 | (?: |
||||
561 | (?: |
||||
562 | \s+ |
||||
563 | (?:as)? |
||||
564 | \s* |
||||
565 | ) |
||||
566 | ( |
||||
567 | (?:['"`\[]|{{) |
||||
568 | .*? |
||||
569 | (?:['"`\]]|}}) |
||||
570 | | |
||||
571 | .*? |
||||
572 | ) |
||||
573 | )? |
||||
574 | \s* |
||||
575 | $ |
||||
576 | ~iux |
||||
577 | 9 | PATTERN; |
|||
578 | 9 | if (preg_match($pattern, $tableName, $matches)) { |
|||
579 | 9 | if (isset($matches[2])) { |
|||
580 | list(, $tableName, $alias) = $matches; |
||||
581 | } else { |
||||
582 | 9 | $tableName = $alias = $matches[1]; |
|||
583 | } |
||||
584 | } |
||||
585 | } |
||||
586 | |||||
587 | |||||
588 | 9 | if ($tableName instanceof Expression) { |
|||
589 | if (!is_string($alias)) { |
||||
590 | throw new InvalidArgumentException('To use Expression in from() method, pass it in array format with alias.'); |
||||
591 | } |
||||
592 | $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName; |
||||
593 | 9 | } elseif ($tableName instanceof self) { |
|||
594 | $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName; |
||||
595 | } else { |
||||
596 | 9 | $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $this->ensureNameQuoted($tableName); |
|||
597 | } |
||||
598 | } |
||||
599 | |||||
600 | 9 | return $cleanedUpTableNames; |
|||
601 | } |
||||
602 | |||||
603 | /** |
||||
604 | * Ensures name is wrapped with {{ and }} |
||||
605 | * @param string $name |
||||
606 | * @return string |
||||
607 | */ |
||||
608 | 9 | private function ensureNameQuoted($name) |
|||
609 | { |
||||
610 | 9 | $name = str_replace(["'", '"', '`', '[', ']'], '', $name); |
|||
611 | 9 | if ($name && !preg_match('/^{{.*}}$/', $name)) { |
|||
612 | 9 | return '{{' . $name . '}}'; |
|||
613 | } |
||||
614 | |||||
615 | return $name; |
||||
616 | } |
||||
617 | |||||
618 | /** |
||||
619 | * Sets the SELECT part of the query. |
||||
620 | * @param string|array|ExpressionInterface $columns the columns to be selected. |
||||
621 | * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']). |
||||
622 | * Columns can be prefixed with table names (e.g. "user.id") and/or contain column aliases (e.g. "user.id AS user_id"). |
||||
623 | * The method will automatically quote the column names unless a column contains some parenthesis |
||||
624 | * (which means the column contains a DB expression). A DB expression may also be passed in form of |
||||
625 | * an [[ExpressionInterface]] object. |
||||
626 | * |
||||
627 | * Note that if you are selecting an expression like `CONCAT(first_name, ' ', last_name)`, you should |
||||
628 | * use an array to specify the columns. Otherwise, the expression may be incorrectly split into several parts. |
||||
629 | * |
||||
630 | * When the columns are specified as an array, you may also use array keys as the column aliases (if a column |
||||
631 | * does not need alias, do not use a string key). |
||||
632 | * |
||||
633 | * Starting from version 2.0.1, you may also select sub-queries as columns by specifying each such column |
||||
634 | * as a `Query` instance representing the sub-query. |
||||
635 | * |
||||
636 | * @param string|null $option additional option that should be appended to the 'SELECT' keyword. For example, |
||||
637 | * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used. |
||||
638 | * @return $this the query object itself |
||||
639 | */ |
||||
640 | 4 | public function select($columns, $option = null) |
|||
641 | { |
||||
642 | 4 | $this->select = $this->normalizeSelect($columns); |
|||
643 | 4 | $this->selectOption = $option; |
|||
644 | 4 | return $this; |
|||
645 | } |
||||
646 | |||||
647 | /** |
||||
648 | * Add more columns to the SELECT part of the query. |
||||
649 | * |
||||
650 | * Note, that if [[select]] has not been specified before, you should include `*` explicitly |
||||
651 | * if you want to select all remaining columns too: |
||||
652 | * |
||||
653 | * ```php |
||||
654 | * $query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one(); |
||||
655 | * ``` |
||||
656 | * |
||||
657 | * @param string|array|ExpressionInterface $columns the columns to add to the select. See [[select()]] for more |
||||
658 | * details about the format of this parameter. |
||||
659 | * @return $this the query object itself |
||||
660 | * @see select() |
||||
661 | */ |
||||
662 | public function addSelect($columns) |
||||
663 | { |
||||
664 | if ($this->select === null) { |
||||
665 | return $this->select($columns); |
||||
666 | } |
||||
667 | if (!is_array($this->select)) { |
||||
0 ignored issues
–
show
|
|||||
668 | $this->select = $this->normalizeSelect($this->select); |
||||
669 | } |
||||
670 | $this->select = array_merge($this->select, $this->normalizeSelect($columns)); |
||||
671 | |||||
672 | return $this; |
||||
673 | } |
||||
674 | |||||
675 | /** |
||||
676 | * Normalizes the SELECT columns passed to [[select()]] or [[addSelect()]]. |
||||
677 | * |
||||
678 | * @param string|array|ExpressionInterface $columns |
||||
679 | * @return array |
||||
680 | * @since 2.0.21 |
||||
681 | */ |
||||
682 | 4 | protected function normalizeSelect($columns) |
|||
683 | { |
||||
684 | 4 | if ($columns instanceof ExpressionInterface) { |
|||
685 | $columns = [$columns]; |
||||
686 | 4 | } elseif (!is_array($columns)) { |
|||
687 | $columns = preg_split('/\s*,\s*/', trim((string)$columns), -1, PREG_SPLIT_NO_EMPTY); |
||||
688 | } |
||||
689 | 4 | $select = []; |
|||
690 | 4 | foreach ($columns as $columnAlias => $columnDefinition) { |
|||
691 | 4 | if (is_string($columnAlias)) { |
|||
692 | // Already in the normalized format, good for them |
||||
693 | $select[$columnAlias] = $columnDefinition; |
||||
694 | continue; |
||||
695 | } |
||||
696 | 4 | if (is_string($columnDefinition)) { |
|||
697 | if ( |
||||
698 | 4 | preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $columnDefinition, $matches) && |
|||
699 | 4 | !preg_match('/^\d+$/', $matches[2]) && |
|||
700 | 4 | strpos($matches[2], '.') === false |
|||
701 | ) { |
||||
702 | // Using "columnName as alias" or "columnName alias" syntax |
||||
703 | $select[$matches[2]] = $matches[1]; |
||||
704 | continue; |
||||
705 | } |
||||
706 | 4 | if (strpos($columnDefinition, '(') === false) { |
|||
707 | // Normal column name, just alias it to itself to ensure it's not selected twice |
||||
708 | 4 | $select[$columnDefinition] = $columnDefinition; |
|||
709 | 4 | continue; |
|||
710 | } |
||||
711 | } |
||||
712 | // Either a string calling a function, DB expression, or sub-query |
||||
713 | $select[] = $columnDefinition; |
||||
714 | } |
||||
715 | 4 | return $select; |
|||
716 | } |
||||
717 | |||||
718 | /** |
||||
719 | * Sets the value indicating whether to SELECT DISTINCT or not. |
||||
720 | * @param bool $value whether to SELECT DISTINCT or not. |
||||
721 | * @return $this the query object itself |
||||
722 | */ |
||||
723 | public function distinct($value = true) |
||||
724 | { |
||||
725 | $this->distinct = $value; |
||||
726 | return $this; |
||||
727 | } |
||||
728 | |||||
729 | /** |
||||
730 | * Sets the FROM part of the query. |
||||
731 | * @param string|array|ExpressionInterface $tables the table(s) to be selected from. This can be either a string (e.g. `'user'`) |
||||
732 | * or an array (e.g. `['user', 'profile']`) specifying one or several table names. |
||||
733 | * Table names can contain schema prefixes (e.g. `'public.user'`) and/or table aliases (e.g. `'user u'`). |
||||
734 | * The method will automatically quote the table names unless it contains some parenthesis |
||||
735 | * (which means the table is given as a sub-query or DB expression). |
||||
736 | * |
||||
737 | * When the tables are specified as an array, you may also use the array keys as the table aliases |
||||
738 | * (if a table does not need alias, do not use a string key). |
||||
739 | * |
||||
740 | * Use a Query object to represent a sub-query. In this case, the corresponding array key will be used |
||||
741 | * as the alias for the sub-query. |
||||
742 | * |
||||
743 | * To specify the `FROM` part in plain SQL, you may pass an instance of [[ExpressionInterface]]. |
||||
744 | * |
||||
745 | * Here are some examples: |
||||
746 | * |
||||
747 | * ```php |
||||
748 | * // SELECT * FROM `user` `u`, `profile`; |
||||
749 | * $query = (new \yii\db\Query)->from(['u' => 'user', 'profile']); |
||||
750 | * |
||||
751 | * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`; |
||||
752 | * $subquery = (new \yii\db\Query)->from('user')->where(['active' => true]) |
||||
753 | * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]); |
||||
754 | * |
||||
755 | * // subquery can also be a string with plain SQL wrapped in parenthesis |
||||
756 | * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`; |
||||
757 | * $subquery = "(SELECT * FROM `user` WHERE `active` = 1)"; |
||||
758 | * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]); |
||||
759 | * ``` |
||||
760 | * |
||||
761 | * @return $this the query object itself |
||||
762 | */ |
||||
763 | 4 | public function from($tables) |
|||
764 | { |
||||
765 | 4 | if ($tables instanceof ExpressionInterface) { |
|||
766 | $tables = [$tables]; |
||||
767 | } |
||||
768 | 4 | if (is_string($tables)) { |
|||
769 | 4 | $tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY); |
|||
770 | } |
||||
771 | 4 | $this->from = $tables; |
|||
0 ignored issues
–
show
It seems like
$tables can also be of type string . However, the property $from is declared as type array|null . 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 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;
}
![]() |
|||||
772 | 4 | return $this; |
|||
773 | } |
||||
774 | |||||
775 | /** |
||||
776 | * Sets the WHERE part of the query. |
||||
777 | * |
||||
778 | * The method requires a `$condition` parameter, and optionally a `$params` parameter |
||||
779 | * specifying the values to be bound to the query. |
||||
780 | * |
||||
781 | * The `$condition` parameter should be either a string (e.g. `'id=1'`) or an array. |
||||
782 | * |
||||
783 | * {@inheritdoc} |
||||
784 | * |
||||
785 | * @param string|array|ExpressionInterface $condition the conditions that should be put in the WHERE part. |
||||
786 | * @param array $params the parameters (name => value) to be bound to the query. |
||||
787 | * @return $this the query object itself |
||||
788 | * @see andWhere() |
||||
789 | * @see orWhere() |
||||
790 | * @see QueryInterface::where() |
||||
791 | */ |
||||
792 | 4 | public function where($condition, $params = []) |
|||
793 | { |
||||
794 | 4 | $this->where = $condition; |
|||
795 | 4 | $this->addParams($params); |
|||
796 | 4 | return $this; |
|||
797 | } |
||||
798 | |||||
799 | /** |
||||
800 | * Adds an additional WHERE condition to the existing one. |
||||
801 | * The new condition and the existing one will be joined using the `AND` operator. |
||||
802 | * @param string|array|ExpressionInterface $condition the new WHERE condition. Please refer to [[where()]] |
||||
803 | * on how to specify this parameter. |
||||
804 | * @param array $params the parameters (name => value) to be bound to the query. |
||||
805 | * @return $this the query object itself |
||||
806 | * @see where() |
||||
807 | * @see orWhere() |
||||
808 | */ |
||||
809 | 9 | public function andWhere($condition, $params = []) |
|||
810 | { |
||||
811 | 9 | if ($this->where === null) { |
|||
812 | 9 | $this->where = $condition; |
|||
813 | } elseif (is_array($this->where) && isset($this->where[0]) && strcasecmp($this->where[0], 'and') === 0) { |
||||
814 | $this->where[] = $condition; |
||||
815 | } else { |
||||
816 | $this->where = ['and', $this->where, $condition]; |
||||
817 | } |
||||
818 | 9 | $this->addParams($params); |
|||
819 | 9 | return $this; |
|||
820 | } |
||||
821 | |||||
822 | /** |
||||
823 | * Adds an additional WHERE condition to the existing one. |
||||
824 | * The new condition and the existing one will be joined using the `OR` operator. |
||||
825 | * @param string|array|ExpressionInterface $condition the new WHERE condition. Please refer to [[where()]] |
||||
826 | * on how to specify this parameter. |
||||
827 | * @param array $params the parameters (name => value) to be bound to the query. |
||||
828 | * @return $this the query object itself |
||||
829 | * @see where() |
||||
830 | * @see andWhere() |
||||
831 | */ |
||||
832 | 2 | public function orWhere($condition, $params = []) |
|||
833 | { |
||||
834 | 2 | if ($this->where === null) { |
|||
835 | $this->where = $condition; |
||||
836 | } else { |
||||
837 | 2 | $this->where = ['or', $this->where, $condition]; |
|||
838 | } |
||||
839 | 2 | $this->addParams($params); |
|||
840 | 2 | return $this; |
|||
841 | } |
||||
842 | |||||
843 | /** |
||||
844 | * Adds a filtering condition for a specific column and allow the user to choose a filter operator. |
||||
845 | * |
||||
846 | * It adds an additional WHERE condition for the given field and determines the comparison operator |
||||
847 | * based on the first few characters of the given value. |
||||
848 | * The condition is added in the same way as in [[andFilterWhere]] so [[isEmpty()|empty values]] are ignored. |
||||
849 | * The new condition and the existing one will be joined using the `AND` operator. |
||||
850 | * |
||||
851 | * The comparison operator is intelligently determined based on the first few characters in the given value. |
||||
852 | * In particular, it recognizes the following operators if they appear as the leading characters in the given value: |
||||
853 | * |
||||
854 | * - `<`: the column must be less than the given value. |
||||
855 | * - `>`: the column must be greater than the given value. |
||||
856 | * - `<=`: the column must be less than or equal to the given value. |
||||
857 | * - `>=`: the column must be greater than or equal to the given value. |
||||
858 | * - `<>`: the column must not be the same as the given value. |
||||
859 | * - `=`: the column must be equal to the given value. |
||||
860 | * - If none of the above operators is detected, the `$defaultOperator` will be used. |
||||
861 | * |
||||
862 | * @param string $name the column name. |
||||
863 | * @param string $value the column value optionally prepended with the comparison operator. |
||||
864 | * @param string $defaultOperator The operator to use, when no operator is given in `$value`. |
||||
865 | * Defaults to `=`, performing an exact match. |
||||
866 | * @return $this The query object itself |
||||
867 | * @since 2.0.8 |
||||
868 | */ |
||||
869 | public function andFilterCompare($name, $value, $defaultOperator = '=') |
||||
870 | { |
||||
871 | if (preg_match('/^(<>|>=|>|<=|<|=)/', (string)$value, $matches)) { |
||||
872 | $operator = $matches[1]; |
||||
873 | $value = substr($value, strlen($operator)); |
||||
874 | } else { |
||||
875 | $operator = $defaultOperator; |
||||
876 | } |
||||
877 | |||||
878 | return $this->andFilterWhere([$operator, $name, $value]); |
||||
879 | } |
||||
880 | |||||
881 | /** |
||||
882 | * Appends a JOIN part to the query. |
||||
883 | * The first parameter specifies what type of join it is. |
||||
884 | * @param string $type the type of join, such as INNER JOIN, LEFT JOIN. |
||||
885 | * @param string|array $table the table or sub-query to be joined. |
||||
886 | * |
||||
887 | * Use a string to represent the name of the table to be joined. |
||||
888 | * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). |
||||
889 | * The method will automatically quote the table name unless it contains some parenthesis |
||||
890 | * (which means the table is given as a sub-query or DB expression). |
||||
891 | * |
||||
892 | * You may also specify the table as an array with one element, using the array key as the table alias |
||||
893 | * (e.g. ['u' => 'user']). |
||||
894 | * |
||||
895 | * To join a sub-query, use an array with one element, with the value set to a [[Query]] object |
||||
896 | * representing the sub-query, and the corresponding key representing the alias. |
||||
897 | * |
||||
898 | * @param string|array $on the join condition that should appear in the ON part. |
||||
899 | * Please refer to [[where()]] on how to specify this parameter. |
||||
900 | * |
||||
901 | * Note that the array format of [[where()]] is designed to match columns to values instead of columns to columns, so |
||||
902 | * the following would **not** work as expected: `['post.author_id' => 'user.id']`, it would |
||||
903 | * match the `post.author_id` column value against the string `'user.id'`. |
||||
904 | * It is recommended to use the string syntax here which is more suited for a join: |
||||
905 | * |
||||
906 | * ```php |
||||
907 | * 'post.author_id = user.id' |
||||
908 | * ``` |
||||
909 | * |
||||
910 | * @param array $params the parameters (name => value) to be bound to the query. |
||||
911 | * @return $this the query object itself |
||||
912 | */ |
||||
913 | public function join($type, $table, $on = '', $params = []) |
||||
914 | { |
||||
915 | $this->join[] = [$type, $table, $on]; |
||||
916 | return $this->addParams($params); |
||||
917 | } |
||||
918 | |||||
919 | /** |
||||
920 | * Appends an INNER JOIN part to the query. |
||||
921 | * @param string|array $table the table or sub-query to be joined. |
||||
922 | * |
||||
923 | * Use a string to represent the name of the table to be joined. |
||||
924 | * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). |
||||
925 | * The method will automatically quote the table name unless it contains some parenthesis |
||||
926 | * (which means the table is given as a sub-query or DB expression). |
||||
927 | * |
||||
928 | * You may also specify the table as an array with one element, using the array key as the table alias |
||||
929 | * (e.g. ['u' => 'user']). |
||||
930 | * |
||||
931 | * To join a sub-query, use an array with one element, with the value set to a [[Query]] object |
||||
932 | * representing the sub-query, and the corresponding key representing the alias. |
||||
933 | * |
||||
934 | * @param string|array $on the join condition that should appear in the ON part. |
||||
935 | * Please refer to [[join()]] on how to specify this parameter. |
||||
936 | * @param array $params the parameters (name => value) to be bound to the query. |
||||
937 | * @return $this the query object itself |
||||
938 | */ |
||||
939 | public function innerJoin($table, $on = '', $params = []) |
||||
940 | { |
||||
941 | $this->join[] = ['INNER JOIN', $table, $on]; |
||||
942 | return $this->addParams($params); |
||||
943 | } |
||||
944 | |||||
945 | /** |
||||
946 | * Appends a LEFT OUTER JOIN part to the query. |
||||
947 | * @param string|array $table the table or sub-query to be joined. |
||||
948 | * |
||||
949 | * Use a string to represent the name of the table to be joined. |
||||
950 | * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). |
||||
951 | * The method will automatically quote the table name unless it contains some parenthesis |
||||
952 | * (which means the table is given as a sub-query or DB expression). |
||||
953 | * |
||||
954 | * You may also specify the table as an array with one element, using the array key as the table alias |
||||
955 | * (e.g. ['u' => 'user']). |
||||
956 | * |
||||
957 | * To join a sub-query, use an array with one element, with the value set to a [[Query]] object |
||||
958 | * representing the sub-query, and the corresponding key representing the alias. |
||||
959 | * |
||||
960 | * @param string|array $on the join condition that should appear in the ON part. |
||||
961 | * Please refer to [[join()]] 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 | */ |
||||
965 | public function leftJoin($table, $on = '', $params = []) |
||||
966 | { |
||||
967 | $this->join[] = ['LEFT JOIN', $table, $on]; |
||||
968 | return $this->addParams($params); |
||||
969 | } |
||||
970 | |||||
971 | /** |
||||
972 | * Appends a RIGHT OUTER JOIN part to the query. |
||||
973 | * @param string|array $table the table or sub-query to be joined. |
||||
974 | * |
||||
975 | * Use a string to represent the name of the table to be joined. |
||||
976 | * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). |
||||
977 | * The method will automatically quote the table name unless it contains some parenthesis |
||||
978 | * (which means the table is given as a sub-query or DB expression). |
||||
979 | * |
||||
980 | * You may also specify the table as an array with one element, using the array key as the table alias |
||||
981 | * (e.g. ['u' => 'user']). |
||||
982 | * |
||||
983 | * To join a sub-query, use an array with one element, with the value set to a [[Query]] object |
||||
984 | * representing the sub-query, and the corresponding key representing the alias. |
||||
985 | * |
||||
986 | * @param string|array $on the join condition that should appear in the ON part. |
||||
987 | * Please refer to [[join()]] on how to specify this parameter. |
||||
988 | * @param array $params the parameters (name => value) to be bound to the query |
||||
989 | * @return $this the query object itself |
||||
990 | */ |
||||
991 | public function rightJoin($table, $on = '', $params = []) |
||||
992 | { |
||||
993 | $this->join[] = ['RIGHT JOIN', $table, $on]; |
||||
994 | return $this->addParams($params); |
||||
995 | } |
||||
996 | |||||
997 | /** |
||||
998 | * Sets the GROUP BY part of the query. |
||||
999 | * @param string|array|ExpressionInterface|null $columns the columns to be grouped by. |
||||
1000 | * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']). |
||||
1001 | * The method will automatically quote the column names unless a column contains some parenthesis |
||||
1002 | * (which means the column contains a DB expression). |
||||
1003 | * |
||||
1004 | * Note that if your group-by is an expression containing commas, you should always use an array |
||||
1005 | * to represent the group-by information. Otherwise, the method will not be able to correctly determine |
||||
1006 | * the group-by columns. |
||||
1007 | * |
||||
1008 | * Since version 2.0.7, an [[ExpressionInterface]] object can be passed to specify the GROUP BY part explicitly in plain SQL. |
||||
1009 | * Since version 2.0.14, an [[ExpressionInterface]] object can be passed as well. |
||||
1010 | * @return $this the query object itself |
||||
1011 | * @see addGroupBy() |
||||
1012 | */ |
||||
1013 | public function groupBy($columns) |
||||
1014 | { |
||||
1015 | if ($columns instanceof ExpressionInterface) { |
||||
1016 | $columns = [$columns]; |
||||
1017 | } elseif (!is_array($columns) && !is_null($columns)) { |
||||
1018 | $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY); |
||||
1019 | } |
||||
1020 | $this->groupBy = $columns; |
||||
1021 | return $this; |
||||
1022 | } |
||||
1023 | |||||
1024 | /** |
||||
1025 | * Adds additional group-by columns to the existing ones. |
||||
1026 | * @param string|array|ExpressionInterface $columns additional columns to be grouped by. |
||||
1027 | * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']). |
||||
1028 | * The method will automatically quote the column names unless a column contains some parenthesis |
||||
1029 | * (which means the column contains a DB expression). |
||||
1030 | * |
||||
1031 | * Note that if your group-by is an expression containing commas, you should always use an array |
||||
1032 | * to represent the group-by information. Otherwise, the method will not be able to correctly determine |
||||
1033 | * the group-by columns. |
||||
1034 | * |
||||
1035 | * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL. |
||||
1036 | * Since version 2.0.14, an [[ExpressionInterface]] object can be passed as well. |
||||
1037 | * @return $this the query object itself |
||||
1038 | * @see groupBy() |
||||
1039 | */ |
||||
1040 | public function addGroupBy($columns) |
||||
1041 | { |
||||
1042 | if ($columns instanceof ExpressionInterface) { |
||||
1043 | $columns = [$columns]; |
||||
1044 | } elseif (!is_array($columns)) { |
||||
1045 | $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY); |
||||
1046 | } |
||||
1047 | if ($this->groupBy === null) { |
||||
1048 | $this->groupBy = $columns; |
||||
1049 | } else { |
||||
1050 | $this->groupBy = array_merge($this->groupBy, $columns); |
||||
1051 | } |
||||
1052 | |||||
1053 | return $this; |
||||
1054 | } |
||||
1055 | |||||
1056 | /** |
||||
1057 | * Sets the HAVING part of the query. |
||||
1058 | * @param string|array|ExpressionInterface $condition the conditions to be put after HAVING. |
||||
1059 | * Please refer to [[where()]] on how to specify this parameter. |
||||
1060 | * @param array $params the parameters (name => value) to be bound to the query. |
||||
1061 | * @return $this the query object itself |
||||
1062 | * @see andHaving() |
||||
1063 | * @see orHaving() |
||||
1064 | */ |
||||
1065 | public function having($condition, $params = []) |
||||
1066 | { |
||||
1067 | $this->having = $condition; |
||||
1068 | $this->addParams($params); |
||||
1069 | return $this; |
||||
1070 | } |
||||
1071 | |||||
1072 | /** |
||||
1073 | * Adds an additional HAVING condition to the existing one. |
||||
1074 | * The new condition and the existing one will be joined using the `AND` operator. |
||||
1075 | * @param string|array|ExpressionInterface $condition the new HAVING condition. Please refer to [[where()]] |
||||
1076 | * on how to specify this parameter. |
||||
1077 | * @param array $params the parameters (name => value) to be bound to the query. |
||||
1078 | * @return $this the query object itself |
||||
1079 | * @see having() |
||||
1080 | * @see orHaving() |
||||
1081 | */ |
||||
1082 | public function andHaving($condition, $params = []) |
||||
1083 | { |
||||
1084 | if ($this->having === null) { |
||||
1085 | $this->having = $condition; |
||||
1086 | } else { |
||||
1087 | $this->having = ['and', $this->having, $condition]; |
||||
1088 | } |
||||
1089 | $this->addParams($params); |
||||
1090 | return $this; |
||||
1091 | } |
||||
1092 | |||||
1093 | /** |
||||
1094 | * Adds an additional HAVING condition to the existing one. |
||||
1095 | * The new condition and the existing one will be joined using the `OR` operator. |
||||
1096 | * @param string|array|ExpressionInterface $condition the new HAVING condition. Please refer to [[where()]] |
||||
1097 | * on how to specify this parameter. |
||||
1098 | * @param array $params the parameters (name => value) to be bound to the query. |
||||
1099 | * @return $this the query object itself |
||||
1100 | * @see having() |
||||
1101 | * @see andHaving() |
||||
1102 | */ |
||||
1103 | public function orHaving($condition, $params = []) |
||||
1104 | { |
||||
1105 | if ($this->having === null) { |
||||
1106 | $this->having = $condition; |
||||
1107 | } else { |
||||
1108 | $this->having = ['or', $this->having, $condition]; |
||||
1109 | } |
||||
1110 | $this->addParams($params); |
||||
1111 | return $this; |
||||
1112 | } |
||||
1113 | |||||
1114 | /** |
||||
1115 | * Sets the HAVING part of the query but ignores [[isEmpty()|empty operands]]. |
||||
1116 | * |
||||
1117 | * This method is similar to [[having()]]. The main difference is that this method will |
||||
1118 | * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited |
||||
1119 | * for building query conditions based on filter values entered by users. |
||||
1120 | * |
||||
1121 | * The following code shows the difference between this method and [[having()]]: |
||||
1122 | * |
||||
1123 | * ```php |
||||
1124 | * // HAVING `age`=:age |
||||
1125 | * $query->filterHaving(['name' => null, 'age' => 20]); |
||||
1126 | * // HAVING `age`=:age |
||||
1127 | * $query->having(['age' => 20]); |
||||
1128 | * // HAVING `name` IS NULL AND `age`=:age |
||||
1129 | * $query->having(['name' => null, 'age' => 20]); |
||||
1130 | * ``` |
||||
1131 | * |
||||
1132 | * Note that unlike [[having()]], you cannot pass binding parameters to this method. |
||||
1133 | * |
||||
1134 | * @param array $condition the conditions that should be put in the HAVING part. |
||||
1135 | * See [[having()]] on how to specify this parameter. |
||||
1136 | * @return $this the query object itself |
||||
1137 | * @see having() |
||||
1138 | * @see andFilterHaving() |
||||
1139 | * @see orFilterHaving() |
||||
1140 | * @since 2.0.11 |
||||
1141 | */ |
||||
1142 | public function filterHaving(array $condition) |
||||
1143 | { |
||||
1144 | $condition = $this->filterCondition($condition); |
||||
1145 | if ($condition !== []) { |
||||
1146 | $this->having($condition); |
||||
1147 | } |
||||
1148 | |||||
1149 | return $this; |
||||
1150 | } |
||||
1151 | |||||
1152 | /** |
||||
1153 | * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]]. |
||||
1154 | * The new condition and the existing one will be joined using the `AND` operator. |
||||
1155 | * |
||||
1156 | * This method is similar to [[andHaving()]]. The main difference is that this method will |
||||
1157 | * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited |
||||
1158 | * for building query conditions based on filter values entered by users. |
||||
1159 | * |
||||
1160 | * @param array $condition the new HAVING condition. Please refer to [[having()]] |
||||
1161 | * on how to specify this parameter. |
||||
1162 | * @return $this the query object itself |
||||
1163 | * @see filterHaving() |
||||
1164 | * @see orFilterHaving() |
||||
1165 | * @since 2.0.11 |
||||
1166 | */ |
||||
1167 | public function andFilterHaving(array $condition) |
||||
1168 | { |
||||
1169 | $condition = $this->filterCondition($condition); |
||||
1170 | if ($condition !== []) { |
||||
1171 | $this->andHaving($condition); |
||||
1172 | } |
||||
1173 | |||||
1174 | return $this; |
||||
1175 | } |
||||
1176 | |||||
1177 | /** |
||||
1178 | * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]]. |
||||
1179 | * The new condition and the existing one will be joined using the `OR` operator. |
||||
1180 | * |
||||
1181 | * This method is similar to [[orHaving()]]. The main difference is that this method will |
||||
1182 | * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited |
||||
1183 | * for building query conditions based on filter values entered by users. |
||||
1184 | * |
||||
1185 | * @param array $condition the new HAVING condition. Please refer to [[having()]] |
||||
1186 | * on how to specify this parameter. |
||||
1187 | * @return $this the query object itself |
||||
1188 | * @see filterHaving() |
||||
1189 | * @see andFilterHaving() |
||||
1190 | * @since 2.0.11 |
||||
1191 | */ |
||||
1192 | public function orFilterHaving(array $condition) |
||||
1193 | { |
||||
1194 | $condition = $this->filterCondition($condition); |
||||
1195 | if ($condition !== []) { |
||||
1196 | $this->orHaving($condition); |
||||
1197 | } |
||||
1198 | |||||
1199 | return $this; |
||||
1200 | } |
||||
1201 | |||||
1202 | /** |
||||
1203 | * Appends a SQL statement using UNION operator. |
||||
1204 | * @param string|Query $sql the SQL statement to be appended using UNION |
||||
1205 | * @param bool $all TRUE if using UNION ALL and FALSE if using UNION |
||||
1206 | * @return $this the query object itself |
||||
1207 | */ |
||||
1208 | public function union($sql, $all = false) |
||||
1209 | { |
||||
1210 | $this->union[] = ['query' => $sql, 'all' => $all]; |
||||
1211 | return $this; |
||||
1212 | } |
||||
1213 | |||||
1214 | /** |
||||
1215 | * Prepends a SQL statement using WITH syntax. |
||||
1216 | * @param string|Query $query the SQL statement to be prepended using WITH |
||||
1217 | * @param string $alias query alias in WITH construction |
||||
1218 | * @param bool $recursive TRUE if using WITH RECURSIVE and FALSE if using WITH |
||||
1219 | * @return $this the query object itself |
||||
1220 | * @since 2.0.35 |
||||
1221 | */ |
||||
1222 | public function withQuery($query, $alias, $recursive = false) |
||||
1223 | { |
||||
1224 | $this->withQueries[] = ['query' => $query, 'alias' => $alias, 'recursive' => $recursive]; |
||||
1225 | return $this; |
||||
1226 | } |
||||
1227 | |||||
1228 | /** |
||||
1229 | * Sets the parameters to be bound to the query. |
||||
1230 | * @param array $params list of query parameter values indexed by parameter placeholders. |
||||
1231 | * For example, `[':name' => 'Dan', ':age' => 31]`. |
||||
1232 | * @return $this the query object itself |
||||
1233 | * @see addParams() |
||||
1234 | */ |
||||
1235 | public function params($params) |
||||
1236 | { |
||||
1237 | $this->params = $params; |
||||
1238 | return $this; |
||||
1239 | } |
||||
1240 | |||||
1241 | /** |
||||
1242 | * Adds additional parameters to be bound to the query. |
||||
1243 | * @param array $params list of query parameter values indexed by parameter placeholders. |
||||
1244 | * For example, `[':name' => 'Dan', ':age' => 31]`. |
||||
1245 | * @return $this the query object itself |
||||
1246 | * @see params() |
||||
1247 | */ |
||||
1248 | 13 | public function addParams($params) |
|||
1249 | { |
||||
1250 | 13 | if (!empty($params)) { |
|||
1251 | if (empty($this->params)) { |
||||
1252 | $this->params = $params; |
||||
1253 | } else { |
||||
1254 | foreach ($params as $name => $value) { |
||||
1255 | if (is_int($name)) { |
||||
1256 | $this->params[] = $value; |
||||
1257 | } else { |
||||
1258 | $this->params[$name] = $value; |
||||
1259 | } |
||||
1260 | } |
||||
1261 | } |
||||
1262 | } |
||||
1263 | |||||
1264 | 13 | return $this; |
|||
1265 | } |
||||
1266 | |||||
1267 | /** |
||||
1268 | * Enables query cache for this Query. |
||||
1269 | * @param int|true $duration the number of seconds that query results can remain valid in cache. |
||||
1270 | * Use 0 to indicate that the cached data will never expire. |
||||
1271 | * Use a negative number to indicate that query cache should not be used. |
||||
1272 | * Use boolean `true` to indicate that [[Connection::queryCacheDuration]] should be used. |
||||
1273 | * Defaults to `true`. |
||||
1274 | * @param \yii\caching\Dependency|null $dependency the cache dependency associated with the cached result. |
||||
1275 | * @return $this the Query object itself |
||||
1276 | * @since 2.0.14 |
||||
1277 | */ |
||||
1278 | public function cache($duration = true, $dependency = null) |
||||
1279 | { |
||||
1280 | $this->queryCacheDuration = $duration; |
||||
1281 | $this->queryCacheDependency = $dependency; |
||||
1282 | return $this; |
||||
1283 | } |
||||
1284 | |||||
1285 | /** |
||||
1286 | * Disables query cache for this Query. |
||||
1287 | * @return $this the Query object itself |
||||
1288 | * @since 2.0.14 |
||||
1289 | */ |
||||
1290 | 4 | public function noCache() |
|||
1291 | { |
||||
1292 | 4 | $this->queryCacheDuration = -1; |
|||
1293 | 4 | return $this; |
|||
1294 | } |
||||
1295 | |||||
1296 | /** |
||||
1297 | * Sets $command cache, if this query has enabled caching. |
||||
1298 | * |
||||
1299 | * @param Command $command |
||||
1300 | * @return Command |
||||
1301 | * @since 2.0.14 |
||||
1302 | */ |
||||
1303 | 31 | protected function setCommandCache($command) |
|||
1304 | { |
||||
1305 | 31 | if ($this->queryCacheDuration !== null || $this->queryCacheDependency !== null) { |
|||
1306 | 4 | $duration = $this->queryCacheDuration === true ? null : $this->queryCacheDuration; |
|||
1307 | 4 | $command->cache($duration, $this->queryCacheDependency); |
|||
0 ignored issues
–
show
It seems like
$duration can also be of type false ; however, parameter $duration of yii\db\Command::cache() does only seem to accept integer|null , maybe add an additional type check?
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||
1308 | } |
||||
1309 | |||||
1310 | 31 | return $command; |
|||
1311 | } |
||||
1312 | |||||
1313 | /** |
||||
1314 | * Creates a new Query object and copies its property values from an existing one. |
||||
1315 | * The properties being copies are the ones to be used by query builders. |
||||
1316 | * @param Query $from the source query object |
||||
1317 | * @return Query the new Query object |
||||
1318 | */ |
||||
1319 | 12 | public static function create($from) |
|||
1320 | { |
||||
1321 | 12 | return new self([ |
|||
1322 | 12 | 'where' => $from->where, |
|||
1323 | 12 | 'limit' => $from->limit, |
|||
1324 | 12 | 'offset' => $from->offset, |
|||
1325 | 12 | 'orderBy' => $from->orderBy, |
|||
1326 | 12 | 'indexBy' => $from->indexBy, |
|||
1327 | 12 | 'select' => $from->select, |
|||
1328 | 12 | 'selectOption' => $from->selectOption, |
|||
1329 | 12 | 'distinct' => $from->distinct, |
|||
1330 | 12 | 'from' => $from->from, |
|||
1331 | 12 | 'groupBy' => $from->groupBy, |
|||
1332 | 12 | 'join' => $from->join, |
|||
1333 | 12 | 'having' => $from->having, |
|||
1334 | 12 | 'union' => $from->union, |
|||
1335 | 12 | 'params' => $from->params, |
|||
1336 | 12 | 'withQueries' => $from->withQueries, |
|||
1337 | 12 | ]); |
|||
1338 | } |
||||
1339 | |||||
1340 | /** |
||||
1341 | * Returns the SQL representation of Query |
||||
1342 | * @return string |
||||
1343 | */ |
||||
1344 | public function __toString() |
||||
1345 | { |
||||
1346 | return serialize($this); |
||||
1347 | } |
||||
1348 | } |
||||
1349 |
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.