Passed
Pull Request — master (#20056)
by
unknown
11:51
created

QueryBuilder::addColumn()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 3
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
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\base\InvalidArgumentException;
11
use yii\base\NotSupportedException;
12
use yii\db\conditions\ConditionInterface;
13
use yii\db\conditions\HashCondition;
14
use yii\helpers\StringHelper;
15
16
/**
17
 * QueryBuilder builds a SELECT SQL statement based on the specification given as a [[Query]] object.
18
 *
19
 * SQL statements are created from [[Query]] objects using the [[build()]]-method.
20
 *
21
 * QueryBuilder is also used by [[Command]] to build SQL statements such as INSERT, UPDATE, DELETE, CREATE TABLE.
22
 *
23
 * For more details and usage information on QueryBuilder, see the [guide article on query builders](guide:db-query-builder).
24
 *
25
 * @property-write string[] $conditionClasses Map of condition aliases to condition classes. For example:
26
 * ```php ['LIKE' => yii\db\condition\LikeCondition::class] ``` .
27
 * @property-write string[] $expressionBuilders Array of builders that should be merged with the pre-defined
28
 * ones in [[expressionBuilders]] property.
29
 *
30
 * @author Qiang Xue <[email protected]>
31
 * @since 2.0
32
 */
33
class QueryBuilder extends \yii\base\BaseObject
34
{
35
    /**
36
     * The prefix for automatically generated query binding parameters.
37
     */
38
    const PARAM_PREFIX = ':qp';
39
40
    /**
41
     * @var Connection the database connection.
42
     */
43
    public $db;
44
    /**
45
     * @var string the separator between different fragments of a SQL statement.
46
     * Defaults to an empty space. This is mainly used by [[build()]] when generating a SQL statement.
47
     */
48
    public $separator = ' ';
49
    /**
50
     * @var array the abstract column types mapped to physical column types.
51
     * This is mainly used to support creating/modifying tables using DB-independent data type specifications.
52
     * Child classes should override this property to declare supported type mappings.
53
     */
54
    public $typeMap = [];
55
56
    /**
57
     * @var array map of query condition to builder methods.
58
     * These methods are used by [[buildCondition]] to build SQL conditions from array syntax.
59
     * @deprecated since 2.0.14. Is not used, will be dropped in 2.1.0.
60
     */
61
    protected $conditionBuilders = [];
62
    /**
63
     * @var array map of condition aliases to condition classes. For example:
64
     *
65
     * ```php
66
     * return [
67
     *     'LIKE' => yii\db\condition\LikeCondition::class,
68
     * ];
69
     * ```
70
     *
71
     * This property is used by [[createConditionFromArray]] method.
72
     * See default condition classes list in [[defaultConditionClasses()]] method.
73
     *
74
     * In case you want to add custom conditions support, use the [[setConditionClasses()]] method.
75
     *
76
     * @see setConditionClasses()
77
     * @see defaultConditionClasses()
78
     * @since 2.0.14
79
     */
80
    protected $conditionClasses = [];
81
    /**
82
     * @var string[]|ExpressionBuilderInterface[] maps expression class to expression builder class.
83
     * For example:
84
     *
85
     * ```php
86
     * [
87
     *    yii\db\Expression::class => yii\db\ExpressionBuilder::class
88
     * ]
89
     * ```
90
     * This property is mainly used by [[buildExpression()]] to build SQL expressions form expression objects.
91
     * See default values in [[defaultExpressionBuilders()]] method.
92
     *
93
     *
94
     * To override existing builders or add custom, use [[setExpressionBuilder()]] method. New items will be added
95
     * to the end of this array.
96
     *
97
     * To find a builder, [[buildExpression()]] will check the expression class for its exact presence in this map.
98
     * In case it is NOT present, the array will be iterated in reverse direction, checking whether the expression
99
     * extends the class, defined in this map.
100
     *
101
     * @see setExpressionBuilders()
102
     * @see defaultExpressionBuilders()
103
     * @since 2.0.14
104
     */
105
    protected $expressionBuilders = [];
106
107
108
    /**
109
     * Constructor.
110
     * @param Connection $connection the database connection.
111
     * @param array $config name-value pairs that will be used to initialize the object properties
112
     */
113 1751
    public function __construct($connection, $config = [])
114
    {
115 1751
        $this->db = $connection;
116 1751
        parent::__construct($config);
117 1751
    }
118
119
    /**
120
     * {@inheritdoc}
121
     */
122 1751
    public function init()
123
    {
124 1751
        parent::init();
125
126 1751
        $this->expressionBuilders = array_merge($this->defaultExpressionBuilders(), $this->expressionBuilders);
0 ignored issues
show
introduced by
The property expressionBuilders is declared write-only in yii\db\QueryBuilder.
Loading history...
127 1751
        $this->conditionClasses = array_merge($this->defaultConditionClasses(), $this->conditionClasses);
0 ignored issues
show
introduced by
The property conditionClasses is declared write-only in yii\db\QueryBuilder.
Loading history...
128 1751
    }
129
130
    /**
131
     * Contains array of default condition classes. Extend this method, if you want to change
132
     * default condition classes for the query builder. See [[conditionClasses]] docs for details.
133
     *
134
     * @return array
135
     * @see conditionClasses
136
     * @since 2.0.14
137
     */
138 1751
    protected function defaultConditionClasses()
139
    {
140
        return [
141 1751
            'NOT' => 'yii\db\conditions\NotCondition',
142
            'AND' => 'yii\db\conditions\AndCondition',
143
            'OR' => 'yii\db\conditions\OrCondition',
144
            'BETWEEN' => 'yii\db\conditions\BetweenCondition',
145
            'NOT BETWEEN' => 'yii\db\conditions\BetweenCondition',
146
            'IN' => 'yii\db\conditions\InCondition',
147
            'NOT IN' => 'yii\db\conditions\InCondition',
148
            'LIKE' => 'yii\db\conditions\LikeCondition',
149
            'NOT LIKE' => 'yii\db\conditions\LikeCondition',
150
            'OR LIKE' => 'yii\db\conditions\LikeCondition',
151
            'OR NOT LIKE' => 'yii\db\conditions\LikeCondition',
152
            'EXISTS' => 'yii\db\conditions\ExistsCondition',
153
            'NOT EXISTS' => 'yii\db\conditions\ExistsCondition',
154
        ];
155
    }
156
157
    /**
158
     * Contains array of default expression builders. Extend this method and override it, if you want to change
159
     * default expression builders for this query builder. See [[expressionBuilders]] docs for details.
160
     *
161
     * @return array
162
     * @see expressionBuilders
163
     * @since 2.0.14
164
     */
165 1751
    protected function defaultExpressionBuilders()
166
    {
167
        return [
168 1751
            'yii\db\Query' => 'yii\db\QueryExpressionBuilder',
169
            'yii\db\PdoValue' => 'yii\db\PdoValueBuilder',
170
            'yii\db\Expression' => 'yii\db\ExpressionBuilder',
171
            'yii\db\conditions\ConjunctionCondition' => 'yii\db\conditions\ConjunctionConditionBuilder',
172
            'yii\db\conditions\NotCondition' => 'yii\db\conditions\NotConditionBuilder',
173
            'yii\db\conditions\AndCondition' => 'yii\db\conditions\ConjunctionConditionBuilder',
174
            'yii\db\conditions\OrCondition' => 'yii\db\conditions\ConjunctionConditionBuilder',
175
            'yii\db\conditions\BetweenCondition' => 'yii\db\conditions\BetweenConditionBuilder',
176
            'yii\db\conditions\InCondition' => 'yii\db\conditions\InConditionBuilder',
177
            'yii\db\conditions\LikeCondition' => 'yii\db\conditions\LikeConditionBuilder',
178
            'yii\db\conditions\ExistsCondition' => 'yii\db\conditions\ExistsConditionBuilder',
179
            'yii\db\conditions\SimpleCondition' => 'yii\db\conditions\SimpleConditionBuilder',
180
            'yii\db\conditions\HashCondition' => 'yii\db\conditions\HashConditionBuilder',
181
            'yii\db\conditions\BetweenColumnsCondition' => 'yii\db\conditions\BetweenColumnsConditionBuilder',
182
        ];
183
    }
184
185
    /**
186
     * Setter for [[expressionBuilders]] property.
187
     *
188
     * @param string[] $builders array of builders that should be merged with the pre-defined ones
189
     * in [[expressionBuilders]] property.
190
     * @since 2.0.14
191
     * @see expressionBuilders
192
     */
193 4
    public function setExpressionBuilders($builders)
194
    {
195 4
        $this->expressionBuilders = array_merge($this->expressionBuilders, $builders);
0 ignored issues
show
introduced by
The property expressionBuilders is declared write-only in yii\db\QueryBuilder.
Loading history...
196 4
    }
197
198
    /**
199
     * Setter for [[conditionClasses]] property.
200
     *
201
     * @param string[] $classes map of condition aliases to condition classes. For example:
202
     *
203
     * ```php
204
     * ['LIKE' => yii\db\condition\LikeCondition::class]
205
     * ```
206
     *
207
     * @since 2.0.14.2
208
     * @see conditionClasses
209
     */
210
    public function setConditionClasses($classes)
211
    {
212
        $this->conditionClasses = array_merge($this->conditionClasses, $classes);
0 ignored issues
show
introduced by
The property conditionClasses is declared write-only in yii\db\QueryBuilder.
Loading history...
213
    }
214
215
    /**
216
     * Generates a SELECT SQL statement from a [[Query]] object.
217
     *
218
     * @param Query $query the [[Query]] object from which the SQL statement will be generated.
219
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will
220
     * be included in the result with the additional parameters generated during the query building process.
221
     * @return array the generated SQL statement (the first array element) and the corresponding
222
     * parameters to be bound to the SQL statement (the second array element). The parameters returned
223
     * include those provided in `$params`.
224
     */
225 984
    public function build($query, $params = [])
226
    {
227 984
        $query = $query->prepare($this);
228
229 984
        $params = empty($params) ? $query->params : array_merge($params, $query->params);
0 ignored issues
show
Bug introduced by
It seems like $query->params can also be of type null; however, parameter $arrays of array_merge() does only seem to accept array, 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 ignore-type  annotation

229
        $params = empty($params) ? $query->params : array_merge($params, /** @scrutinizer ignore-type */ $query->params);
Loading history...
230
231
        $clauses = [
232 984
            $this->buildSelect($query->select, $params, $query->distinct, $query->selectOption),
233 984
            $this->buildFrom($query->from, $params),
234 984
            $this->buildJoin($query->join, $params),
235 984
            $this->buildWhere($query->where, $params),
0 ignored issues
show
Bug introduced by
It seems like $query->where can also be of type yii\db\ExpressionInterface; however, parameter $condition of yii\db\QueryBuilder::buildWhere() does only seem to accept array|string, 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 ignore-type  annotation

235
            $this->buildWhere(/** @scrutinizer ignore-type */ $query->where, $params),
Loading history...
236 984
            $this->buildGroupBy($query->groupBy),
237 984
            $this->buildHaving($query->having, $params),
0 ignored issues
show
Bug introduced by
It seems like $query->having can also be of type yii\db\ExpressionInterface; however, parameter $condition of yii\db\QueryBuilder::buildHaving() does only seem to accept array|string, 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 ignore-type  annotation

237
            $this->buildHaving(/** @scrutinizer ignore-type */ $query->having, $params),
Loading history...
238
        ];
239
240 984
        $sql = implode($this->separator, array_filter($clauses));
241 984
        $sql = $this->buildOrderByAndLimit($sql, $query->orderBy, $query->limit, $query->offset);
0 ignored issues
show
Bug introduced by
It seems like $query->limit can also be of type yii\db\ExpressionInterface; however, parameter $limit of yii\db\QueryBuilder::buildOrderByAndLimit() does only seem to accept integer, 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 ignore-type  annotation

241
        $sql = $this->buildOrderByAndLimit($sql, $query->orderBy, /** @scrutinizer ignore-type */ $query->limit, $query->offset);
Loading history...
Bug introduced by
It seems like $query->offset can also be of type yii\db\ExpressionInterface; however, parameter $offset of yii\db\QueryBuilder::buildOrderByAndLimit() does only seem to accept integer, 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 ignore-type  annotation

241
        $sql = $this->buildOrderByAndLimit($sql, $query->orderBy, $query->limit, /** @scrutinizer ignore-type */ $query->offset);
Loading history...
242
243 984
        if (!empty($query->orderBy)) {
244 139
            foreach ($query->orderBy as $expression) {
245 139
                if ($expression instanceof ExpressionInterface) {
246 2
                    $this->buildExpression($expression, $params);
247
                }
248
            }
249
        }
250 984
        if (!empty($query->groupBy)) {
251 20
            foreach ($query->groupBy as $expression) {
252 20
                if ($expression instanceof ExpressionInterface) {
253 2
                    $this->buildExpression($expression, $params);
254
                }
255
            }
256
        }
257
258 984
        $union = $this->buildUnion($query->union, $params);
259 984
        if ($union !== '') {
260 10
            $sql = "($sql){$this->separator}$union";
261
        }
262
263 984
        $with = $this->buildWithQueries($query->withQueries, $params);
264 984
        if ($with !== '') {
265 4
            $sql = "$with{$this->separator}$sql";
266
        }
267
268 984
        return [$sql, $params];
269
    }
270
271
    /**
272
     * Builds given $expression
273
     *
274
     * @param ExpressionInterface $expression the expression to be built
275
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will
276
     * be included in the result with the additional parameters generated during the expression building process.
277
     * @return string the SQL statement that will not be neither quoted nor encoded before passing to DBMS
278
     * @throws InvalidArgumentException when $expression building is not supported by this QueryBuilder.
279
     * @see ExpressionBuilderInterface
280
     * @see expressionBuilders
281
     * @since 2.0.14
282
     * @see ExpressionInterface
283
     */
284 1301
    public function buildExpression(ExpressionInterface $expression, &$params = [])
285
    {
286 1301
        $builder = $this->getExpressionBuilder($expression);
287
288 1301
        return $builder->build($expression, $params);
289
    }
290
291
    /**
292
     * Gets object of [[ExpressionBuilderInterface]] that is suitable for $expression.
293
     * Uses [[expressionBuilders]] array to find a suitable builder class.
294
     *
295
     * @param ExpressionInterface $expression
296
     * @return ExpressionBuilderInterface
297
     * @throws InvalidArgumentException when $expression building is not supported by this QueryBuilder.
298
     * @since 2.0.14
299
     * @see expressionBuilders
300
     */
301 1305
    public function getExpressionBuilder(ExpressionInterface $expression)
302
    {
303 1305
        $className = get_class($expression);
304
305 1305
        if (!isset($this->expressionBuilders[$className])) {
0 ignored issues
show
introduced by
The property expressionBuilders is declared write-only in yii\db\QueryBuilder.
Loading history...
306
            foreach (array_reverse($this->expressionBuilders) as $expressionClass => $builderClass) {
307
                if (is_subclass_of($expression, $expressionClass)) {
308
                    $this->expressionBuilders[$className] = $builderClass;
309
                    break;
310
                }
311
            }
312
313
            if (!isset($this->expressionBuilders[$className])) {
314
                throw new InvalidArgumentException('Expression of class ' . $className . ' can not be built in ' . get_class($this));
315
            }
316
        }
317
318 1305
        if ($this->expressionBuilders[$className] === __CLASS__) {
319
            return $this;
320
        }
321
322 1305
        if (!is_object($this->expressionBuilders[$className])) {
0 ignored issues
show
introduced by
The condition is_object($this->expressionBuilders[$className]) is always false.
Loading history...
323 1264
            $this->expressionBuilders[$className] = new $this->expressionBuilders[$className]($this);
324
        }
325
326 1305
        return $this->expressionBuilders[$className];
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->expressionBuilders[$className] returns the type string which is incompatible with the documented return type yii\db\ExpressionBuilderInterface.
Loading history...
327
    }
328
329
    /**
330
     * Creates an INSERT SQL statement.
331
     * For example,
332
     * ```php
333
     * $sql = $queryBuilder->insert('user', [
334
     *     'name' => 'Sam',
335
     *     'age' => 30,
336
     * ], $params);
337
     * ```
338
     * The method will properly escape the table and column names.
339
     *
340
     * @param string $table the table that new rows will be inserted into.
341
     * @param array|Query $columns the column data (name => value) to be inserted into the table or instance
342
     * of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement.
343
     * Passing of [[yii\db\Query|Query]] is available since version 2.0.11.
344
     * @param array $params the binding parameters that will be generated by this method.
345
     * They should be bound to the DB command later.
346
     * @return string the INSERT SQL
347
     */
348 591
    public function insert($table, $columns, &$params)
349
    {
350 591
        list($names, $placeholders, $values, $params) = $this->prepareInsertValues($table, $columns, $params);
351 582
        return 'INSERT INTO ' . $this->db->quoteTableName($table)
352 582
            . (!empty($names) ? ' (' . implode(', ', $names) . ')' : '')
353 582
            . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : $values);
354
    }
355
356
    /**
357
     * Prepares a `VALUES` part for an `INSERT` SQL statement.
358
     *
359
     * @param string $table the table that new rows will be inserted into.
360
     * @param array|Query $columns the column data (name => value) to be inserted into the table or instance
361
     * of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement.
362
     * @param array $params the binding parameters that will be generated by this method.
363
     * They should be bound to the DB command later.
364
     * @return array array of column names, placeholders, values and params.
365
     * @since 2.0.14
366
     */
367 606
    protected function prepareInsertValues($table, $columns, $params = [])
368
    {
369 606
        $schema = $this->db->getSchema();
370 606
        $tableSchema = $schema->getTableSchema($table);
371 606
        $columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
372 606
        $names = [];
373 606
        $placeholders = [];
374 606
        $values = ' DEFAULT VALUES';
375 606
        if ($columns instanceof Query) {
376 42
            list($names, $values, $params) = $this->prepareInsertSelectSubQuery($columns, $schema, $params);
377
        } else {
378 570
            foreach ($columns as $name => $value) {
379 565
                $names[] = $schema->quoteColumnName($name);
380 565
                $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
381
382 565
                if ($value instanceof ExpressionInterface) {
383 150
                    $placeholders[] = $this->buildExpression($value, $params);
384 545
                } elseif ($value instanceof \yii\db\Query) {
385
                    list($sql, $params) = $this->build($value, $params);
386
                    $placeholders[] = "($sql)";
387
                } else {
388 545
                    $placeholders[] = $this->bindParam($value, $params);
389
                }
390
            }
391
        }
392 597
        return [$names, $placeholders, $values, $params];
393
    }
394
395
    /**
396
     * Prepare select-subquery and field names for INSERT INTO ... SELECT SQL statement.
397
     *
398
     * @param Query $columns Object, which represents select query.
399
     * @param \yii\db\Schema $schema Schema object to quote column name.
400
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will
401
     * be included in the result with the additional parameters generated during the query building process.
402
     * @return array array of column names, values and params.
403
     * @throws InvalidArgumentException if query's select does not contain named parameters only.
404
     * @since 2.0.11
405
     */
406 42
    protected function prepareInsertSelectSubQuery($columns, $schema, $params = [])
407
    {
408 42
        if (!is_array($columns->select) || empty($columns->select) || in_array('*', $columns->select)) {
409 9
            throw new InvalidArgumentException('Expected select query object with enumerated (named) parameters');
410
        }
411
412 33
        list($values, $params) = $this->build($columns, $params);
413 33
        $names = [];
414 33
        $values = ' ' . $values;
415 33
        foreach ($columns->select as $title => $field) {
416 33
            if (is_string($title)) {
417 33
                $names[] = $schema->quoteColumnName($title);
418
            } elseif (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $field, $matches)) {
419
                $names[] = $schema->quoteColumnName($matches[2]);
420
            } else {
421
                $names[] = $schema->quoteColumnName($field);
422
            }
423
        }
424
425 33
        return [$names, $values, $params];
426
    }
427
428
    /**
429
     * Generates a batch INSERT SQL statement.
430
     *
431
     * For example,
432
     *
433
     * ```php
434
     * $sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
435
     *     ['Tom', 30],
436
     *     ['Jane', 20],
437
     *     ['Linda', 25],
438
     * ]);
439
     * ```
440
     *
441
     * Note that the values in each row must match the corresponding column names.
442
     *
443
     * The method will properly escape the column names, and quote the values to be inserted.
444
     *
445
     * @param string $table the table that new rows will be inserted into.
446
     * @param array $columns the column names
447
     * @param array|\Generator $rows the rows to be batch inserted into the table
448
     * @param array $params the binding parameters. This parameter exists since 2.0.14
449
     * @return string the batch INSERT SQL statement
450
     */
451 29
    public function batchInsert($table, $columns, $rows, &$params = [])
452
    {
453 29
        if (empty($rows)) {
454 2
            return '';
455
        }
456
457 28
        $schema = $this->db->getSchema();
458 28
        if (($tableSchema = $schema->getTableSchema($table)) !== null) {
459 22
            $columnSchemas = $tableSchema->columns;
460
        } else {
461 6
            $columnSchemas = [];
462
        }
463
464 28
        $values = [];
465 28
        foreach ($rows as $row) {
466 24
            $vs = [];
467 24
            foreach ($row as $i => $value) {
468 24
                if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
469 15
                    $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
470
                }
471 24
                if (is_string($value)) {
472 16
                    $value = $schema->quoteValue($value);
473 15
                } elseif (is_float($value)) {
474
                    // ensure type cast always has . as decimal separator in all locales
475 2
                    $value = StringHelper::floatToString($value);
476 15
                } elseif ($value === false) {
477 6
                    $value = 0;
478 15
                } elseif ($value === null) {
479 8
                    $value = 'NULL';
480 9
                } elseif ($value instanceof ExpressionInterface) {
481 6
                    $value = $this->buildExpression($value, $params);
482
                }
483 24
                $vs[] = $value;
484
            }
485 24
            $values[] = '(' . implode(', ', $vs) . ')';
486
        }
487 28
        if (empty($values)) {
488 4
            return '';
489
        }
490
491 24
        foreach ($columns as $i => $name) {
492 22
            $columns[$i] = $schema->quoteColumnName($name);
493
        }
494
495 24
        return 'INSERT INTO ' . $schema->quoteTableName($table)
496 24
            . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
497
    }
498
499
    /**
500
     * Creates an SQL statement to insert rows into a database table if
501
     * they do not already exist (matching unique constraints),
502
     * or update them if they do.
503
     *
504
     * For example,
505
     *
506
     * ```php
507
     * $sql = $queryBuilder->upsert('pages', [
508
     *     'name' => 'Front page',
509
     *     'url' => 'https://example.com/', // url is unique
510
     *     'visits' => 0,
511
     * ], [
512
     *     'visits' => new \yii\db\Expression('visits + 1'),
513
     * ], $params);
514
     * ```
515
     *
516
     * The method will properly escape the table and column names.
517
     *
518
     * @param string $table the table that new rows will be inserted into/updated in.
519
     * @param array|Query $insertColumns the column data (name => value) to be inserted into the table or instance
520
     * of [[Query]] to perform `INSERT INTO ... SELECT` SQL statement.
521
     * @param array|bool $updateColumns the column data (name => value) to be updated if they already exist.
522
     * If `true` is passed, the column data will be updated to match the insert column data.
523
     * If `false` is passed, no update will be performed if the column data already exists.
524
     * @param array $params the binding parameters that will be generated by this method.
525
     * They should be bound to the DB command later.
526
     * @return string the resulting SQL.
527
     * @throws NotSupportedException if this is not supported by the underlying DBMS.
528
     * @since 2.0.14
529
     */
530
    public function upsert($table, $insertColumns, $updateColumns, &$params)
531
    {
532
        throw new NotSupportedException($this->db->getDriverName() . ' does not support upsert statements.');
533
    }
534
535
    /**
536
     * @param string $table
537
     * @param array|Query $insertColumns
538
     * @param array|bool $updateColumns
539
     * @param Constraint[] $constraints this parameter recieves a matched constraint list.
540
     * The constraints will be unique by their column names.
541
     * @return array
542
     * @since 2.0.14
543
     */
544 107
    protected function prepareUpsertColumns($table, $insertColumns, $updateColumns, &$constraints = [])
545
    {
546 107
        if ($insertColumns instanceof Query) {
547 24
            list($insertNames) = $this->prepareInsertSelectSubQuery($insertColumns, $this->db->getSchema());
548
        } else {
549 83
            $insertNames = array_map([$this->db, 'quoteColumnName'], array_keys($insertColumns));
550
        }
551 107
        $uniqueNames = $this->getTableUniqueColumnNames($table, $insertNames, $constraints);
552 107
        $uniqueNames = array_map([$this->db, 'quoteColumnName'], $uniqueNames);
553 107
        if ($updateColumns !== true) {
554 36
            return [$uniqueNames, $insertNames, null];
555
        }
556
557 71
        return [$uniqueNames, $insertNames, array_diff($insertNames, $uniqueNames)];
558
    }
559
560
    /**
561
     * Returns all column names belonging to constraints enforcing uniqueness (`PRIMARY KEY`, `UNIQUE INDEX`, etc.)
562
     * for the named table removing constraints which did not cover the specified column list.
563
     * The column list will be unique by column names.
564
     *
565
     * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
566
     * @param string[] $columns source column list.
567
     * @param Constraint[] $constraints this parameter optionally recieves a matched constraint list.
568
     * The constraints will be unique by their column names.
569
     * @return string[] column list.
570
     */
571 107
    private function getTableUniqueColumnNames($name, $columns, &$constraints = [])
572
    {
573 107
        $schema = $this->db->getSchema();
574 107
        if (!$schema instanceof ConstraintFinderInterface) {
575
            return [];
576
        }
577
578 107
        $constraints = [];
579 107
        $primaryKey = $schema->getTablePrimaryKey($name);
0 ignored issues
show
Bug introduced by
The method getTablePrimaryKey() does not exist on yii\db\Schema. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

579
        /** @scrutinizer ignore-call */ 
580
        $primaryKey = $schema->getTablePrimaryKey($name);
Loading history...
580 107
        if ($primaryKey !== null) {
581 107
            $constraints[] = $primaryKey;
582
        }
583 107
        foreach ($schema->getTableIndexes($name) as $constraint) {
0 ignored issues
show
Bug introduced by
The method getTableIndexes() does not exist on yii\db\Schema. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

583
        foreach ($schema->/** @scrutinizer ignore-call */ getTableIndexes($name) as $constraint) {
Loading history...
584 106
            if ($constraint->isUnique) {
585 106
                $constraints[] = $constraint;
586
            }
587
        }
588 107
        $constraints = array_merge($constraints, $schema->getTableUniques($name));
0 ignored issues
show
Bug introduced by
The method getTableUniques() does not exist on yii\db\Schema. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

588
        $constraints = array_merge($constraints, $schema->/** @scrutinizer ignore-call */ getTableUniques($name));
Loading history...
589
        // Remove duplicates
590
        $constraints = array_combine(array_map(function (Constraint $constraint) {
591 107
            $columns = $constraint->columnNames;
592 107
            sort($columns, SORT_STRING);
0 ignored issues
show
Bug introduced by
It seems like $columns can also be of type null; however, parameter $array of sort() does only seem to accept array, 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 ignore-type  annotation

592
            sort(/** @scrutinizer ignore-type */ $columns, SORT_STRING);
Loading history...
593 107
            return json_encode($columns);
594 107
        }, $constraints), $constraints);
595 107
        $columnNames = [];
596
        // Remove all constraints which do not cover the specified column list
597
        $constraints = array_values(array_filter($constraints, function (Constraint $constraint) use ($schema, $columns, &$columnNames) {
598 107
            $constraintColumnNames = array_map([$schema, 'quoteColumnName'], $constraint->columnNames);
0 ignored issues
show
Bug introduced by
It seems like $constraint->columnNames can also be of type null; however, parameter $array of array_map() does only seem to accept array, 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 ignore-type  annotation

598
            $constraintColumnNames = array_map([$schema, 'quoteColumnName'], /** @scrutinizer ignore-type */ $constraint->columnNames);
Loading history...
599 107
            $result = !array_diff($constraintColumnNames, $columns);
600 107
            if ($result) {
601 98
                $columnNames = array_merge($columnNames, $constraintColumnNames);
602
            }
603 107
            return $result;
604 107
        }));
605 107
        return array_unique($columnNames);
606
    }
607
608
    /**
609
     * Creates an UPDATE SQL statement.
610
     *
611
     * For example,
612
     *
613
     * ```php
614
     * $params = [];
615
     * $sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params);
616
     * ```
617
     *
618
     * The method will properly escape the table and column names.
619
     *
620
     * @param string $table the table to be updated.
621
     * @param array $columns the column data (name => value) to be updated.
622
     * @param array|string $condition the condition that will be put in the WHERE part. Please
623
     * refer to [[Query::where()]] on how to specify condition.
624
     * @param array $params the binding parameters that will be modified by this method
625
     * so that they can be bound to the DB command later.
626
     * @return string the UPDATE SQL
627
     */
628 118
    public function update($table, $columns, $condition, &$params)
629
    {
630 118
        list($lines, $params) = $this->prepareUpdateSets($table, $columns, $params);
631 118
        $sql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $lines);
632 118
        $where = $this->buildWhere($condition, $params);
633 118
        return $where === '' ? $sql : $sql . ' ' . $where;
634
    }
635
636
    /**
637
     * Prepares a `SET` parts for an `UPDATE` SQL statement.
638
     * @param string $table the table to be updated.
639
     * @param array $columns the column data (name => value) to be updated.
640
     * @param array $params the binding parameters that will be modified by this method
641
     * so that they can be bound to the DB command later.
642
     * @return array an array `SET` parts for an `UPDATE` SQL statement (the first array element) and params (the second array element).
643
     * @since 2.0.14
644
     */
645 187
    protected function prepareUpdateSets($table, $columns, $params = [])
646
    {
647 187
        $tableSchema = $this->db->getTableSchema($table);
648 187
        $columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
649 187
        $sets = [];
650 187
        foreach ($columns as $name => $value) {
651
652 187
            $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
653 187
            if ($value instanceof ExpressionInterface) {
654 104
                $placeholder = $this->buildExpression($value, $params);
655
            } else {
656 104
                $placeholder = $this->bindParam($value, $params);
657
            }
658
659 187
            $sets[] = $this->db->quoteColumnName($name) . '=' . $placeholder;
660
        }
661 187
        return [$sets, $params];
662
    }
663
664
    /**
665
     * Creates a DELETE SQL statement.
666
     *
667
     * For example,
668
     *
669
     * ```php
670
     * $sql = $queryBuilder->delete('user', 'status = 0');
671
     * ```
672
     *
673
     * The method will properly escape the table and column names.
674
     *
675
     * @param string $table the table where the data will be deleted from.
676
     * @param array|string $condition the condition that will be put in the WHERE part. Please
677
     * refer to [[Query::where()]] on how to specify condition.
678
     * @param array $params the binding parameters that will be modified by this method
679
     * so that they can be bound to the DB command later.
680
     * @return string the DELETE SQL
681
     */
682 389
    public function delete($table, $condition, &$params)
683
    {
684 389
        $sql = 'DELETE FROM ' . $this->db->quoteTableName($table);
685 389
        $where = $this->buildWhere($condition, $params);
686
687 389
        return $where === '' ? $sql : $sql . ' ' . $where;
688
    }
689
690
    /**
691
     * Builds a SQL statement for creating a new DB table.
692
     *
693
     * The columns in the new table should be specified as name-definition pairs (e.g. 'name' => 'string'),
694
     * where name stands for a column name which will be properly quoted by the method, and definition
695
     * stands for the column type which must contain an abstract DB type.
696
     * The [[getColumnType()]] method will be invoked to convert any abstract type into a physical one.
697
     *
698
     * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
699
     * inserted into the generated SQL.
700
     *
701
     * For example,
702
     *
703
     * ```php
704
     * $sql = $queryBuilder->createTable('user', [
705
     *  'id' => 'pk',
706
     *  'name' => 'string',
707
     *  'age' => 'integer',
708
     *  'column_name double precision null default null', # definition only example
709
     * ]);
710
     * ```
711
     *
712
     * @param string $table the name of the table to be created. The name will be properly quoted by the method.
713
     * @param array $columns the columns (name => definition) in the new table.
714
     * @param string|null $options additional SQL fragment that will be appended to the generated SQL.
715
     * @return string the SQL statement for creating a new DB table.
716
     */
717 175
    public function createTable($table, $columns, $options = null)
718
    {
719 175
        $cols = [];
720 175
        foreach ($columns as $name => $type) {
721 175
            if (is_string($name)) {
722 175
                $cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type);
723
            } else {
724 32
                $cols[] = "\t" . $type;
725
            }
726
        }
727 175
        $sql = 'CREATE TABLE ' . $this->db->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)";
728
729 175
        return $options === null ? $sql : $sql . ' ' . $options;
730
    }
731
732
    /**
733
     * Builds a SQL statement for renaming a DB table.
734
     * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
735
     * @param string $newName the new table name. The name will be properly quoted by the method.
736
     * @return string the SQL statement for renaming a DB table.
737
     */
738 2
    public function renameTable($oldName, $newName)
739
    {
740 2
        return 'RENAME TABLE ' . $this->db->quoteTableName($oldName) . ' TO ' . $this->db->quoteTableName($newName);
741
    }
742
743
    /**
744
     * Builds a SQL statement for dropping a DB table.
745
     * @param string $table the table to be dropped. The name will be properly quoted by the method.
746
     * @return string the SQL statement for dropping a DB table.
747
     */
748 55
    public function dropTable($table)
749
    {
750 55
        return 'DROP TABLE ' . $this->db->quoteTableName($table);
751
    }
752
753
    /**
754
     * Builds a SQL statement for adding a primary key constraint to an existing table.
755
     * @param string $name the name of the primary key constraint.
756
     * @param string $table the table that the primary key constraint will be added to.
757
     * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
758
     * @return string the SQL statement for adding a primary key constraint to an existing table.
759
     */
760 6
    public function addPrimaryKey($name, $table, $columns)
761
    {
762 6
        if (is_string($columns)) {
763 4
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
764
        }
765
766 6
        foreach ($columns as $i => $col) {
767 6
            $columns[$i] = $this->db->quoteColumnName($col);
768
        }
769
770 6
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
771 6
            . $this->db->quoteColumnName($name) . ' PRIMARY KEY ('
772 6
            . implode(', ', $columns) . ')';
773
    }
774
775
    /**
776
     * Builds a SQL statement for removing a primary key constraint to an existing table.
777
     * @param string $name the name of the primary key constraint to be removed.
778
     * @param string $table the table that the primary key constraint will be removed from.
779
     * @return string the SQL statement for removing a primary key constraint from an existing table.
780
     */
781 2
    public function dropPrimaryKey($name, $table)
782
    {
783 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
784 2
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
785
    }
786
787
    /**
788
     * Builds a SQL statement for truncating a DB table.
789
     * @param string $table the table to be truncated. The name will be properly quoted by the method.
790
     * @return string the SQL statement for truncating a DB table.
791
     */
792 11
    public function truncateTable($table)
793
    {
794 11
        return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table);
795
    }
796
797
    /**
798
     * Builds a SQL statement for adding a new DB column.
799
     * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
800
     * @param string $column the name of the new column. The name will be properly quoted by the method.
801
     * @param string $type the column type. The [[getColumnType()]] method will be invoked to convert abstract column type (if any)
802
     * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
803
     * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
804
     * @return string the SQL statement for adding a new column.
805
     */
806 7
    public function addColumn($table, $column, $type)
807
    {
808 7
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
809 7
            . ' ADD ' . $this->db->quoteColumnName($column) . ' '
810 7
            . $this->getColumnType($type);
811
    }
812
813
    /**
814
     * Builds a SQL statement for dropping a DB column.
815
     * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
816
     * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
817
     * @return string the SQL statement for dropping a DB column.
818
     */
819
    public function dropColumn($table, $column)
820
    {
821
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
822
            . ' DROP COLUMN ' . $this->db->quoteColumnName($column);
823
    }
824
825
    /**
826
     * Builds a SQL statement for renaming a column.
827
     * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
828
     * @param string $oldName the old name of the column. The name will be properly quoted by the method.
829
     * @param string $newName the new name of the column. The name will be properly quoted by the method.
830
     * @return string the SQL statement for renaming a DB column.
831
     */
832
    public function renameColumn($table, $oldName, $newName)
833
    {
834
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
835
            . ' RENAME COLUMN ' . $this->db->quoteColumnName($oldName)
836
            . ' TO ' . $this->db->quoteColumnName($newName);
837
    }
838
839
    /**
840
     * Builds a SQL statement for changing the definition of a column.
841
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
842
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
843
     * @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract
844
     * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
845
     * in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
846
     * will become 'varchar(255) not null'.
847
     * @return string the SQL statement for changing the definition of a column.
848
     */
849 1
    public function alterColumn($table, $column, $type)
850
    {
851 1
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
852 1
            . $this->db->quoteColumnName($column) . ' '
853 1
            . $this->db->quoteColumnName($column) . ' '
854 1
            . $this->getColumnType($type);
855
    }
856
857
    /**
858
     * Builds a SQL statement for adding a foreign key constraint to an existing table.
859
     * The method will properly quote the table and column names.
860
     * @param string $name the name of the foreign key constraint.
861
     * @param string $table the table that the foreign key constraint will be added to.
862
     * @param string|array $columns the name of the column to that the constraint will be added on.
863
     * If there are multiple columns, separate them with commas or use an array to represent them.
864
     * @param string $refTable the table that the foreign key references to.
865
     * @param string|array $refColumns the name of the column that the foreign key references to.
866
     * If there are multiple columns, separate them with commas or use an array to represent them.
867
     * @param string|null $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
868
     * @param string|null $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
869
     * @return string the SQL statement for adding a foreign key constraint to an existing table.
870
     */
871 8
    public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
872
    {
873 8
        $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
874 8
            . ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name)
875 8
            . ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
876 8
            . ' REFERENCES ' . $this->db->quoteTableName($refTable)
877 8
            . ' (' . $this->buildColumns($refColumns) . ')';
878 8
        if ($delete !== null) {
879 4
            $sql .= ' ON DELETE ' . $delete;
880
        }
881 8
        if ($update !== null) {
882 4
            $sql .= ' ON UPDATE ' . $update;
883
        }
884
885 8
        return $sql;
886
    }
887
888
    /**
889
     * Builds a SQL statement for dropping a foreign key constraint.
890
     * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
891
     * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
892
     * @return string the SQL statement for dropping a foreign key constraint.
893
     */
894 3
    public function dropForeignKey($name, $table)
895
    {
896 3
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
897 3
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
898
    }
899
900
    /**
901
     * Builds a SQL statement for creating a new index.
902
     * @param string $name the name of the index. The name will be properly quoted by the method.
903
     * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
904
     * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns,
905
     * separate them with commas or use an array to represent them. Each column name will be properly quoted
906
     * by the method, unless a parenthesis is found in the name.
907
     * @param bool $unique whether to add UNIQUE constraint on the created index.
908
     * @return string the SQL statement for creating a new index.
909
     */
910
    public function createIndex($name, $table, $columns, $unique = false)
911
    {
912
        return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
913
            . $this->db->quoteTableName($name) . ' ON '
914
            . $this->db->quoteTableName($table)
915
            . ' (' . $this->buildColumns($columns) . ')';
916
    }
917
918
    /**
919
     * Builds a SQL statement for dropping an index.
920
     * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
921
     * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
922
     * @return string the SQL statement for dropping an index.
923
     */
924 4
    public function dropIndex($name, $table)
925
    {
926 4
        return 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON ' . $this->db->quoteTableName($table);
927
    }
928
929
    /**
930
     * Creates a SQL command for adding an unique constraint to an existing table.
931
     * @param string $name the name of the unique constraint.
932
     * The name will be properly quoted by the method.
933
     * @param string $table the table that the unique constraint will be added to.
934
     * The name will be properly quoted by the method.
935
     * @param string|array $columns the name of the column to that the constraint will be added on.
936
     * If there are multiple columns, separate them with commas.
937
     * The name will be properly quoted by the method.
938
     * @return string the SQL statement for adding an unique constraint to an existing table.
939
     * @since 2.0.13
940
     */
941 6
    public function addUnique($name, $table, $columns)
942
    {
943 6
        if (is_string($columns)) {
944 4
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
945
        }
946 6
        foreach ($columns as $i => $col) {
947 6
            $columns[$i] = $this->db->quoteColumnName($col);
948
        }
949
950 6
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
951 6
            . $this->db->quoteColumnName($name) . ' UNIQUE ('
952 6
            . implode(', ', $columns) . ')';
953
    }
954
955
    /**
956
     * Creates a SQL command for dropping an unique constraint.
957
     * @param string $name the name of the unique constraint to be dropped.
958
     * The name will be properly quoted by the method.
959
     * @param string $table the table whose unique constraint is to be dropped.
960
     * The name will be properly quoted by the method.
961
     * @return string the SQL statement for dropping an unique constraint.
962
     * @since 2.0.13
963
     */
964 2
    public function dropUnique($name, $table)
965
    {
966 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
967 2
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
968
    }
969
970
    /**
971
     * Creates a SQL command for adding a check constraint to an existing table.
972
     * @param string $name the name of the check constraint.
973
     * The name will be properly quoted by the method.
974
     * @param string $table the table that the check constraint will be added to.
975
     * The name will be properly quoted by the method.
976
     * @param string $expression the SQL of the `CHECK` constraint.
977
     * @return string the SQL statement for adding a check constraint to an existing table.
978
     * @since 2.0.13
979
     */
980 2
    public function addCheck($name, $table, $expression)
981
    {
982 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
983 2
            . $this->db->quoteColumnName($name) . ' CHECK (' . $this->db->quoteSql($expression) . ')';
984
    }
985
986
    /**
987
     * Creates a SQL command for dropping a check constraint.
988
     * @param string $name the name of the check constraint to be dropped.
989
     * The name will be properly quoted by the method.
990
     * @param string $table the table whose check constraint is to be dropped.
991
     * The name will be properly quoted by the method.
992
     * @return string the SQL statement for dropping a check constraint.
993
     * @since 2.0.13
994
     */
995 2
    public function dropCheck($name, $table)
996
    {
997 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
998 2
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
999
    }
1000
1001
    /**
1002
     * Creates a SQL command for adding a default value constraint to an existing table.
1003
     * @param string $name the name of the default value constraint.
1004
     * The name will be properly quoted by the method.
1005
     * @param string $table the table that the default value constraint will be added to.
1006
     * The name will be properly quoted by the method.
1007
     * @param string $column the name of the column to that the constraint will be added on.
1008
     * The name will be properly quoted by the method.
1009
     * @param mixed $value default value.
1010
     * @return string the SQL statement for adding a default value constraint to an existing table.
1011
     * @throws NotSupportedException if this is not supported by the underlying DBMS.
1012
     * @since 2.0.13
1013
     */
1014
    public function addDefaultValue($name, $table, $column, $value)
1015
    {
1016
        throw new NotSupportedException($this->db->getDriverName() . ' does not support adding default value constraints.');
1017
    }
1018
1019
    /**
1020
     * Creates a SQL command for dropping a default value constraint.
1021
     * @param string $name the name of the default value constraint to be dropped.
1022
     * The name will be properly quoted by the method.
1023
     * @param string $table the table whose default value constraint is to be dropped.
1024
     * The name will be properly quoted by the method.
1025
     * @return string the SQL statement for dropping a default value constraint.
1026
     * @throws NotSupportedException if this is not supported by the underlying DBMS.
1027
     * @since 2.0.13
1028
     */
1029
    public function dropDefaultValue($name, $table)
1030
    {
1031
        throw new NotSupportedException($this->db->getDriverName() . ' does not support dropping default value constraints.');
1032
    }
1033
1034
    /**
1035
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
1036
     * The sequence will be reset such that the primary key of the next new row inserted
1037
     * will have the specified value or the maximum existing value +1.
1038
     * @param string $table the name of the table whose primary key sequence will be reset
1039
     * @param array|string|null $value the value for the primary key of the next new row inserted. If this is not set,
1040
     * the next new row's primary key will have the maximum existing value +1.
1041
     * @return string the SQL statement for resetting sequence
1042
     * @throws NotSupportedException if this is not supported by the underlying DBMS
1043
     */
1044
    public function resetSequence($table, $value = null)
0 ignored issues
show
Unused Code introduced by
The parameter $table is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

1044
    public function resetSequence(/** @scrutinizer ignore-unused */ $table, $value = null)

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

Loading history...
1045
    {
1046
        throw new NotSupportedException($this->db->getDriverName() . ' does not support resetting sequence.');
1047
    }
1048
1049
    /**
1050
     * Execute a SQL statement for resetting the sequence value of a table's primary key.
1051
     * Reason for execute is that some databases (Oracle) need several queries to do so.
1052
     * The sequence is reset such that the primary key of the next new row inserted
1053
     * will have the specified value or the maximum existing value +1.
1054
     * @param string $table the name of the table whose primary key sequence is reset
1055
     * @param array|string|null $value the value for the primary key of the next new row inserted. If this is not set,
1056
     * the next new row's primary key will have the maximum existing value +1.
1057
     * @return int number of rows affected by the execution.
1058
     * @throws NotSupportedException if this is not supported by the underlying DBMS
1059
     * @since 2.0.16
1060
     */
1061 25
    public function executeResetSequence($table, $value = null)
1062
    {
1063 25
        return $this->db->createCommand()->resetSequence($table, $value)->execute();
1064
    }
1065
1066
    /**
1067
     * Builds a SQL statement for enabling or disabling integrity check.
1068
     * @param bool $check whether to turn on or off the integrity check.
1069
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
1070
     * @param string $table the table name. Defaults to empty string, meaning that no table will be changed.
1071
     * @return string the SQL statement for checking integrity
1072
     * @throws NotSupportedException if this is not supported by the underlying DBMS
1073
     */
1074
    public function checkIntegrity($check = true, $schema = '', $table = '')
0 ignored issues
show
Unused Code introduced by
The parameter $check is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

1074
    public function checkIntegrity(/** @scrutinizer ignore-unused */ $check = true, $schema = '', $table = '')

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

Loading history...
1075
    {
1076
        throw new NotSupportedException($this->db->getDriverName() . ' does not support enabling/disabling integrity check.');
1077
    }
1078
1079
    /**
1080
     * Builds a SQL command for adding comment to column.
1081
     *
1082
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
1083
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
1084
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
1085
     * @return string the SQL statement for adding comment on column
1086
     * @since 2.0.8
1087
     */
1088 2
    public function addCommentOnColumn($table, $column, $comment)
1089
    {
1090 2
        return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . ' IS ' . $this->db->quoteValue($comment);
1091
    }
1092
1093
    /**
1094
     * Builds a SQL command for adding comment to table.
1095
     *
1096
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
1097
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
1098
     * @return string the SQL statement for adding comment on table
1099
     * @since 2.0.8
1100
     */
1101 1
    public function addCommentOnTable($table, $comment)
1102
    {
1103 1
        return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS ' . $this->db->quoteValue($comment);
1104
    }
1105
1106
    /**
1107
     * Builds a SQL command for adding comment to column.
1108
     *
1109
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
1110
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
1111
     * @return string the SQL statement for adding comment on column
1112
     * @since 2.0.8
1113
     */
1114 2
    public function dropCommentFromColumn($table, $column)
1115
    {
1116 2
        return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . ' IS NULL';
1117
    }
1118
1119
    /**
1120
     * Builds a SQL command for adding comment to table.
1121
     *
1122
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
1123
     * @return string the SQL statement for adding comment on column
1124
     * @since 2.0.8
1125
     */
1126 1
    public function dropCommentFromTable($table)
1127
    {
1128 1
        return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS NULL';
1129
    }
1130
1131
    /**
1132
     * Creates a SQL View.
1133
     *
1134
     * @param string $viewName the name of the view to be created.
1135
     * @param string|Query $subQuery the select statement which defines the view.
1136
     * This can be either a string or a [[Query]] object.
1137
     * @return string the `CREATE VIEW` SQL statement.
1138
     * @since 2.0.14
1139
     */
1140 3
    public function createView($viewName, $subQuery)
1141
    {
1142 3
        if ($subQuery instanceof Query) {
1143 3
            list($rawQuery, $params) = $this->build($subQuery);
1144 3
            array_walk(
1145 3
                $params,
1146 3
                function (&$param) {
1147 3
                    $param = $this->db->quoteValue($param);
1148 3
                }
1149
            );
1150 3
            $subQuery = strtr($rawQuery, $params);
1151
        }
1152
1153 3
        return 'CREATE VIEW ' . $this->db->quoteTableName($viewName) . ' AS ' . $subQuery;
1154
    }
1155
1156
    /**
1157
     * Drops a SQL View.
1158
     *
1159
     * @param string $viewName the name of the view to be dropped.
1160
     * @return string the `DROP VIEW` SQL statement.
1161
     * @since 2.0.14
1162
     */
1163 5
    public function dropView($viewName)
1164
    {
1165 5
        return 'DROP VIEW ' . $this->db->quoteTableName($viewName);
1166
    }
1167
1168
    /**
1169
     * Converts an abstract column type into a physical column type.
1170
     *
1171
     * The conversion is done using the type map specified in [[typeMap]].
1172
     * The following abstract column types are supported (using MySQL as an example to explain the corresponding
1173
     * physical types):
1174
     *
1175
     * - `pk`: an auto-incremental primary key type, will be converted into "int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY"
1176
     * - `bigpk`: an auto-incremental primary key type, will be converted into "bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY"
1177
     * - `upk`: an unsigned auto-incremental primary key type, will be converted into "int(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY"
1178
     * - `char`: char type, will be converted into "char(1)"
1179
     * - `string`: string type, will be converted into "varchar(255)"
1180
     * - `text`: a long string type, will be converted into "text"
1181
     * - `smallint`: a small integer type, will be converted into "smallint(6)"
1182
     * - `integer`: integer type, will be converted into "int(11)"
1183
     * - `bigint`: a big integer type, will be converted into "bigint(20)"
1184
     * - `boolean`: boolean type, will be converted into "tinyint(1)"
1185
     * - `float``: float number type, will be converted into "float"
1186
     * - `decimal`: decimal number type, will be converted into "decimal"
1187
     * - `datetime`: datetime type, will be converted into "datetime"
1188
     * - `timestamp`: timestamp type, will be converted into "timestamp"
1189
     * - `time`: time type, will be converted into "time"
1190
     * - `date`: date type, will be converted into "date"
1191
     * - `money`: money type, will be converted into "decimal(19,4)"
1192
     * - `binary`: binary data type, will be converted into "blob"
1193
     *
1194
     * If the abstract type contains two or more parts separated by spaces (e.g. "string NOT NULL"), then only
1195
     * the first part will be converted, and the rest of the parts will be appended to the converted result.
1196
     * For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'.
1197
     *
1198
     * For some of the abstract types you can also specify a length or precision constraint
1199
     * by appending it in round brackets directly to the type.
1200
     * For example `string(32)` will be converted into "varchar(32)" on a MySQL database.
1201
     * If the underlying DBMS does not support these kind of constraints for a type it will
1202
     * be ignored.
1203
     *
1204
     * If a type cannot be found in [[typeMap]], it will be returned without any change.
1205
     * @param string|ColumnSchemaBuilder $type abstract column type
1206
     * @return string physical column type.
1207
     */
1208 178
    public function getColumnType($type)
1209
    {
1210 178
        if ($type instanceof ColumnSchemaBuilder) {
1211 52
            $type = $type->__toString();
1212
        }
1213
1214 178
        if (isset($this->typeMap[$type])) {
1215 164
            return $this->typeMap[$type];
1216 100
        } elseif (preg_match('/^(\w+)\((.+?)\)(.*)$/', $type, $matches)) {
1217 51
            if (isset($this->typeMap[$matches[1]])) {
1218 51
                return preg_replace('/\(.+\)/', '(' . $matches[2] . ')', $this->typeMap[$matches[1]]) . $matches[3];
1219
            }
1220 65
        } elseif (preg_match('/^(\w+)\s+/', $type, $matches)) {
1221 61
            if (isset($this->typeMap[$matches[1]])) {
1222 61
                return preg_replace('/^\w+/', $this->typeMap[$matches[1]], $type);
1223
            }
1224
        }
1225
1226 47
        return $type;
1227
    }
1228
1229
    /**
1230
     * @param array $columns
1231
     * @param array $params the binding parameters to be populated
1232
     * @param bool $distinct
1233
     * @param string|null $selectOption
1234
     * @return string the SELECT clause built from [[Query::$select]].
1235
     */
1236 1406
    public function buildSelect($columns, &$params, $distinct = false, $selectOption = null)
1237
    {
1238 1406
        $select = $distinct ? 'SELECT DISTINCT' : 'SELECT';
1239 1406
        if ($selectOption !== null) {
1240
            $select .= ' ' . $selectOption;
1241
        }
1242
1243 1406
        if (empty($columns)) {
1244 1118
            return $select . ' *';
1245
        }
1246
1247 621
        foreach ($columns as $i => $column) {
1248 621
            if ($column instanceof ExpressionInterface) {
1249 42
                if (is_int($i)) {
1250 6
                    $columns[$i] = $this->buildExpression($column, $params);
1251
                } else {
1252 42
                    $columns[$i] = $this->buildExpression($column, $params) . ' AS ' . $this->db->quoteColumnName($i);
1253
                }
1254 612
            } elseif ($column instanceof Query) {
1255
                list($sql, $params) = $this->build($column, $params);
1256
                $columns[$i] = "($sql) AS " . $this->db->quoteColumnName($i);
1257 612
            } elseif (is_string($i) && $i !== $column) {
1258 37
                if (strpos($column, '(') === false) {
1259 28
                    $column = $this->db->quoteColumnName($column);
1260
                }
1261 37
                $columns[$i] = "$column AS " . $this->db->quoteColumnName($i);
1262 607
            } elseif (strpos($column, '(') === false) {
1263 511
                if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $column, $matches)) {
1264
                    $columns[$i] = $this->db->quoteColumnName($matches[1]) . ' AS ' . $this->db->quoteColumnName($matches[2]);
1265
                } else {
1266 511
                    $columns[$i] = $this->db->quoteColumnName($column);
1267
                }
1268
            }
1269
        }
1270
1271 621
        return $select . ' ' . implode(', ', $columns);
1272
    }
1273
1274
    /**
1275
     * @param array $tables
1276
     * @param array $params the binding parameters to be populated
1277
     * @return string the FROM clause built from [[Query::$from]].
1278
     */
1279 1418
    public function buildFrom($tables, &$params)
1280
    {
1281 1418
        if (empty($tables)) {
1282 435
            return '';
1283
        }
1284
1285 1023
        $tables = $this->quoteTableNames($tables, $params);
1286
1287 1023
        return 'FROM ' . implode(', ', $tables);
1288
    }
1289
1290
    /**
1291
     * @param array $joins
1292
     * @param array $params the binding parameters to be populated
1293
     * @return string the JOIN clause built from [[Query::$join]].
1294
     * @throws Exception if the $joins parameter is not in proper format
1295
     */
1296 1406
    public function buildJoin($joins, &$params)
1297
    {
1298 1406
        if (empty($joins)) {
1299 1394
            return '';
1300
        }
1301
1302 93
        foreach ($joins as $i => $join) {
1303 93
            if (!is_array($join) || !isset($join[0], $join[1])) {
1304
                throw new Exception('A join clause must be specified as an array of join type, join table, and optionally join condition.');
1305
            }
1306
            // 0:join type, 1:join table, 2:on-condition (optional)
1307 93
            list($joinType, $table) = $join;
1308 93
            $tables = $this->quoteTableNames((array)$table, $params);
1309 93
            $table = reset($tables);
1310 93
            $joins[$i] = "$joinType $table";
1311 93
            if (isset($join[2])) {
1312 93
                $condition = $this->buildCondition($join[2], $params);
1313 93
                if ($condition !== '') {
1314 93
                    $joins[$i] .= ' ON ' . $condition;
1315
                }
1316
            }
1317
        }
1318
1319 93
        return implode($this->separator, $joins);
1320
    }
1321
1322
    /**
1323
     * Quotes table names passed.
1324
     *
1325
     * @param array $tables
1326
     * @param array $params
1327
     * @return array
1328
     */
1329 1023
    private function quoteTableNames($tables, &$params)
1330
    {
1331 1023
        foreach ($tables as $i => $table) {
1332 1023
            if ($table instanceof Query) {
1333 10
                list($sql, $params) = $this->build($table, $params);
1334 10
                $tables[$i] = "($sql) " . $this->db->quoteTableName($i);
1335 1023
            } elseif (is_string($i)) {
1336 121
                if (strpos($table, '(') === false) {
1337 104
                    $table = $this->db->quoteTableName($table);
1338
                }
1339 121
                $tables[$i] = "$table " . $this->db->quoteTableName($i);
1340 968
            } elseif (strpos($table, '(') === false) {
1341 961
                if ($tableWithAlias = $this->extractAlias($table)) { // with alias
1342 33
                    $tables[$i] = $this->db->quoteTableName($tableWithAlias[1]) . ' ' . $this->db->quoteTableName($tableWithAlias[2]);
1343
                } else {
1344 937
                    $tables[$i] = $this->db->quoteTableName($table);
1345
                }
1346
            }
1347
        }
1348
1349 1023
        return $tables;
1350
    }
1351
1352
    /**
1353
     * @param string|array $condition
1354
     * @param array $params the binding parameters to be populated
1355
     * @return string the WHERE clause built from [[Query::$where]].
1356
     */
1357 1504
    public function buildWhere($condition, &$params)
1358
    {
1359 1504
        $where = $this->buildCondition($condition, $params);
1360
1361 1504
        return $where === '' ? '' : 'WHERE ' . $where;
1362
    }
1363
1364
    /**
1365
     * @param array $columns
1366
     * @return string the GROUP BY clause
1367
     */
1368 1406
    public function buildGroupBy($columns)
1369
    {
1370 1406
        if (empty($columns)) {
1371 1400
            return '';
1372
        }
1373 23
        foreach ($columns as $i => $column) {
1374 23
            if ($column instanceof ExpressionInterface) {
1375 3
                $columns[$i] = $this->buildExpression($column);
1376 23
            } elseif (strpos($column, '(') === false) {
1377 23
                $columns[$i] = $this->db->quoteColumnName($column);
1378
            }
1379
        }
1380
1381 23
        return 'GROUP BY ' . implode(', ', $columns);
1382
    }
1383
1384
    /**
1385
     * @param string|array $condition
1386
     * @param array $params the binding parameters to be populated
1387
     * @return string the HAVING clause built from [[Query::$having]].
1388
     */
1389 1406
    public function buildHaving($condition, &$params)
1390
    {
1391 1406
        $having = $this->buildCondition($condition, $params);
1392
1393 1406
        return $having === '' ? '' : 'HAVING ' . $having;
1394
    }
1395
1396
    /**
1397
     * Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL.
1398
     * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET)
1399
     * @param array $orderBy the order by columns. See [[Query::orderBy]] for more details on how to specify this parameter.
1400
     * @param int $limit the limit number. See [[Query::limit]] for more details.
1401
     * @param int $offset the offset number. See [[Query::offset]] for more details.
1402
     * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any)
1403
     */
1404 1406
    public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset)
1405
    {
1406 1406
        $orderBy = $this->buildOrderBy($orderBy);
1407 1406
        if ($orderBy !== '') {
1408 234
            $sql .= $this->separator . $orderBy;
1409
        }
1410 1406
        $limit = $this->buildLimit($limit, $offset);
1411 1406
        if ($limit !== '') {
1412 118
            $sql .= $this->separator . $limit;
1413
        }
1414
1415 1406
        return $sql;
1416
    }
1417
1418
    /**
1419
     * @param array $columns
1420
     * @return string the ORDER BY clause built from [[Query::$orderBy]].
1421
     */
1422 1406
    public function buildOrderBy($columns)
1423
    {
1424 1406
        if (empty($columns)) {
1425 1364
            return '';
1426
        }
1427 234
        $orders = [];
1428 234
        foreach ($columns as $name => $direction) {
1429 234
            if ($direction instanceof ExpressionInterface) {
1430 11
                $orders[] = $this->buildExpression($direction);
1431
            } else {
1432 234
                $orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : '');
1433
            }
1434
        }
1435
1436 234
        return 'ORDER BY ' . implode(', ', $orders);
1437
    }
1438
1439
    /**
1440
     * @param int $limit
1441
     * @param int $offset
1442
     * @return string the LIMIT and OFFSET clauses
1443
     */
1444 502
    public function buildLimit($limit, $offset)
1445
    {
1446 502
        $sql = '';
1447 502
        if ($this->hasLimit($limit)) {
1448 33
            $sql = 'LIMIT ' . $limit;
1449
        }
1450 502
        if ($this->hasOffset($offset)) {
1451 3
            $sql .= ' OFFSET ' . $offset;
1452
        }
1453
1454 502
        return ltrim($sql);
1455
    }
1456
1457
    /**
1458
     * Checks to see if the given limit is effective.
1459
     * @param mixed $limit the given limit
1460
     * @return bool whether the limit is effective
1461
     */
1462 924
    protected function hasLimit($limit)
1463
    {
1464 924
        return ($limit instanceof ExpressionInterface) || ctype_digit((string)$limit);
1465
    }
1466
1467
    /**
1468
     * Checks to see if the given offset is effective.
1469
     * @param mixed $offset the given offset
1470
     * @return bool whether the offset is effective
1471
     */
1472 924
    protected function hasOffset($offset)
1473
    {
1474 924
        return ($offset instanceof ExpressionInterface) || ctype_digit((string)$offset) && (string)$offset !== '0';
1475
    }
1476
1477
    /**
1478
     * @param array $unions
1479
     * @param array $params the binding parameters to be populated
1480
     * @return string the UNION clause built from [[Query::$union]].
1481
     */
1482 984
    public function buildUnion($unions, &$params)
1483
    {
1484 984
        if (empty($unions)) {
1485 984
            return '';
1486
        }
1487
1488 10
        $result = '';
1489
1490 10
        foreach ($unions as $i => $union) {
1491 10
            $query = $union['query'];
1492 10
            if ($query instanceof Query) {
1493 10
                list($unions[$i]['query'], $params) = $this->build($query, $params);
1494
            }
1495
1496 10
            $result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . '( ' . $unions[$i]['query'] . ' ) ';
1497
        }
1498
1499 10
        return trim($result);
1500
    }
1501
1502
    /**
1503
     * @param array $withs of configurations for each WITH query
1504
     * @param array $params the binding parameters to be populated
1505
     * @return string compiled WITH prefix of query including nested queries
1506
     * @see Query::withQuery()
1507
     * @since 2.0.35
1508
     */
1509 1406
    public function buildWithQueries($withs, &$params)
1510
    {
1511 1406
        if (empty($withs)) {
1512 1406
            return '';
1513
        }
1514
1515 6
        $recursive = false;
1516 6
        $result = [];
1517
1518 6
        foreach ($withs as $i => $with) {
1519 6
            if ($with['recursive']) {
1520 3
                $recursive = true;
1521
            }
1522
1523 6
            $query = $with['query'];
1524 6
            if ($query instanceof Query) {
1525 6
                list($with['query'], $params) = $this->build($query, $params);
1526
            }
1527
1528 6
            $result[] = $with['alias'] . ' AS (' . $with['query'] . ')';
1529
        }
1530
1531 6
        return 'WITH ' . ($recursive ? 'RECURSIVE ' : '') . implode (', ', $result);
1532
    }
1533
1534
    /**
1535
     * Processes columns and properly quotes them if necessary.
1536
     * It will join all columns into a string with comma as separators.
1537
     * @param string|array $columns the columns to be processed
1538
     * @return string the processing result
1539
     */
1540 33
    public function buildColumns($columns)
1541
    {
1542 33
        if (!is_array($columns)) {
1543 28
            if (strpos($columns, '(') !== false) {
1544
                return $columns;
1545
            }
1546
1547 28
            $rawColumns = $columns;
1548 28
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
1549 28
            if ($columns === false) {
1550
                throw new InvalidArgumentException("$rawColumns is not valid columns.");
1551
            }
1552
        }
1553 33
        foreach ($columns as $i => $column) {
1554 33
            if ($column instanceof ExpressionInterface) {
1555
                $columns[$i] = $this->buildExpression($column);
1556 33
            } elseif (strpos($column, '(') === false) {
1557 33
                $columns[$i] = $this->db->quoteColumnName($column);
1558
            }
1559
        }
1560
1561 33
        return implode(', ', $columns);
0 ignored issues
show
Bug introduced by
It seems like $columns can also be of type string; however, parameter $pieces of implode() does only seem to accept array, 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 ignore-type  annotation

1561
        return implode(', ', /** @scrutinizer ignore-type */ $columns);
Loading history...
1562
    }
1563
1564
    /**
1565
     * Parses the condition specification and generates the corresponding SQL expression.
1566
     * @param string|array|ExpressionInterface $condition the condition specification. Please refer to [[Query::where()]]
1567
     * on how to specify a condition.
1568
     * @param array $params the binding parameters to be populated
1569
     * @return string the generated SQL expression
1570
     */
1571 1504
    public function buildCondition($condition, &$params)
1572
    {
1573 1504
        if (is_array($condition)) {
1574 1123
            if (empty($condition)) {
1575 3
                return '';
1576
            }
1577
1578 1123
            $condition = $this->createConditionFromArray($condition);
1579
        }
1580
1581 1504
        if ($condition instanceof ExpressionInterface) {
1582 1189
            return $this->buildExpression($condition, $params);
1583
        }
1584
1585 1484
        return (string)$condition;
1586
    }
1587
1588
    /**
1589
     * Transforms $condition defined in array format (as described in [[Query::where()]]
1590
     * to instance of [[yii\db\condition\ConditionInterface|ConditionInterface]] according to
1591
     * [[conditionClasses]] map.
1592
     *
1593
     * @param string|array $condition
1594
     * @return ConditionInterface
1595
     * @see conditionClasses
1596
     * @since 2.0.14
1597
     */
1598 1123
    public function createConditionFromArray($condition)
1599
    {
1600 1123
        if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
1601 704
            $operator = strtoupper(array_shift($condition));
0 ignored issues
show
Bug introduced by
It seems like $condition can also be of type string; however, parameter $array of array_shift() does only seem to accept array, 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 ignore-type  annotation

1601
            $operator = strtoupper(array_shift(/** @scrutinizer ignore-type */ $condition));
Loading history...
1602 704
            if (isset($this->conditionClasses[$operator])) {
0 ignored issues
show
introduced by
The property conditionClasses is declared write-only in yii\db\QueryBuilder.
Loading history...
1603 618
                $className = $this->conditionClasses[$operator];
1604
            } else {
1605 95
                $className = 'yii\db\conditions\SimpleCondition';
1606
            }
1607
            /** @var ConditionInterface $className */
1608 704
            return $className::fromArrayDefinition($operator, $condition);
1609
        }
1610
1611
        // hash format: 'column1' => 'value1', 'column2' => 'value2', ...
1612 760
        return new HashCondition($condition);
1613
    }
1614
1615
    /**
1616
     * Creates a condition based on column-value pairs.
1617
     * @param array $condition the condition specification.
1618
     * @param array $params the binding parameters to be populated
1619
     * @return string the generated SQL expression
1620
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1621
     */
1622
    public function buildHashCondition($condition, &$params)
1623
    {
1624
        return $this->buildCondition(new HashCondition($condition), $params);
1625
    }
1626
1627
    /**
1628
     * Connects two or more SQL expressions with the `AND` or `OR` operator.
1629
     * @param string $operator the operator to use for connecting the given operands
1630
     * @param array $operands the SQL expressions to connect.
1631
     * @param array $params the binding parameters to be populated
1632
     * @return string the generated SQL expression
1633
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1634
     */
1635
    public function buildAndCondition($operator, $operands, &$params)
1636
    {
1637
        array_unshift($operands, $operator);
1638
        return $this->buildCondition($operands, $params);
1639
    }
1640
1641
    /**
1642
     * Inverts an SQL expressions with `NOT` operator.
1643
     * @param string $operator the operator to use for connecting the given operands
1644
     * @param array $operands the SQL expressions to connect.
1645
     * @param array $params the binding parameters to be populated
1646
     * @return string the generated SQL expression
1647
     * @throws InvalidArgumentException if wrong number of operands have been given.
1648
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1649
     */
1650
    public function buildNotCondition($operator, $operands, &$params)
1651
    {
1652
        array_unshift($operands, $operator);
1653
        return $this->buildCondition($operands, $params);
1654
    }
1655
1656
    /**
1657
     * Creates an SQL expressions with the `BETWEEN` operator.
1658
     * @param string $operator the operator to use (e.g. `BETWEEN` or `NOT BETWEEN`)
1659
     * @param array $operands the first operand is the column name. The second and third operands
1660
     * describe the interval that column value should be in.
1661
     * @param array $params the binding parameters to be populated
1662
     * @return string the generated SQL expression
1663
     * @throws InvalidArgumentException if wrong number of operands have been given.
1664
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1665
     */
1666
    public function buildBetweenCondition($operator, $operands, &$params)
1667
    {
1668
        array_unshift($operands, $operator);
1669
        return $this->buildCondition($operands, $params);
1670
    }
1671
1672
    /**
1673
     * Creates an SQL expressions with the `IN` operator.
1674
     * @param string $operator the operator to use (e.g. `IN` or `NOT IN`)
1675
     * @param array $operands the first operand is the column name. If it is an array
1676
     * a composite IN condition will be generated.
1677
     * The second operand is an array of values that column value should be among.
1678
     * If it is an empty array the generated expression will be a `false` value if
1679
     * operator is `IN` and empty if operator is `NOT IN`.
1680
     * @param array $params the binding parameters to be populated
1681
     * @return string the generated SQL expression
1682
     * @throws Exception if wrong number of operands have been given.
1683
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1684
     */
1685
    public function buildInCondition($operator, $operands, &$params)
1686
    {
1687
        array_unshift($operands, $operator);
1688
        return $this->buildCondition($operands, $params);
1689
    }
1690
1691
    /**
1692
     * Creates an SQL expressions with the `LIKE` operator.
1693
     * @param string $operator the operator to use (e.g. `LIKE`, `NOT LIKE`, `OR LIKE` or `OR NOT LIKE`)
1694
     * @param array $operands an array of two or three operands
1695
     *
1696
     * - The first operand is the column name.
1697
     * - The second operand is a single value or an array of values that column value
1698
     *   should be compared with. If it is an empty array the generated expression will
1699
     *   be a `false` value if operator is `LIKE` or `OR LIKE`, and empty if operator
1700
     *   is `NOT LIKE` or `OR NOT LIKE`.
1701
     * - An optional third operand can also be provided to specify how to escape special characters
1702
     *   in the value(s). The operand should be an array of mappings from the special characters to their
1703
     *   escaped counterparts. If this operand is not provided, a default escape mapping will be used.
1704
     *   You may use `false` or an empty array to indicate the values are already escaped and no escape
1705
     *   should be applied. Note that when using an escape mapping (or the third operand is not provided),
1706
     *   the values will be automatically enclosed within a pair of percentage characters.
1707
     * @param array $params the binding parameters to be populated
1708
     * @return string the generated SQL expression
1709
     * @throws InvalidArgumentException if wrong number of operands have been given.
1710
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1711
     */
1712
    public function buildLikeCondition($operator, $operands, &$params)
1713
    {
1714
        array_unshift($operands, $operator);
1715
        return $this->buildCondition($operands, $params);
1716
    }
1717
1718
    /**
1719
     * Creates an SQL expressions with the `EXISTS` operator.
1720
     * @param string $operator the operator to use (e.g. `EXISTS` or `NOT EXISTS`)
1721
     * @param array $operands contains only one element which is a [[Query]] object representing the sub-query.
1722
     * @param array $params the binding parameters to be populated
1723
     * @return string the generated SQL expression
1724
     * @throws InvalidArgumentException if the operand is not a [[Query]] object.
1725
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1726
     */
1727
    public function buildExistsCondition($operator, $operands, &$params)
1728
    {
1729
        array_unshift($operands, $operator);
1730
        return $this->buildCondition($operands, $params);
1731
    }
1732
1733
    /**
1734
     * Creates an SQL expressions like `"column" operator value`.
1735
     * @param string $operator the operator to use. Anything could be used e.g. `>`, `<=`, etc.
1736
     * @param array $operands contains two column names.
1737
     * @param array $params the binding parameters to be populated
1738
     * @return string the generated SQL expression
1739
     * @throws InvalidArgumentException if wrong number of operands have been given.
1740
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1741
     */
1742
    public function buildSimpleCondition($operator, $operands, &$params)
1743
    {
1744
        array_unshift($operands, $operator);
1745
        return $this->buildCondition($operands, $params);
1746
    }
1747
1748
    /**
1749
     * Creates a SELECT EXISTS() SQL statement.
1750
     * @param string $rawSql the subquery in a raw form to select from.
1751
     * @return string the SELECT EXISTS() SQL statement.
1752
     * @since 2.0.8
1753
     */
1754 83
    public function selectExists($rawSql)
1755
    {
1756 83
        return 'SELECT EXISTS(' . $rawSql . ')';
1757
    }
1758
1759
    /**
1760
     * Helper method to add $value to $params array using [[PARAM_PREFIX]].
1761
     *
1762
     * @param string|null $value
1763
     * @param array $params passed by reference
1764
     * @return string the placeholder name in $params array
1765
     *
1766
     * @since 2.0.14
1767
     */
1768 1248
    public function bindParam($value, &$params)
1769
    {
1770 1248
        $phName = self::PARAM_PREFIX . count($params);
1771 1248
        $params[$phName] = $value;
1772
1773 1248
        return $phName;
1774
    }
1775
1776
    /**
1777
     * Extracts table alias if there is one or returns false
1778
     * @param $table
1779
     * @return bool|array
1780
     * @since 2.0.24
1781
     */
1782 961
    protected function extractAlias($table)
1783
    {
1784 961
        if (preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $table, $matches)) {
1785 33
            return $matches;
1786
        }
1787
1788 937
        return false;
1789
    }
1790
}
1791