Passed
Pull Request — 2.2 (#20357)
by Wilmer
12:59 queued 04:29
created

QueryBuilder::addForeignKey()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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

224
        $params = empty($params) ? $query->params : array_merge($params, /** @scrutinizer ignore-type */ $query->params);
Loading history...
225
226
        $clauses = [
227
            $this->buildSelect($query->select, $params, $query->distinct, $query->selectOption),
228
            $this->buildFrom($query->from, $params),
229
            $this->buildJoin($query->join, $params),
230
            $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

230
            $this->buildWhere(/** @scrutinizer ignore-type */ $query->where, $params),
Loading history...
231
            $this->buildGroupBy($query->groupBy),
232
            $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

232
            $this->buildHaving(/** @scrutinizer ignore-type */ $query->having, $params),
Loading history...
233
        ];
234
235
        $sql = implode($this->separator, array_filter($clauses));
236
        $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

236
        $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

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

574
        /** @scrutinizer ignore-call */ 
575
        $primaryKey = $schema->getTablePrimaryKey($name);
Loading history...
575
        if ($primaryKey !== null) {
576
            $constraints[] = $primaryKey;
577
        }
578
        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

578
        foreach ($schema->/** @scrutinizer ignore-call */ getTableIndexes($name) as $constraint) {
Loading history...
579
            if ($constraint->isUnique) {
580
                $constraints[] = $constraint;
581
            }
582
        }
583
        $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

583
        $constraints = array_merge($constraints, $schema->/** @scrutinizer ignore-call */ getTableUniques($name));
Loading history...
584
        // Remove duplicates
585
        $constraints = array_combine(array_map(function (Constraint $constraint) {
586
            $columns = $constraint->columnNames;
587
            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

587
            sort(/** @scrutinizer ignore-type */ $columns, SORT_STRING);
Loading history...
588
            return json_encode($columns);
589
        }, $constraints), $constraints);
590
        $columnNames = [];
591
        // Remove all constraints which do not cover the specified column list
592
        $constraints = array_values(array_filter($constraints, function (Constraint $constraint) use ($schema, $columns, &$columnNames) {
593
            $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

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

1038
    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...
1039
    {
1040
        throw new NotSupportedException($this->db->getDriverName() . ' does not support resetting sequence.');
1041
    }
1042
1043
    /**
1044
     * Execute a SQL statement for resetting the sequence value of a table's primary key.
1045
     * Reason for execute is that some databases (Oracle) need several queries to do so.
1046
     * The sequence is reset such that the primary key of the next new row inserted
1047
     * will have the specified value or the maximum existing value +1.
1048
     * @param string $table the name of the table whose primary key sequence is reset
1049
     * @param array|string|null $value the value for the primary key of the next new row inserted. If this is not set,
1050
     * the next new row's primary key will have the maximum existing value +1.
1051
     * @throws NotSupportedException if this is not supported by the underlying DBMS
1052
     * @since 2.0.16
1053
     */
1054
    public function executeResetSequence($table, $value = null)
1055
    {
1056
        $this->db->createCommand()->resetSequence($table, $value)->execute();
1057
    }
1058
1059
    /**
1060
     * Builds a SQL statement for enabling or disabling integrity check.
1061
     * @param bool $check whether to turn on or off the integrity check.
1062
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
1063
     * @param string $table the table name. Defaults to empty string, meaning that no table will be changed.
1064
     * @return string the SQL statement for checking integrity
1065
     * @throws NotSupportedException if this is not supported by the underlying DBMS
1066
     */
1067
    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

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

1554
        return implode(', ', /** @scrutinizer ignore-type */ $columns);
Loading history...
1555
    }
1556
1557
    /**
1558
     * Parses the condition specification and generates the corresponding SQL expression.
1559
     * @param string|array|ExpressionInterface $condition the condition specification. Please refer to [[Query::where()]]
1560
     * on how to specify a condition.
1561
     * @param array $params the binding parameters to be populated
1562
     * @return string the generated SQL expression
1563
     */
1564 33
    public function buildCondition($condition, &$params)
1565
    {
1566 33
        if (is_array($condition)) {
1567 19
            if (empty($condition)) {
1568
                return '';
1569
            }
1570
1571 19
            $condition = $this->createConditionFromArray($condition);
1572
        }
1573
1574 33
        if ($condition instanceof ExpressionInterface) {
1575 19
            return $this->buildExpression($condition, $params);
1576
        }
1577
1578 27
        return (string)$condition;
1579
    }
1580
1581
    /**
1582
     * Transforms $condition defined in array format (as described in [[Query::where()]]
1583
     * to instance of [[yii\db\condition\ConditionInterface|ConditionInterface]] according to
1584
     * [[conditionClasses]] map.
1585
     *
1586
     * @param string|array $condition
1587
     * @return ConditionInterface
1588
     * @see conditionClasses
1589
     * @since 2.0.14
1590
     */
1591 19
    public function createConditionFromArray($condition)
1592
    {
1593 19
        if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
1594 7
            $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

1594
            $operator = strtoupper(array_shift(/** @scrutinizer ignore-type */ $condition));
Loading history...
1595 7
            if (isset($this->conditionClasses[$operator])) {
0 ignored issues
show
introduced by
The property conditionClasses is declared write-only in yii\db\QueryBuilder.
Loading history...
1596 7
                $className = $this->conditionClasses[$operator];
1597
            } else {
1598
                $className = 'yii\db\conditions\SimpleCondition';
1599
            }
1600
            /** @var ConditionInterface $className */
1601 7
            return $className::fromArrayDefinition($operator, $condition);
1602
        }
1603
1604
        // hash format: 'column1' => 'value1', 'column2' => 'value2', ...
1605 18
        return new HashCondition($condition);
1606
    }
1607
1608
    /**
1609
     * Creates a SELECT EXISTS() SQL statement.
1610
     * @param string $rawSql the subquery in a raw form to select from.
1611
     * @return string the SELECT EXISTS() SQL statement.
1612
     * @since 2.0.8
1613
     */
1614 7
    public function selectExists($rawSql)
1615
    {
1616 7
        return 'SELECT EXISTS(' . $rawSql . ')';
1617
    }
1618
1619
    /**
1620
     * Helper method to add $value to $params array using [[PARAM_PREFIX]].
1621
     *
1622
     * @param string|null $value
1623
     * @param array $params passed by reference
1624
     * @return string the placeholder name in $params array
1625
     *
1626
     * @since 2.0.14
1627
     */
1628 31
    public function bindParam($value, &$params)
1629
    {
1630 31
        $phName = self::PARAM_PREFIX . count($params);
1631 31
        $params[$phName] = $value;
1632
1633 31
        return $phName;
1634
    }
1635
1636
    /**
1637
     * Extracts table alias if there is one or returns false
1638
     * @param $table
1639
     * @return bool|array
1640
     * @since 2.0.24
1641
     */
1642 16
    protected function extractAlias($table)
1643
    {
1644 16
        if (preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $table, $matches)) {
1645
            return $matches;
1646
        }
1647
1648 16
        return false;
1649
    }
1650
}
1651