Passed
Pull Request — master (#20134)
by Wilmer
10:17 queued 29s
created

QueryBuilder::getTableUniqueColumnNames()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 35
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 6.002

Importance

Changes 0
Metric Value
cc 6
eloc 24
nc 7
nop 3
dl 0
loc 35
ccs 25
cts 26
cp 0.9615
crap 6.002
rs 8.9137
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 query condition to builder methods.
59
     * These methods are used by [[buildCondition]] to build SQL conditions from array syntax.
60
     * @deprecated since 2.0.14. Is not used, will be dropped in 2.1.0.
61
     */
62
    protected $conditionBuilders = [];
63
    /**
64
     * @var array map of condition aliases to condition classes. For example:
65
     *
66
     * ```php
67
     * return [
68
     *     'LIKE' => yii\db\condition\LikeCondition::class,
69
     * ];
70
     * ```
71
     *
72
     * This property is used by [[createConditionFromArray]] method.
73
     * See default condition classes list in [[defaultConditionClasses()]] method.
74
     *
75
     * In case you want to add custom conditions support, use the [[setConditionClasses()]] method.
76
     *
77
     * @see setConditionClasses()
78
     * @see defaultConditionClasses()
79
     * @since 2.0.14
80
     */
81
    protected $conditionClasses = [];
82
    /**
83
     * @var string[]|ExpressionBuilderInterface[] maps expression class to expression builder class.
84
     * For example:
85
     *
86
     * ```php
87
     * [
88
     *    yii\db\Expression::class => yii\db\ExpressionBuilder::class
89
     * ]
90
     * ```
91
     * This property is mainly used by [[buildExpression()]] to build SQL expressions form expression objects.
92
     * See default values in [[defaultExpressionBuilders()]] method.
93
     *
94
     *
95
     * To override existing builders or add custom, use [[setExpressionBuilder()]] method. New items will be added
96
     * to the end of this array.
97
     *
98
     * To find a builder, [[buildExpression()]] will check the expression class for its exact presence in this map.
99
     * In case it is NOT present, the array will be iterated in reverse direction, checking whether the expression
100
     * extends the class, defined in this map.
101
     *
102
     * @see setExpressionBuilders()
103
     * @see defaultExpressionBuilders()
104
     * @since 2.0.14
105
     */
106
    protected $expressionBuilders = [];
107
108
109
    /**
110
     * Constructor.
111
     * @param Connection $connection the database connection.
112
     * @param array $config name-value pairs that will be used to initialize the object properties
113
     */
114 1755
    public function __construct($connection, $config = [])
115
    {
116 1755
        $this->db = $connection;
117 1755
        parent::__construct($config);
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123 1755
    public function init()
124
    {
125 1755
        parent::init();
126
127 1755
        $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...
128 1755
        $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...
129
    }
130
131
    /**
132
     * Contains array of default condition classes. Extend this method, if you want to change
133
     * default condition classes for the query builder. See [[conditionClasses]] docs for details.
134
     *
135
     * @return array
136
     * @see conditionClasses
137
     * @since 2.0.14
138
     */
139 1755
    protected function defaultConditionClasses()
140
    {
141 1755
        return [
142 1755
            'NOT' => 'yii\db\conditions\NotCondition',
143 1755
            'AND' => 'yii\db\conditions\AndCondition',
144 1755
            'OR' => 'yii\db\conditions\OrCondition',
145 1755
            'BETWEEN' => 'yii\db\conditions\BetweenCondition',
146 1755
            'NOT BETWEEN' => 'yii\db\conditions\BetweenCondition',
147 1755
            'IN' => 'yii\db\conditions\InCondition',
148 1755
            'NOT IN' => 'yii\db\conditions\InCondition',
149 1755
            'LIKE' => 'yii\db\conditions\LikeCondition',
150 1755
            'NOT LIKE' => 'yii\db\conditions\LikeCondition',
151 1755
            'OR LIKE' => 'yii\db\conditions\LikeCondition',
152 1755
            'OR NOT LIKE' => 'yii\db\conditions\LikeCondition',
153 1755
            'EXISTS' => 'yii\db\conditions\ExistsCondition',
154 1755
            'NOT EXISTS' => 'yii\db\conditions\ExistsCondition',
155 1755
        ];
156
    }
157
158
    /**
159
     * Contains array of default expression builders. Extend this method and override it, if you want to change
160
     * default expression builders for this query builder. See [[expressionBuilders]] docs for details.
161
     *
162
     * @return array
163
     * @see expressionBuilders
164
     * @since 2.0.14
165
     */
166 1755
    protected function defaultExpressionBuilders()
167
    {
168 1755
        return [
169 1755
            'yii\db\Query' => 'yii\db\QueryExpressionBuilder',
170 1755
            'yii\db\PdoValue' => 'yii\db\PdoValueBuilder',
171 1755
            'yii\db\Expression' => 'yii\db\ExpressionBuilder',
172 1755
            'yii\db\conditions\ConjunctionCondition' => 'yii\db\conditions\ConjunctionConditionBuilder',
173 1755
            'yii\db\conditions\NotCondition' => 'yii\db\conditions\NotConditionBuilder',
174 1755
            'yii\db\conditions\AndCondition' => 'yii\db\conditions\ConjunctionConditionBuilder',
175 1755
            'yii\db\conditions\OrCondition' => 'yii\db\conditions\ConjunctionConditionBuilder',
176 1755
            'yii\db\conditions\BetweenCondition' => 'yii\db\conditions\BetweenConditionBuilder',
177 1755
            'yii\db\conditions\InCondition' => 'yii\db\conditions\InConditionBuilder',
178 1755
            'yii\db\conditions\LikeCondition' => 'yii\db\conditions\LikeConditionBuilder',
179 1755
            'yii\db\conditions\ExistsCondition' => 'yii\db\conditions\ExistsConditionBuilder',
180 1755
            'yii\db\conditions\SimpleCondition' => 'yii\db\conditions\SimpleConditionBuilder',
181 1755
            'yii\db\conditions\HashCondition' => 'yii\db\conditions\HashConditionBuilder',
182 1755
            'yii\db\conditions\BetweenColumnsCondition' => 'yii\db\conditions\BetweenColumnsConditionBuilder',
183 1755
        ];
184
    }
185
186
    /**
187
     * Setter for [[expressionBuilders]] property.
188
     *
189
     * @param string[] $builders array of builders that should be merged with the pre-defined ones
190
     * in [[expressionBuilders]] property.
191
     * @since 2.0.14
192
     * @see expressionBuilders
193
     */
194 4
    public function setExpressionBuilders($builders)
195
    {
196 4
        $this->expressionBuilders = array_merge($this->expressionBuilders, $builders);
0 ignored issues
show
introduced by
The property expressionBuilders is declared write-only in yii\db\QueryBuilder.
Loading history...
197
    }
198
199
    /**
200
     * Setter for [[conditionClasses]] property.
201
     *
202
     * @param string[] $classes map of condition aliases to condition classes. For example:
203
     *
204
     * ```php
205
     * ['LIKE' => yii\db\condition\LikeCondition::class]
206
     * ```
207
     *
208
     * @since 2.0.14.2
209
     * @see conditionClasses
210
     */
211
    public function setConditionClasses($classes)
212
    {
213
        $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...
214
    }
215
216
    /**
217
     * Generates a SELECT SQL statement from a [[Query]] object.
218
     *
219
     * @param Query $query the [[Query]] object from which the SQL statement will be generated.
220
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will
221
     * be included in the result with the additional parameters generated during the query building process.
222
     * @return array the generated SQL statement (the first array element) and the corresponding
223
     * parameters to be bound to the SQL statement (the second array element). The parameters returned
224
     * include those provided in `$params`.
225
     */
226 985
    public function build($query, $params = [])
227
    {
228 985
        $query = $query->prepare($this);
229
230 985
        $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

230
        $params = empty($params) ? $query->params : array_merge($params, /** @scrutinizer ignore-type */ $query->params);
Loading history...
231
232 985
        $clauses = [
233 985
            $this->buildSelect($query->select, $params, $query->distinct, $query->selectOption),
234 985
            $this->buildFrom($query->from, $params),
235 985
            $this->buildJoin($query->join, $params),
236 985
            $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

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

238
            $this->buildHaving(/** @scrutinizer ignore-type */ $query->having, $params),
Loading history...
239 985
        ];
240
241 985
        $sql = implode($this->separator, array_filter($clauses));
242 985
        $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

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

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

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

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

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

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

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

589
        $constraints = array_merge($constraints, $schema->/** @scrutinizer ignore-call */ getTableUniques($name));
Loading history...
590
        // Remove duplicates
591 107
        $constraints = array_combine(array_map(function (Constraint $constraint) {
592 107
            $columns = $constraint->columnNames;
593 107
            sort($columns, SORT_STRING);
0 ignored issues
show
Bug introduced by
It seems like $columns can also be of type null; however, parameter $array of sort() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

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

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

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

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

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

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

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

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

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

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

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