Completed
Push — php-74-ci ( 3d1af5...9001b7 )
by Alexander
24:14 queued 23:56
created

QueryBuilder::extractAlias()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use yii\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 string[] $conditionClasses Map of condition aliases to condition classes. For example: ```php
26
 * ['LIKE' => yii\db\condition\LikeCondition::class] ``` . This property is write-only.
27
 * @property string[] $expressionBuilders Array of builders that should be merged with the pre-defined ones in
28
 * [[expressionBuilders]] property. This property is write-only.
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 setConditonClasses()
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 1528
    public function __construct($connection, $config = [])
114
    {
115 1528
        $this->db = $connection;
116 1528
        parent::__construct($config);
117 1528
    }
118
119
    /**
120
     * {@inheritdoc}
121
     */
122 1528
    public function init()
123
    {
124 1528
        parent::init();
125
126 1528
        $this->expressionBuilders = array_merge($this->defaultExpressionBuilders(), $this->expressionBuilders);
127 1528
        $this->conditionClasses = array_merge($this->defaultConditionClasses(), $this->conditionClasses);
128 1528
    }
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 1528
    protected function defaultConditionClasses()
139
    {
140
        return [
141 1528
            '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 1528
    protected function defaultExpressionBuilders()
166
    {
167
        return [
168 1528
            '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
    public function setExpressionBuilders($builders)
194
    {
195
        $this->expressionBuilders = array_merge($this->expressionBuilders, $builders);
196
    }
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);
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 856
    public function build($query, $params = [])
226
    {
227 856
        $query = $query->prepare($this);
228
229 856
        $params = empty($params) ? $query->params : array_merge($params, $query->params);
230
231
        $clauses = [
232 856
            $this->buildSelect($query->select, $params, $query->distinct, $query->selectOption),
233 856
            $this->buildFrom($query->from, $params),
234 856
            $this->buildJoin($query->join, $params),
235 856
            $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 856
            $this->buildGroupBy($query->groupBy),
237 856
            $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 856
        $sql = implode($this->separator, array_filter($clauses));
241 856
        $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 856
        if (!empty($query->orderBy)) {
244 115
            foreach ($query->orderBy as $expression) {
245 115
                if ($expression instanceof ExpressionInterface) {
246 2
                    $this->buildExpression($expression, $params);
247
                }
248
            }
249
        }
250 856
        if (!empty($query->groupBy)) {
251 21
            foreach ($query->groupBy as $expression) {
252 21
                if ($expression instanceof ExpressionInterface) {
253 2
                    $this->buildExpression($expression, $params);
254
                }
255
            }
256
        }
257
258 856
        $union = $this->buildUnion($query->union, $params);
259 856
        if ($union !== '') {
260 8
            $sql = "($sql){$this->separator}$union";
261
        }
262
263 856
        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 1115
    public function buildExpression(ExpressionInterface $expression, &$params = [])
280
    {
281 1115
        $builder = $this->getExpressionBuilder($expression);
282
283 1115
        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 1115
    public function getExpressionBuilder(ExpressionInterface $expression)
297
    {
298 1115
        $className = get_class($expression);
299
300 1115
        if (!isset($this->expressionBuilders[$className])) {
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 1115
        if ($this->expressionBuilders[$className] === __CLASS__) {
314
            return $this;
315
        }
316
317 1115
        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 1071
            $this->expressionBuilders[$className] = new $this->expressionBuilders[$className]($this);
319
        }
320
321 1115
        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 556
    public function insert($table, $columns, &$params)
344
    {
345 556
        list($names, $placeholders, $values, $params) = $this->prepareInsertValues($table, $columns, $params);
346 547
        return 'INSERT INTO ' . $this->db->quoteTableName($table)
347 547
            . (!empty($names) ? ' (' . implode(', ', $names) . ')' : '')
348 547
            . (!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 571
    protected function prepareInsertValues($table, $columns, $params = [])
363
    {
364 571
        $schema = $this->db->getSchema();
365 571
        $tableSchema = $schema->getTableSchema($table);
366 571
        $columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
367 571
        $names = [];
368 571
        $placeholders = [];
369 571
        $values = ' DEFAULT VALUES';
370 571
        if ($columns instanceof Query) {
371 42
            list($names, $values, $params) = $this->prepareInsertSelectSubQuery($columns, $schema, $params);
372
        } else {
373 535
            foreach ($columns as $name => $value) {
374 531
                $names[] = $schema->quoteColumnName($name);
375 531
                $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
376
377 531
                if ($value instanceof ExpressionInterface) {
378 137
                    $placeholders[] = $this->buildExpression($value, $params);
379 521
                } elseif ($value instanceof \yii\db\Query) {
380
                    list($sql, $params) = $this->build($value, $params);
381
                    $placeholders[] = "($sql)";
382
                } else {
383 521
                    $placeholders[] = $this->bindParam($value, $params);
384
                }
385
            }
386
        }
387 562
        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 42
    protected function prepareInsertSelectSubQuery($columns, $schema, $params = [])
402
    {
403 42
        if (!is_array($columns->select) || empty($columns->select) || in_array('*', $columns->select)) {
0 ignored issues
show
introduced by
The condition is_array($columns->select) is always true.
Loading history...
404 9
            throw new InvalidArgumentException('Expected select query object with enumerated (named) parameters');
405
        }
406
407 33
        list($values, $params) = $this->build($columns, $params);
408 33
        $names = [];
409 33
        $values = ' ' . $values;
410 33
        foreach ($columns->select as $title => $field) {
411 33
            if (is_string($title)) {
412 33
                $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 33
        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 29
    public function batchInsert($table, $columns, $rows, &$params = [])
447
    {
448 29
        if (empty($rows)) {
449 2
            return '';
450
        }
451
452 28
        $schema = $this->db->getSchema();
453 28
        if (($tableSchema = $schema->getTableSchema($table)) !== null) {
454 22
            $columnSchemas = $tableSchema->columns;
455
        } else {
456 6
            $columnSchemas = [];
457
        }
458
459 28
        $values = [];
460 28
        foreach ($rows as $row) {
461 24
            $vs = [];
462 24
            foreach ($row as $i => $value) {
463 24
                if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
464 15
                    $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
465
                }
466 24
                if (is_string($value)) {
467 16
                    $value = $schema->quoteValue($value);
468 15
                } elseif (is_float($value)) {
469
                    // ensure type cast always has . as decimal separator in all locales
470 2
                    $value = StringHelper::floatToString($value);
471 15
                } elseif ($value === false) {
472 4
                    $value = 0;
473 15
                } elseif ($value === null) {
474 8
                    $value = 'NULL';
475 10
                } elseif ($value instanceof ExpressionInterface) {
476 6
                    $value = $this->buildExpression($value, $params);
477
                }
478 24
                $vs[] = $value;
479
            }
480 24
            $values[] = '(' . implode(', ', $vs) . ')';
481
        }
482 28
        if (empty($values)) {
483 4
            return '';
484
        }
485
486 24
        foreach ($columns as $i => $name) {
487 22
            $columns[$i] = $schema->quoteColumnName($name);
488
        }
489
490 24
        return 'INSERT INTO ' . $schema->quoteTableName($table)
491 24
            . ' (' . 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' => 'http://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 104
    protected function prepareUpsertColumns($table, $insertColumns, $updateColumns, &$constraints = [])
540
    {
541 104
        if ($insertColumns instanceof Query) {
542 24
            list($insertNames) = $this->prepareInsertSelectSubQuery($insertColumns, $this->db->getSchema());
543
        } else {
544 80
            $insertNames = array_map([$this->db, 'quoteColumnName'], array_keys($insertColumns));
545
        }
546 104
        $uniqueNames = $this->getTableUniqueColumnNames($table, $insertNames, $constraints);
547 104
        $uniqueNames = array_map([$this->db, 'quoteColumnName'], $uniqueNames);
548 104
        if ($updateColumns !== true) {
549 36
            return [$uniqueNames, $insertNames, null];
550
        }
551
552 68
        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 104
    private function getTableUniqueColumnNames($name, $columns, &$constraints = [])
567
    {
568 104
        $schema = $this->db->getSchema();
569 104
        if (!$schema instanceof ConstraintFinderInterface) {
570
            return [];
571
        }
572
573 104
        $constraints = [];
574 104
        $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 104
        if ($primaryKey !== null) {
576 104
            $constraints[] = $primaryKey;
577
        }
578 104
        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 103
            if ($constraint->isUnique) {
580 103
                $constraints[] = $constraint;
581
            }
582
        }
583 104
        $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 104
            $columns = $constraint->columnNames;
587 104
            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 104
            return json_encode($columns);
589 104
        }, $constraints), $constraints);
590 104
        $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) {
0 ignored issues
show
Bug introduced by
It seems like $constraints can also be of type false; however, parameter $input of array_filter() 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
        $constraints = array_values(array_filter(/** @scrutinizer ignore-type */ $constraints, function (Constraint $constraint) use ($schema, $columns, &$columnNames) {
Loading history...
593 104
            $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 $arr1 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 104
            $result = !array_diff($constraintColumnNames, $columns);
595 104
            if ($result) {
596 95
                $columnNames = array_merge($columnNames, $constraintColumnNames);
597
            }
598 104
            return $result;
599 104
        }));
600 104
        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 114
    public function update($table, $columns, $condition, &$params)
624
    {
625 114
        list($lines, $params) = $this->prepareUpdateSets($table, $columns, $params);
626 114
        $sql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $lines);
627 114
        $where = $this->buildWhere($condition, $params);
628 114
        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 181
    protected function prepareUpdateSets($table, $columns, $params = [])
641
    {
642 181
        $tableSchema = $this->db->getTableSchema($table);
643 181
        $columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
644 181
        $sets = [];
645 181
        foreach ($columns as $name => $value) {
646
647 181
            $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
648 181
            if ($value instanceof ExpressionInterface) {
649 100
                $placeholder = $this->buildExpression($value, $params);
650
            } else {
651 102
                $placeholder = $this->bindParam($value, $params);
652
            }
653
654 181
            $sets[] = $this->db->quoteColumnName($name) . '=' . $placeholder;
655
        }
656 181
        return [$sets, $params];
657
    }
658
659
    /**
660
     * Creates a DELETE SQL statement.
661
     *
662
     * For example,
663
     *
664
     * ```php
665
     * $sql = $queryBuilder->delete('user', 'status = 0');
666
     * ```
667
     *
668
     * The method will properly escape the table and column names.
669
     *
670
     * @param string $table the table where the data will be deleted from.
671
     * @param array|string $condition the condition that will be put in the WHERE part. Please
672
     * refer to [[Query::where()]] on how to specify condition.
673
     * @param array $params the binding parameters that will be modified by this method
674
     * so that they can be bound to the DB command later.
675
     * @return string the DELETE SQL
676
     */
677 372
    public function delete($table, $condition, &$params)
678
    {
679 372
        $sql = 'DELETE FROM ' . $this->db->quoteTableName($table);
680 372
        $where = $this->buildWhere($condition, $params);
681
682 372
        return $where === '' ? $sql : $sql . ' ' . $where;
683
    }
684
685
    /**
686
     * Builds a SQL statement for creating a new DB table.
687
     *
688
     * The columns in the new table should be specified as name-definition pairs (e.g. 'name' => 'string'),
689
     * where name stands for a column name which will be properly quoted by the method, and definition
690
     * stands for the column type which can contain an abstract DB type.
691
     * The [[getColumnType()]] method will be invoked to convert any abstract type into a physical one.
692
     *
693
     * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
694
     * inserted into the generated SQL.
695
     *
696
     * For example,
697
     *
698
     * ```php
699
     * $sql = $queryBuilder->createTable('user', [
700
     *  'id' => 'pk',
701
     *  'name' => 'string',
702
     *  'age' => 'integer',
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 $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 147
    public function createTable($table, $columns, $options = null)
712
    {
713 147
        $cols = [];
714 147
        foreach ($columns as $name => $type) {
715 147
            if (is_string($name)) {
716 147
                $cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type);
717
            } else {
718 26
                $cols[] = "\t" . $type;
719
            }
720
        }
721 147
        $sql = 'CREATE TABLE ' . $this->db->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)";
722
723 147
        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 2
    public function renameTable($oldName, $newName)
733
    {
734 2
        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 43
    public function dropTable($table)
743
    {
744 43
        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 6
    public function addPrimaryKey($name, $table, $columns)
755
    {
756 6
        if (is_string($columns)) {
757 4
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
758
        }
759
760 6
        foreach ($columns as $i => $col) {
761 6
            $columns[$i] = $this->db->quoteColumnName($col);
762
        }
763
764 6
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
765 6
            . $this->db->quoteColumnName($name) . ' PRIMARY KEY ('
766 6
            . implode(', ', $columns) . ')';
0 ignored issues
show
Bug introduced by
It seems like $columns can also be of type false; 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

766
            . implode(', ', /** @scrutinizer ignore-type */ $columns) . ')';
Loading history...
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 2
    public function dropPrimaryKey($name, $table)
776
    {
777 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
778 2
            . ' 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 12
    public function truncateTable($table)
787
    {
788 12
        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 7
    public function addColumn($table, $column, $type)
801
    {
802 7
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
803 7
            . ' ADD ' . $this->db->quoteColumnName($column) . ' '
804 7
            . $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 1
    public function alterColumn($table, $column, $type)
844
    {
845 1
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
846 1
            . $this->db->quoteColumnName($column) . ' '
847 1
            . $this->db->quoteColumnName($column) . ' '
848 1
            . $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 $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
862
     * @param string $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 8
    public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
866
    {
867 8
        $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
868 8
            . ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name)
869 8
            . ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
870 8
            . ' REFERENCES ' . $this->db->quoteTableName($refTable)
871 8
            . ' (' . $this->buildColumns($refColumns) . ')';
872 8
        if ($delete !== null) {
873 4
            $sql .= ' ON DELETE ' . $delete;
874
        }
875 8
        if ($update !== null) {
876 4
            $sql .= ' ON UPDATE ' . $update;
877
        }
878
879 8
        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 3
    public function dropForeignKey($name, $table)
889
    {
890 3
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
891 3
            . ' 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 6
    public function createIndex($name, $table, $columns, $unique = false)
905
    {
906 6
        return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
907 6
            . $this->db->quoteTableName($name) . ' ON '
908 6
            . $this->db->quoteTableName($table)
909 6
            . ' (' . $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 4
    public function dropIndex($name, $table)
919
    {
920 4
        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 6
    public function addUnique($name, $table, $columns)
936
    {
937 6
        if (is_string($columns)) {
938 4
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
939
        }
940 6
        foreach ($columns as $i => $col) {
941 6
            $columns[$i] = $this->db->quoteColumnName($col);
942
        }
943
944 6
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
945 6
            . $this->db->quoteColumnName($name) . ' UNIQUE ('
946 6
            . implode(', ', $columns) . ')';
0 ignored issues
show
Bug introduced by
It seems like $columns can also be of type false; 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

946
            . implode(', ', /** @scrutinizer ignore-type */ $columns) . ')';
Loading history...
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 2
    public function dropUnique($name, $table)
959
    {
960 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
961 2
            . ' 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 2
    public function addCheck($name, $table, $expression)
975
    {
976 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
977 2
            . $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 2
    public function dropCheck($name, $table)
990
    {
991 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
992 2
            . ' 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 $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 $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 25
    public function executeResetSequence($table, $value = null)
1055
    {
1056 25
        $this->db->createCommand()->resetSequence($table, $value)->execute();
1057 25
    }
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 2
    public function addCommentOnColumn($table, $column, $comment)
1082
    {
1083 2
        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 1
    public function addCommentOnTable($table, $comment)
1095
    {
1096 1
        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 2
    public function dropCommentFromColumn($table, $column)
1108
    {
1109 2
        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 1
    public function dropCommentFromTable($table)
1120
    {
1121 1
        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 3
    public function createView($viewName, $subQuery)
1134
    {
1135 3
        if ($subQuery instanceof Query) {
1136 3
            list($rawQuery, $params) = $this->build($subQuery);
1137 3
            array_walk(
1138 3
                $params,
1139
                function (&$param) {
1140 3
                    $param = $this->db->quoteValue($param);
1141 3
                }
1142
            );
1143 3
            $subQuery = strtr($rawQuery, $params);
1144
        }
1145
1146 3
        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 5
    public function dropView($viewName)
1157
    {
1158 5
        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 151
    public function getColumnType($type)
1202
    {
1203 151
        if ($type instanceof ColumnSchemaBuilder) {
1204 37
            $type = $type->__toString();
1205
        }
1206
1207 151
        if (isset($this->typeMap[$type])) {
1208 138
            return $this->typeMap[$type];
1209 85
        } elseif (preg_match('/^(\w+)\((.+?)\)(.*)$/', $type, $matches)) {
1210 41
            if (isset($this->typeMap[$matches[1]])) {
1211 41
                return preg_replace('/\(.+\)/', '(' . $matches[2] . ')', $this->typeMap[$matches[1]]) . $matches[3];
1212
            }
1213 60
        } elseif (preg_match('/^(\w+)\s+/', $type, $matches)) {
1214 57
            if (isset($this->typeMap[$matches[1]])) {
1215 57
                return preg_replace('/^\w+/', $this->typeMap[$matches[1]], $type);
1216
            }
1217
        }
1218
1219 34
        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 $selectOption
1227
     * @return string the SELECT clause built from [[Query::$select]].
1228
     */
1229 1210
    public function buildSelect($columns, &$params, $distinct = false, $selectOption = null)
1230
    {
1231 1210
        $select = $distinct ? 'SELECT DISTINCT' : 'SELECT';
1232 1210
        if ($selectOption !== null) {
1233
            $select .= ' ' . $selectOption;
1234
        }
1235
1236 1210
        if (empty($columns)) {
1237 936
            return $select . ' *';
1238
        }
1239
1240 564
        foreach ($columns as $i => $column) {
1241 564
            if ($column instanceof ExpressionInterface) {
1242 42
                if (is_int($i)) {
1243 6
                    $columns[$i] = $this->buildExpression($column, $params);
1244
                } else {
1245 42
                    $columns[$i] = $this->buildExpression($column, $params) . ' AS ' . $this->db->quoteColumnName($i);
1246
                }
1247 555
            } elseif ($column instanceof Query) {
1248
                list($sql, $params) = $this->build($column, $params);
1249
                $columns[$i] = "($sql) AS " . $this->db->quoteColumnName($i);
1250 555
            } elseif (is_string($i) && $i !== $column) {
1251 38
                if (strpos($column, '(') === false) {
1252 29
                    $column = $this->db->quoteColumnName($column);
1253
                }
1254 38
                $columns[$i] = "$column AS " . $this->db->quoteColumnName($i);
1255 550
            } elseif (strpos($column, '(') === false) {
1256 463
                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 463
                    $columns[$i] = $this->db->quoteColumnName($column);
1260
                }
1261
            }
1262
        }
1263
1264 564
        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 1222
    public function buildFrom($tables, &$params)
1273
    {
1274 1222
        if (empty($tables)) {
1275 363
            return '';
1276
        }
1277
1278 899
        $tables = $this->quoteTableNames($tables, $params);
1279
1280 899
        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 1210
    public function buildJoin($joins, &$params)
1290
    {
1291 1210
        if (empty($joins)) {
1292 1198
            return '';
1293
        }
1294
1295 60
        foreach ($joins as $i => $join) {
1296 60
            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 60
            list($joinType, $table) = $join;
1301 60
            $tables = $this->quoteTableNames((array)$table, $params);
1302 60
            $table = reset($tables);
1303 60
            $joins[$i] = "$joinType $table";
1304 60
            if (isset($join[2])) {
1305 60
                $condition = $this->buildCondition($join[2], $params);
1306 60
                if ($condition !== '') {
1307 60
                    $joins[$i] .= ' ON ' . $condition;
1308
                }
1309
            }
1310
        }
1311
1312 60
        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 899
    private function quoteTableNames($tables, &$params)
1323
    {
1324 899
        foreach ($tables as $i => $table) {
1325 899
            if ($table instanceof Query) {
1326 10
                list($sql, $params) = $this->build($table, $params);
1327 10
                $tables[$i] = "($sql) " . $this->db->quoteTableName($i);
1328 899
            } elseif (is_string($i)) {
1329 82
                if (strpos($table, '(') === false) {
1330 73
                    $table = $this->db->quoteTableName($table);
1331
                }
1332 82
                $tables[$i] = "$table " . $this->db->quoteTableName($i);
1333 878
            } elseif (strpos($table, '(') === false) {
1334 871
                if ($tableWithAlias = $this->extractAlias($table)) { // with alias
1335 30
                    $tables[$i] = $this->db->quoteTableName($tableWithAlias[1]) . ' ' . $this->db->quoteTableName($tableWithAlias[2]);
1336
                } else {
1337 847
                    $tables[$i] = $this->db->quoteTableName($table);
1338
                }
1339
            }
1340
        }
1341
1342 899
        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 1307
    public function buildWhere($condition, &$params)
1351
    {
1352 1307
        $where = $this->buildCondition($condition, $params);
1353
1354 1307
        return $where === '' ? '' : 'WHERE ' . $where;
1355
    }
1356
1357
    /**
1358
     * @param array $columns
1359
     * @return string the GROUP BY clause
1360
     */
1361 1210
    public function buildGroupBy($columns)
1362
    {
1363 1210
        if (empty($columns)) {
1364 1204
            return '';
1365
        }
1366 24
        foreach ($columns as $i => $column) {
1367 24
            if ($column instanceof ExpressionInterface) {
1368 3
                $columns[$i] = $this->buildExpression($column);
1369 24
            } elseif (strpos($column, '(') === false) {
1370 24
                $columns[$i] = $this->db->quoteColumnName($column);
1371
            }
1372
        }
1373
1374 24
        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 1210
    public function buildHaving($condition, &$params)
1383
    {
1384 1210
        $having = $this->buildCondition($condition, $params);
1385
1386 1210
        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 1210
    public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset)
1398
    {
1399 1210
        $orderBy = $this->buildOrderBy($orderBy);
1400 1210
        if ($orderBy !== '') {
1401 190
            $sql .= $this->separator . $orderBy;
1402
        }
1403 1210
        $limit = $this->buildLimit($limit, $offset);
1404 1210
        if ($limit !== '') {
1405 100
            $sql .= $this->separator . $limit;
1406
        }
1407
1408 1210
        return $sql;
1409
    }
1410
1411
    /**
1412
     * @param array $columns
1413
     * @return string the ORDER BY clause built from [[Query::$orderBy]].
1414
     */
1415 1210
    public function buildOrderBy($columns)
1416
    {
1417 1210
        if (empty($columns)) {
1418 1168
            return '';
1419
        }
1420 190
        $orders = [];
1421 190
        foreach ($columns as $name => $direction) {
1422 190
            if ($direction instanceof ExpressionInterface) {
1423 3
                $orders[] = $this->buildExpression($direction);
1424
            } else {
1425 190
                $orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : '');
1426
            }
1427
        }
1428
1429 190
        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 437
    public function buildLimit($limit, $offset)
1438
    {
1439 437
        $sql = '';
1440 437
        if ($this->hasLimit($limit)) {
1441 28
            $sql = 'LIMIT ' . $limit;
1442
        }
1443 437
        if ($this->hasOffset($offset)) {
1444 3
            $sql .= ' OFFSET ' . $offset;
1445
        }
1446
1447 437
        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 791
    protected function hasLimit($limit)
1456
    {
1457 791
        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 791
    protected function hasOffset($offset)
1466
    {
1467 791
        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 856
    public function buildUnion($unions, &$params)
1476
    {
1477 856
        if (empty($unions)) {
1478 856
            return '';
1479
        }
1480
1481 8
        $result = '';
1482
1483 8
        foreach ($unions as $i => $union) {
1484 8
            $query = $union['query'];
1485 8
            if ($query instanceof Query) {
1486 8
                list($unions[$i]['query'], $params) = $this->build($query, $params);
1487
            }
1488
1489 8
            $result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . '( ' . $unions[$i]['query'] . ' ) ';
1490
        }
1491
1492 8
        return trim($result);
1493
    }
1494
1495
    /**
1496
     * Processes columns and properly quotes them if necessary.
1497
     * It will join all columns into a string with comma as separators.
1498
     * @param string|array $columns the columns to be processed
1499
     * @return string the processing result
1500
     */
1501 32
    public function buildColumns($columns)
1502
    {
1503 32
        if (!is_array($columns)) {
1504 27
            if (strpos($columns, '(') !== false) {
1505
                return $columns;
1506
            }
1507
1508 27
            $rawColumns = $columns;
1509 27
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
1510 27
            if ($columns === false) {
1511
                throw new InvalidArgumentException("$rawColumns is not valid columns.");
1512
            }
1513
        }
1514 32
        foreach ($columns as $i => $column) {
1515 32
            if ($column instanceof ExpressionInterface) {
1516
                $columns[$i] = $this->buildExpression($column);
1517 32
            } elseif (strpos($column, '(') === false) {
1518 32
                $columns[$i] = $this->db->quoteColumnName($column);
1519
            }
1520
        }
1521
1522 32
        return implode(', ', $columns);
0 ignored issues
show
Bug introduced by
It seems like $columns can also be of type false and 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

1522
        return implode(', ', /** @scrutinizer ignore-type */ $columns);
Loading history...
1523
    }
1524
1525
    /**
1526
     * Parses the condition specification and generates the corresponding SQL expression.
1527
     * @param string|array|ExpressionInterface $condition the condition specification. Please refer to [[Query::where()]]
1528
     * on how to specify a condition.
1529
     * @param array $params the binding parameters to be populated
1530
     * @return string the generated SQL expression
1531
     */
1532 1307
    public function buildCondition($condition, &$params)
1533
    {
1534 1307
        if (is_array($condition)) {
1535 1000
            if (empty($condition)) {
1536 3
                return '';
1537
            }
1538
1539 1000
            $condition = $this->createConditionFromArray($condition);
1540
        }
1541
1542 1307
        if ($condition instanceof ExpressionInterface) {
1543 1021
            return $this->buildExpression($condition, $params);
1544
        }
1545
1546 1287
        return (string)$condition;
1547
    }
1548
1549
    /**
1550
     * Transforms $condition defined in array format (as described in [[Query::where()]]
1551
     * to instance of [[yii\db\condition\ConditionInterface|ConditionInterface]] according to
1552
     * [[conditionClasses]] map.
1553
     *
1554
     * @param string|array $condition
1555
     * @return ConditionInterface
1556
     * @see conditionClasses
1557
     * @since 2.0.14
1558
     */
1559 1000
    public function createConditionFromArray($condition)
1560
    {
1561 1000
        if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
1562 623
            $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

1562
            $operator = strtoupper(array_shift(/** @scrutinizer ignore-type */ $condition));
Loading history...
1563 623
            if (isset($this->conditionClasses[$operator])) {
1564 537
                $className = $this->conditionClasses[$operator];
1565
            } else {
1566 95
                $className = 'yii\db\conditions\SimpleCondition';
1567
            }
1568
            /** @var ConditionInterface $className */
1569 623
            return $className::fromArrayDefinition($operator, $condition);
1570
        }
1571
1572
        // hash format: 'column1' => 'value1', 'column2' => 'value2', ...
1573 691
        return new HashCondition($condition);
1574
    }
1575
1576
    /**
1577
     * Creates a condition based on column-value pairs.
1578
     * @param array $condition the condition specification.
1579
     * @param array $params the binding parameters to be populated
1580
     * @return string the generated SQL expression
1581
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1582
     */
1583
    public function buildHashCondition($condition, &$params)
1584
    {
1585
        return $this->buildCondition(new HashCondition($condition), $params);
1586
    }
1587
1588
    /**
1589
     * Connects two or more SQL expressions with the `AND` or `OR` operator.
1590
     * @param string $operator the operator to use for connecting the given operands
1591
     * @param array $operands the SQL expressions to connect.
1592
     * @param array $params the binding parameters to be populated
1593
     * @return string the generated SQL expression
1594
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1595
     */
1596
    public function buildAndCondition($operator, $operands, &$params)
1597
    {
1598
        array_unshift($operands, $operator);
1599
        return $this->buildCondition($operands, $params);
1600
    }
1601
1602
    /**
1603
     * Inverts an SQL expressions with `NOT` operator.
1604
     * @param string $operator the operator to use for connecting the given operands
1605
     * @param array $operands the SQL expressions to connect.
1606
     * @param array $params the binding parameters to be populated
1607
     * @return string the generated SQL expression
1608
     * @throws InvalidArgumentException if wrong number of operands have been given.
1609
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1610
     */
1611
    public function buildNotCondition($operator, $operands, &$params)
1612
    {
1613
        array_unshift($operands, $operator);
1614
        return $this->buildCondition($operands, $params);
1615
    }
1616
1617
    /**
1618
     * Creates an SQL expressions with the `BETWEEN` operator.
1619
     * @param string $operator the operator to use (e.g. `BETWEEN` or `NOT BETWEEN`)
1620
     * @param array $operands the first operand is the column name. The second and third operands
1621
     * describe the interval that column value should be in.
1622
     * @param array $params the binding parameters to be populated
1623
     * @return string the generated SQL expression
1624
     * @throws InvalidArgumentException if wrong number of operands have been given.
1625
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1626
     */
1627
    public function buildBetweenCondition($operator, $operands, &$params)
1628
    {
1629
        array_unshift($operands, $operator);
1630
        return $this->buildCondition($operands, $params);
1631
    }
1632
1633
    /**
1634
     * Creates an SQL expressions with the `IN` operator.
1635
     * @param string $operator the operator to use (e.g. `IN` or `NOT IN`)
1636
     * @param array $operands the first operand is the column name. If it is an array
1637
     * a composite IN condition will be generated.
1638
     * The second operand is an array of values that column value should be among.
1639
     * If it is an empty array the generated expression will be a `false` value if
1640
     * operator is `IN` and empty if operator is `NOT IN`.
1641
     * @param array $params the binding parameters to be populated
1642
     * @return string the generated SQL expression
1643
     * @throws Exception if wrong number of operands have been given.
1644
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1645
     */
1646
    public function buildInCondition($operator, $operands, &$params)
1647
    {
1648
        array_unshift($operands, $operator);
1649
        return $this->buildCondition($operands, $params);
1650
    }
1651
1652
    /**
1653
     * Creates an SQL expressions with the `LIKE` operator.
1654
     * @param string $operator the operator to use (e.g. `LIKE`, `NOT LIKE`, `OR LIKE` or `OR NOT LIKE`)
1655
     * @param array $operands an array of two or three operands
1656
     *
1657
     * - The first operand is the column name.
1658
     * - The second operand is a single value or an array of values that column value
1659
     *   should be compared with. If it is an empty array the generated expression will
1660
     *   be a `false` value if operator is `LIKE` or `OR LIKE`, and empty if operator
1661
     *   is `NOT LIKE` or `OR NOT LIKE`.
1662
     * - An optional third operand can also be provided to specify how to escape special characters
1663
     *   in the value(s). The operand should be an array of mappings from the special characters to their
1664
     *   escaped counterparts. If this operand is not provided, a default escape mapping will be used.
1665
     *   You may use `false` or an empty array to indicate the values are already escaped and no escape
1666
     *   should be applied. Note that when using an escape mapping (or the third operand is not provided),
1667
     *   the values will be automatically enclosed within a pair of percentage characters.
1668
     * @param array $params the binding parameters to be populated
1669
     * @return string the generated SQL expression
1670
     * @throws InvalidArgumentException if wrong number of operands have been given.
1671
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1672
     */
1673
    public function buildLikeCondition($operator, $operands, &$params)
1674
    {
1675
        array_unshift($operands, $operator);
1676
        return $this->buildCondition($operands, $params);
1677
    }
1678
1679
    /**
1680
     * Creates an SQL expressions with the `EXISTS` operator.
1681
     * @param string $operator the operator to use (e.g. `EXISTS` or `NOT EXISTS`)
1682
     * @param array $operands contains only one element which is a [[Query]] object representing the sub-query.
1683
     * @param array $params the binding parameters to be populated
1684
     * @return string the generated SQL expression
1685
     * @throws InvalidArgumentException if the operand is not a [[Query]] object.
1686
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1687
     */
1688
    public function buildExistsCondition($operator, $operands, &$params)
1689
    {
1690
        array_unshift($operands, $operator);
1691
        return $this->buildCondition($operands, $params);
1692
    }
1693
1694
    /**
1695
     * Creates an SQL expressions like `"column" operator value`.
1696
     * @param string $operator the operator to use. Anything could be used e.g. `>`, `<=`, etc.
1697
     * @param array $operands contains two column names.
1698
     * @param array $params the binding parameters to be populated
1699
     * @return string the generated SQL expression
1700
     * @throws InvalidArgumentException if wrong number of operands have been given.
1701
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1702
     */
1703
    public function buildSimpleCondition($operator, $operands, &$params)
1704
    {
1705
        array_unshift($operands, $operator);
1706
        return $this->buildCondition($operands, $params);
1707
    }
1708
1709
    /**
1710
     * Creates a SELECT EXISTS() SQL statement.
1711
     * @param string $rawSql the subquery in a raw form to select from.
1712
     * @return string the SELECT EXISTS() SQL statement.
1713
     * @since 2.0.8
1714
     */
1715 70
    public function selectExists($rawSql)
1716
    {
1717 70
        return 'SELECT EXISTS(' . $rawSql . ')';
1718
    }
1719
1720
    /**
1721
     * Helper method to add $value to $params array using [[PARAM_PREFIX]].
1722
     *
1723
     * @param string|null $value
1724
     * @param array $params passed by reference
1725
     * @return string the placeholder name in $params array
1726
     *
1727
     * @since 2.0.14
1728
     */
1729 1083
    public function bindParam($value, &$params)
1730
    {
1731 1083
        $phName = self::PARAM_PREFIX . count($params);
1732 1083
        $params[$phName] = $value;
1733
1734 1083
        return $phName;
1735
    }
1736
1737
    /**
1738
     * Extracts table alias if there is one or returns false
1739
     * @param $table
1740
     * @return bool|array
1741
     * @since 2.0.24
1742
     */
1743 871
    protected function extractAlias($table)
1744
    {
1745 871
        if (preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $table, $matches)) {
1746 30
            return $matches;
1747
        }
1748
1749 847
        return false;
1750
    }
1751
}
1752