Completed
Push — master ( 1500e7...dc452b )
by Dmitry
63:45 queued 60:13
created

QueryBuilder::buildCondition()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 8
cts 8
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 8
nc 5
nop 2
crap 4
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use yii\base\InvalidArgumentException;
11
use yii\base\NotSupportedException;
12
use yii\db\conditions\ConditionInterface;
13
use yii\db\conditions\HashCondition;
14
use yii\helpers\StringHelper;
15
16
/**
17
 * QueryBuilder builds a SELECT SQL statement based on the specification given as a [[Query]] object.
18
 *
19
 * SQL statements are created from [[Query]] objects using the [[build()]]-method.
20
 *
21
 * QueryBuilder is also used by [[Command]] to build SQL statements such as INSERT, UPDATE, DELETE, CREATE TABLE.
22
 *
23
 * For more details and usage information on QueryBuilder, see the [guide article on query builders](guide:db-query-builder).
24
 *
25
 * @property string[] $expressionBuilders Array of builders that should be merged with the pre-defined ones
26
 * in [[expressionBuilders]] property. This property is write-only.
27
 *
28
 * @author Qiang Xue <[email protected]>
29
 * @since 2.0
30
 */
31
class QueryBuilder extends \yii\base\BaseObject
32
{
33
    /**
34
     * The prefix for automatically generated query binding parameters.
35
     */
36
    const PARAM_PREFIX = ':qp';
37
38
    /**
39
     * @var Connection the database connection.
40
     */
41
    public $db;
42
    /**
43
     * @var string the separator between different fragments of a SQL statement.
44
     * Defaults to an empty space. This is mainly used by [[build()]] when generating a SQL statement.
45
     */
46
    public $separator = ' ';
47
    /**
48
     * @var array the abstract column types mapped to physical column types.
49
     * This is mainly used to support creating/modifying tables using DB-independent data type specifications.
50
     * Child classes should override this property to declare supported type mappings.
51
     */
52
    public $typeMap = [];
53
54
    /**
55
     * @var array map of query condition to builder methods.
56
     * These methods are used by [[buildCondition]] to build SQL conditions from array syntax.
57
     * @deprecated since 2.0.14. Is not used, will be dropped in 2.1.0.
58
     */
59
    protected $conditionBuilders = [];
60
    /**
61
     * @var array map of condition aliases to condition classes. For example:
62
     *
63
     * ```php
64
     * return [
65
     *     'LIKE' => yii\db\condition\LikeCondition::class,
66
     * ];
67
     * ```
68
     *
69
     * This property is used by [[createConditionFromArray]] method.
70
     * See default condition classes list in [[defaultConditionClasses()]] method.
71
     *
72
     * In case you want to add custom conditions support, use the [[setConditionClasses()]] method.
73
     *
74
     * @see setConditonClasses()
75
     * @see defaultConditionClasses()
76
     * @since 2.0.14
77
     */
78
    protected $conditionClasses = [];
79
    /**
80
     * @var string[]|ExpressionBuilderInterface[] maps expression class to expression builder class.
81
     * For example:
82
     *
83
     * ```php
84
     * [
85
     *    yii\db\Expression::class => yii\db\ExpressionBuilder::class
86
     * ]
87
     * ```
88
     * This property is mainly used by [[buildExpression()]] to build SQL expressions form expression objects.
89
     * See default values in [[defaultExpressionBuilders()]] method.
90
     *
91
     *
92
     * To override existing builders or add custom, use [[setExpressionBuilder()]] method. New items will be added
93
     * to the end of this array.
94
     *
95
     * To find a builder, [[buildExpression()]] will check the expression class for its exact presence in this map.
96
     * In case it is NOT present, the array will be iterated in reverse direction, checking whether the expression
97
     * extends the class, defined in this map.
98
     *
99
     * @see setExpressionBuilders()
100
     * @see defaultExpressionBuilders()
101
     * @since 2.0.14
102
     */
103
    protected $expressionBuilders = [];
104
105
106
    /**
107
     * Constructor.
108
     * @param Connection $connection the database connection.
109
     * @param array $config name-value pairs that will be used to initialize the object properties
110
     */
111 1438
    public function __construct($connection, $config = [])
112
    {
113 1438
        $this->db = $connection;
114 1438
        parent::__construct($config);
115 1438
    }
116
117
    /**
118
     * {@inheritdoc}
119
     */
120 1438
    public function init()
121
    {
122 1438
        parent::init();
123
124 1438
        $this->expressionBuilders = array_merge($this->defaultExpressionBuilders(), $this->expressionBuilders);
0 ignored issues
show
Documentation Bug introduced by
It seems like array_merge($this->defau...is->expressionBuilders) of type array<string|integer,str...nsCondition":"string"}> is incompatible with the declared type array<integer,string|obj...ssionBuilderInterface>> of property $expressionBuilders.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
125 1438
        $this->conditionClasses = array_merge($this->defaultConditionClasses(), $this->conditionClasses);
126 1438
    }
127
128
    /**
129
     * Contains array of default condition classes. Extend this method, if you want to change
130
     * default condition classes for the query builder. See [[conditionClasses]] docs for details.
131
     *
132
     * @return array
133
     * @see conditionClasses
134
     * @since 2.0.14
135
     */
136 1438
    protected function defaultConditionClasses()
137
    {
138
        return [
139 1438
            'NOT' => 'yii\db\conditions\NotCondition',
140
            'AND' => 'yii\db\conditions\AndCondition',
141
            'OR' => 'yii\db\conditions\OrCondition',
142
            'BETWEEN' => 'yii\db\conditions\BetweenCondition',
143
            'NOT BETWEEN' => 'yii\db\conditions\BetweenCondition',
144
            'IN' => 'yii\db\conditions\InCondition',
145
            'NOT IN' => 'yii\db\conditions\InCondition',
146
            'LIKE' => 'yii\db\conditions\LikeCondition',
147
            'NOT LIKE' => 'yii\db\conditions\LikeCondition',
148
            'OR LIKE' => 'yii\db\conditions\LikeCondition',
149
            'OR NOT LIKE' => 'yii\db\conditions\LikeCondition',
150
            'EXISTS' => 'yii\db\conditions\ExistsCondition',
151
            'NOT EXISTS' => 'yii\db\conditions\ExistsCondition',
152
        ];
153
    }
154
155
    /**
156
     * Contains array of default expression builders. Extend this method and override it, if you want to change
157
     * default expression builders for this query builder. See [[expressionBuilders]] docs for details.
158
     *
159
     * @return array
160
     * @see $expressionBuilders
161
     * @since 2.0.14
162
     */
163 1438
    protected function defaultExpressionBuilders()
164
    {
165
        return [
166 1438
            'yii\db\Query' => 'yii\db\QueryExpressionBuilder',
167
            'yii\db\PdoValue' => 'yii\db\PdoValueBuilder',
168
            'yii\db\Expression' => 'yii\db\ExpressionBuilder',
169
            'yii\db\conditions\ConjunctionCondition' => 'yii\db\conditions\ConjunctionConditionBuilder',
170
            'yii\db\conditions\NotCondition' => 'yii\db\conditions\NotConditionBuilder',
171
            'yii\db\conditions\AndCondition' => 'yii\db\conditions\ConjunctionConditionBuilder',
172
            'yii\db\conditions\OrCondition' => 'yii\db\conditions\ConjunctionConditionBuilder',
173
            'yii\db\conditions\BetweenCondition' => 'yii\db\conditions\BetweenConditionBuilder',
174
            'yii\db\conditions\InCondition' => 'yii\db\conditions\InConditionBuilder',
175
            'yii\db\conditions\LikeCondition' => 'yii\db\conditions\LikeConditionBuilder',
176
            'yii\db\conditions\ExistsCondition' => 'yii\db\conditions\ExistsConditionBuilder',
177
            'yii\db\conditions\SimpleCondition' => 'yii\db\conditions\SimpleConditionBuilder',
178
            'yii\db\conditions\HashCondition' => 'yii\db\conditions\HashConditionBuilder',
179
            'yii\db\conditions\BetweenColumnsCondition' => 'yii\db\conditions\BetweenColumnsConditionBuilder',
180
        ];
181
    }
182
183
    /**
184
     * Setter for [[expressionBuilders]] property.
185
     *
186
     * @param string[] $builders array of builders that should be merged with the pre-defined ones
187
     * in [[expressionBuilders]] property.
188
     * @since 2.0.14
189
     * @see expressionBuilders
190
     */
191
    public function setExpressionBuilders($builders)
192
    {
193
        $this->expressionBuilders = array_merge($this->expressionBuilders, $builders);
194
    }
195
196
    /**
197
     * Generates a SELECT SQL statement from a [[Query]] object.
198
     *
199
     * @param Query $query the [[Query]] object from which the SQL statement will be generated.
200
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will
201
     * be included in the result with the additional parameters generated during the query building process.
202
     * @return array the generated SQL statement (the first array element) and the corresponding
203
     * parameters to be bound to the SQL statement (the second array element). The parameters returned
204
     * include those provided in `$params`.
205
     */
206 819
    public function build($query, $params = [])
207
    {
208 819
        $query = $query->prepare($this);
209
210 819
        $params = empty($params) ? $query->params : array_merge($params, $query->params);
211
212
        $clauses = [
213 819
            $this->buildSelect($query->select, $params, $query->distinct, $query->selectOption),
214 819
            $this->buildFrom($query->from, $params),
215 819
            $this->buildJoin($query->join, $params),
216 819
            $this->buildWhere($query->where, $params),
217 819
            $this->buildGroupBy($query->groupBy),
218 819
            $this->buildHaving($query->having, $params),
219
        ];
220
221 819
        $sql = implode($this->separator, array_filter($clauses));
222 819
        $sql = $this->buildOrderByAndLimit($sql, $query->orderBy, $query->limit, $query->offset);
223
224 819
        if (!empty($query->orderBy)) {
225 108
            foreach ($query->orderBy as $expression) {
226 108
                if ($expression instanceof ExpressionInterface) {
227 108
                    $this->buildExpression($expression, $params);
228
                }
229
            }
230
        }
231 819
        if (!empty($query->groupBy)) {
232 18
            foreach ($query->groupBy as $expression) {
233 18
                if ($expression instanceof ExpressionInterface) {
234 18
                    $this->buildExpression($expression, $params);
235
                }
236
            }
237
        }
238
239 819
        $union = $this->buildUnion($query->union, $params);
240 819
        if ($union !== '') {
241 8
            $sql = "($sql){$this->separator}$union";
242
        }
243
244 819
        return [$sql, $params];
245
    }
246
247
    /**
248
     * Builds given $expression
249
     *
250
     * @param ExpressionInterface $expression the expression to be built
251
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will
252
     * be included in the result with the additional parameters generated during the expression building process.
253
     * @return string the SQL statement that will not be neither quoted nor encoded before passing to DBMS
254
     * @see ExpressionInterface
255
     * @see ExpressionBuilderInterface
256
     * @see expressionBuilders
257
     * @since 2.0.14
258
     * @throws InvalidArgumentException when $expression building is not supported by this QueryBuilder.
259
     */
260 1066
    public function buildExpression(ExpressionInterface $expression, &$params = [])
261
    {
262 1066
        $builder = $this->getExpressionBuilder($expression);
263
264 1066
        return $builder->build($expression, $params);
265
    }
266
267
    /**
268
     * Gets object of [[ExpressionBuilderInterface]] that is suitable for $expression.
269
     * Uses [[expressionBuilders]] array to find a suitable builder class.
270
     *
271
     * @param ExpressionInterface $expression
272
     * @return ExpressionBuilderInterface
273
     * @see expressionBuilders
274
     * @since 2.0.14
275
     * @throws InvalidArgumentException when $expression building is not supported by this QueryBuilder.
276
     */
277 1066
    public function getExpressionBuilder(ExpressionInterface $expression)
278
    {
279 1066
        $className = get_class($expression);
280
281 1066
        if (!isset($this->expressionBuilders[$className])) {
282
            foreach (array_reverse($this->expressionBuilders) as $expressionClass => $builderClass) {
283
                if (is_subclass_of($expression, $expressionClass)) {
284
                    $this->expressionBuilders[$className] = $builderClass;
285
                    break;
286
                }
287
            }
288
289
            if (!isset($this->expressionBuilders[$className])) {
290
                throw new InvalidArgumentException('Expression of class ' . $className . ' can not be built in ' . get_class($this));
291
            }
292
        }
293
294 1066
        if ($this->expressionBuilders[$className] === __CLASS__) {
295
            return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (yii\db\QueryBuilder) is incompatible with the return type documented by yii\db\QueryBuilder::getExpressionBuilder of type yii\db\ExpressionBuilderInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
296
        }
297
298 1066
        if (!is_object($this->expressionBuilders[$className])) {
299 1022
            $this->expressionBuilders[$className] = new $this->expressionBuilders[$className]($this);
300
        }
301
302 1066
        return $this->expressionBuilders[$className];
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->expressionBuilders[$className]; of type string|object adds the type string to the return on line 302 which is incompatible with the return type documented by yii\db\QueryBuilder::getExpressionBuilder of type yii\db\ExpressionBuilderInterface.
Loading history...
303
    }
304
305
    /**
306
     * Creates an INSERT SQL statement.
307
     * For example,
308
     * ```php
309
     * $sql = $queryBuilder->insert('user', [
310
     *     'name' => 'Sam',
311
     *     'age' => 30,
312
     * ], $params);
313
     * ```
314
     * The method will properly escape the table and column names.
315
     *
316
     * @param string $table the table that new rows will be inserted into.
317
     * @param array|Query $columns the column data (name => value) to be inserted into the table or instance
318
     * of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement.
319
     * Passing of [[yii\db\Query|Query]] is available since version 2.0.11.
320
     * @param array $params the binding parameters that will be generated by this method.
321
     * They should be bound to the DB command later.
322
     * @return string the INSERT SQL
323
     */
324 533
    public function insert($table, $columns, &$params)
325
    {
326 533
        list($names, $placeholders, $values, $params) = $this->prepareInsertValues($table, $columns, $params);
327 524
        return 'INSERT INTO ' . $this->db->quoteTableName($table)
328 524
            . (!empty($names) ? ' (' . implode(', ', $names) . ')' : '')
329 524
            . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : $values);
330
    }
331
332
    /**
333
     * Prepares a `VALUES` part for an `INSERT` SQL statement.
334
     *
335
     * @param string $table the table that new rows will be inserted into.
336
     * @param array|Query $columns the column data (name => value) to be inserted into the table or instance
337
     * of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement.
338
     * @param array $params the binding parameters that will be generated by this method.
339
     * They should be bound to the DB command later.
340
     * @return array array of column names, placeholders, values and params.
341
     * @since 2.0.14
342
     */
343 547
    protected function prepareInsertValues($table, $columns, $params = [])
344
    {
345 547
        $schema = $this->db->getSchema();
346 547
        $tableSchema = $schema->getTableSchema($table);
347 547
        $columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
348 547
        $names = [];
349 547
        $placeholders = [];
350 547
        $values = ' DEFAULT VALUES';
351 547
        if ($columns instanceof Query) {
352 42
            list($names, $values, $params) = $this->prepareInsertSelectSubQuery($columns, $schema, $params);
353
        } else {
354 511
            foreach ($columns as $name => $value) {
355 507
                $names[] = $schema->quoteColumnName($name);
356 507
                $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
357
358 507
                if ($value instanceof ExpressionInterface) {
359 117
                    $placeholders[] = $this->buildExpression($value, $params);
360 500
                } elseif ($value instanceof \yii\db\Query) {
361
                    list($sql, $params) = $this->build($value, $params);
362
                    $placeholders[] = "($sql)";
363
                } else {
364 507
                    $placeholders[] = $this->bindParam($value, $params);
365
                }
366
            }
367
        }
368 538
        return [$names, $placeholders, $values, $params];
369
    }
370
371
    /**
372
     * Prepare select-subquery and field names for INSERT INTO ... SELECT SQL statement.
373
     *
374
     * @param Query $columns Object, which represents select query.
375
     * @param \yii\db\Schema $schema Schema object to quote column name.
376
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will
377
     * be included in the result with the additional parameters generated during the query building process.
378
     * @return array array of column names, values and params.
379
     * @throws InvalidArgumentException if query's select does not contain named parameters only.
380
     * @since 2.0.11
381
     */
382 42
    protected function prepareInsertSelectSubQuery($columns, $schema, $params = [])
383
    {
384 42
        if (!is_array($columns->select) || empty($columns->select) || in_array('*', $columns->select)) {
385 9
            throw new InvalidArgumentException('Expected select query object with enumerated (named) parameters');
386
        }
387
388 33
        list($values, $params) = $this->build($columns, $params);
389 33
        $names = [];
390 33
        $values = ' ' . $values;
391 33
        foreach ($columns->select as $title => $field) {
392 33
            if (is_string($title)) {
393 27
                $names[] = $schema->quoteColumnName($title);
394 24
            } elseif (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $field, $matches)) {
395 3
                $names[] = $schema->quoteColumnName($matches[2]);
396
            } else {
397 33
                $names[] = $schema->quoteColumnName($field);
398
            }
399
        }
400
401 33
        return [$names, $values, $params];
402
    }
403
404
    /**
405
     * Generates a batch INSERT SQL statement.
406
     *
407
     * For example,
408
     *
409
     * ```php
410
     * $sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
411
     *     ['Tom', 30],
412
     *     ['Jane', 20],
413
     *     ['Linda', 25],
414
     * ]);
415
     * ```
416
     *
417
     * Note that the values in each row must match the corresponding column names.
418
     *
419
     * The method will properly escape the column names, and quote the values to be inserted.
420
     *
421
     * @param string $table the table that new rows will be inserted into.
422
     * @param array $columns the column names
423
     * @param array|\Generator $rows the rows to be batch inserted into the table
424
     * @param array $params the binding parameters. This parameter exists since 2.0.14
425
     * @return string the batch INSERT SQL statement
426
     */
427 27
    public function batchInsert($table, $columns, $rows, &$params = [])
428
    {
429 27
        if (empty($rows)) {
430 2
            return '';
431
        }
432
433 26
        $schema = $this->db->getSchema();
434 26
        if (($tableSchema = $schema->getTableSchema($table)) !== null) {
435 20
            $columnSchemas = $tableSchema->columns;
436
        } else {
437 6
            $columnSchemas = [];
438
        }
439
440 26
        $values = [];
441 26
        foreach ($rows as $row) {
442 24
            $vs = [];
443 24
            foreach ($row as $i => $value) {
444 24
                if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
445 15
                    $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
446
                }
447 24
                if (is_string($value)) {
448 16
                    $value = $schema->quoteValue($value);
449 15
                } elseif (is_float($value)) {
450
                    // ensure type cast always has . as decimal separator in all locales
451 2
                    $value = StringHelper::floatToString($value);
452 15
                } elseif ($value === false) {
453 4
                    $value = 0;
454 15
                } elseif ($value === null) {
455 8
                    $value = 'NULL';
456 10
                } elseif ($value instanceof ExpressionInterface) {
457 6
                    $value = $this->buildExpression($value, $params);
458
                }
459 24
                $vs[] = $value;
460
            }
461 24
            $values[] = '(' . implode(', ', $vs) . ')';
462
        }
463 26
        if (empty($values)) {
464 2
            return '';
465
        }
466
467 24
        foreach ($columns as $i => $name) {
468 22
            $columns[$i] = $schema->quoteColumnName($name);
469
        }
470
471 24
        return 'INSERT INTO ' . $schema->quoteTableName($table)
472 24
        . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
473
    }
474
475
    /**
476
     * Creates an SQL statement to insert rows into a database table if
477
     * they do not already exist (matching unique constraints),
478
     * or update them if they do.
479
     *
480
     * For example,
481
     *
482
     * ```php
483
     * $sql = $queryBuilder->upsert('pages', [
484
     *     'name' => 'Front page',
485
     *     'url' => 'http://example.com/', // url is unique
486
     *     'visits' => 0,
487
     * ], [
488
     *     'visits' => new \yii\db\Expression('visits + 1'),
489
     * ], $params);
490
     * ```
491
     *
492
     * The method will properly escape the table and column names.
493
     *
494
     * @param string $table the table that new rows will be inserted into/updated in.
495
     * @param array|Query $insertColumns the column data (name => value) to be inserted into the table or instance
496
     * of [[Query]] to perform `INSERT INTO ... SELECT` SQL statement.
497
     * @param array|bool $updateColumns the column data (name => value) to be updated if they already exist.
498
     * If `true` is passed, the column data will be updated to match the insert column data.
499
     * If `false` is passed, no update will be performed if the column data already exists.
500
     * @param array $params the binding parameters that will be generated by this method.
501
     * They should be bound to the DB command later.
502
     * @return string the resulting SQL.
503
     * @throws NotSupportedException if this is not supported by the underlying DBMS.
504
     * @since 2.0.14
505
     */
506
    public function upsert($table, $insertColumns, $updateColumns, &$params)
507
    {
508
        throw new NotSupportedException($this->db->getDriverName() . ' does not support upsert statements.');
509
    }
510
511
    /**
512
     * @param string $table
513
     * @param array|Query $insertColumns
514
     * @param array|bool $updateColumns
515
     * @param Constraint[] $constraints this parameter recieves a matched constraint list.
516
     * The constraints will be unique by their column names.
517
     * @return array
518
     * @since 2.0.14
519
     */
520 66
    protected function prepareUpsertColumns($table, $insertColumns, $updateColumns, &$constraints = [])
521
    {
522 66
        if ($insertColumns instanceof Query) {
523 24
            list($insertNames) = $this->prepareInsertSelectSubQuery($insertColumns, $this->db->getSchema());
524
        } else {
525 42
            $insertNames = array_map([$this->db, 'quoteColumnName'], array_keys($insertColumns));
526
        }
527 66
        $uniqueNames = $this->getTableUniqueColumnNames($table, $insertNames, $constraints);
528 66
        $uniqueNames = array_map([$this->db, 'quoteColumnName'], $uniqueNames);
529 66
        if ($updateColumns !== true) {
530 36
            return [$uniqueNames, $insertNames, null];
531
        }
532
533 30
        return [$uniqueNames, $insertNames, array_diff($insertNames, $uniqueNames)];
534
    }
535
536
    /**
537
     * Returns all column names belonging to constraints enforcing uniqueness (`PRIMARY KEY`, `UNIQUE INDEX`, etc.)
538
     * for the named table removing constraints which did not cover the specified column list.
539
     * The column list will be unique by column names.
540
     *
541
     * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
542
     * @param string[] $columns source column list.
543
     * @param Constraint[] $constraints this parameter optionally recieves a matched constraint list.
544
     * The constraints will be unique by their column names.
545
     * @return string[] column list.
546
     */
547 66
    private function getTableUniqueColumnNames($name, $columns, &$constraints = [])
548
    {
549 66
        $schema = $this->db->getSchema();
550 66
        if (!$schema instanceof ConstraintFinderInterface) {
551
            return [];
552
        }
553
554 66
        $constraints = [];
555 66
        $primaryKey = $schema->getTablePrimaryKey($name);
556 66
        if ($primaryKey !== null) {
557 49
            $constraints[] = $primaryKey;
558
        }
559 66
        foreach ($schema->getTableIndexes($name) as $constraint) {
560 66
            if ($constraint->isUnique) {
561 66
                $constraints[] = $constraint;
562
            }
563
        }
564 66
        $constraints = array_merge($constraints, $schema->getTableUniques($name));
565
        // Remove duplicates
566
        $constraints = array_combine(array_map(function (Constraint $constraint) {
567 66
            $columns = $constraint->columnNames;
568 66
            sort($columns, SORT_STRING);
569 66
            return json_encode($columns);
570 66
        }, $constraints), $constraints);
571 66
        $columnNames = [];
572
        // Remove all constraints which do not cover the specified column list
573
        $constraints = array_values(array_filter($constraints, function (Constraint $constraint) use ($schema, $columns, &$columnNames) {
574 66
            $constraintColumnNames = array_map([$schema, 'quoteColumnName'], $constraint->columnNames);
575 66
            $result = !array_diff($constraintColumnNames, $columns);
576 66
            if ($result) {
577 57
                $columnNames = array_merge($columnNames, $constraintColumnNames);
578
            }
579 66
            return $result;
580 66
        }));
581 66
        return array_unique($columnNames);
582
    }
583
584
    /**
585
     * Creates an UPDATE SQL statement.
586
     *
587
     * For example,
588
     *
589
     * ```php
590
     * $params = [];
591
     * $sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params);
592
     * ```
593
     *
594
     * The method will properly escape the table and column names.
595
     *
596
     * @param string $table the table to be updated.
597
     * @param array $columns the column data (name => value) to be updated.
598
     * @param array|string $condition the condition that will be put in the WHERE part. Please
599
     * refer to [[Query::where()]] on how to specify condition.
600
     * @param array $params the binding parameters that will be modified by this method
601
     * so that they can be bound to the DB command later.
602
     * @return string the UPDATE SQL
603
     */
604 134
    public function update($table, $columns, $condition, &$params)
605
    {
606 134
        list($lines, $params) = $this->prepareUpdateSets($table, $columns, $params);
607 134
        $sql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $lines);
608 134
        $where = $this->buildWhere($condition, $params);
609 134
        return $where === '' ? $sql : $sql . ' ' . $where;
610
    }
611
612
    /**
613
     * Prepares a `SET` parts for an `UPDATE` SQL statement.
614
     * @param string $table the table to be updated.
615
     * @param array $columns the column data (name => value) to be updated.
616
     * @param array $params the binding parameters that will be modified by this method
617
     * so that they can be bound to the DB command later.
618
     * @return array an array `SET` parts for an `UPDATE` SQL statement (the first array element) and params (the second array element).
619
     * @since 2.0.14
620
     */
621 166
    protected function prepareUpdateSets($table, $columns, $params = [])
622
    {
623 166
        $tableSchema = $this->db->getTableSchema($table);
624 166
        $columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
625 166
        $sets = [];
626 166
        foreach ($columns as $name => $value) {
627
628 166
            $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
629 166
            if ($value instanceof ExpressionInterface) {
630 91
                $placeholder = $this->buildExpression($value, $params);
631
            } else {
632 125
                $placeholder = $this->bindParam($value, $params);
633
            }
634
635 166
            $sets[] = $this->db->quoteColumnName($name) . '=' . $placeholder;
636
        }
637 166
        return [$sets, $params];
638
    }
639
640
    /**
641
     * Creates a DELETE SQL statement.
642
     *
643
     * For example,
644
     *
645
     * ```php
646
     * $sql = $queryBuilder->delete('user', 'status = 0');
647
     * ```
648
     *
649
     * The method will properly escape the table and column names.
650
     *
651
     * @param string $table the table where the data will be deleted from.
652
     * @param array|string $condition the condition that will be put in the WHERE part. Please
653
     * refer to [[Query::where()]] on how to specify condition.
654
     * @param array $params the binding parameters that will be modified by this method
655
     * so that they can be bound to the DB command later.
656
     * @return string the DELETE SQL
657
     */
658 358
    public function delete($table, $condition, &$params)
659
    {
660 358
        $sql = 'DELETE FROM ' . $this->db->quoteTableName($table);
661 358
        $where = $this->buildWhere($condition, $params);
662
663 358
        return $where === '' ? $sql : $sql . ' ' . $where;
664
    }
665
666
    /**
667
     * Builds a SQL statement for creating a new DB table.
668
     *
669
     * The columns in the new  table should be specified as name-definition pairs (e.g. 'name' => 'string'),
670
     * where name stands for a column name which will be properly quoted by the method, and definition
671
     * stands for the column type which can contain an abstract DB type.
672
     * The [[getColumnType()]] method will be invoked to convert any abstract type into a physical one.
673
     *
674
     * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
675
     * inserted into the generated SQL.
676
     *
677
     * For example,
678
     *
679
     * ```php
680
     * $sql = $queryBuilder->createTable('user', [
681
     *  'id' => 'pk',
682
     *  'name' => 'string',
683
     *  'age' => 'integer',
684
     * ]);
685
     * ```
686
     *
687
     * @param string $table the name of the table to be created. The name will be properly quoted by the method.
688
     * @param array $columns the columns (name => definition) in the new table.
689
     * @param string $options additional SQL fragment that will be appended to the generated SQL.
690
     * @return string the SQL statement for creating a new DB table.
691
     */
692 137
    public function createTable($table, $columns, $options = null)
693
    {
694 137
        $cols = [];
695 137
        foreach ($columns as $name => $type) {
696 137
            if (is_string($name)) {
697 137
                $cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type);
698
            } else {
699 137
                $cols[] = "\t" . $type;
700
            }
701
        }
702 137
        $sql = 'CREATE TABLE ' . $this->db->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)";
703
704 137
        return $options === null ? $sql : $sql . ' ' . $options;
705
    }
706
707
    /**
708
     * Builds a SQL statement for renaming a DB table.
709
     * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
710
     * @param string $newName the new table name. The name will be properly quoted by the method.
711
     * @return string the SQL statement for renaming a DB table.
712
     */
713 1
    public function renameTable($oldName, $newName)
714
    {
715 1
        return 'RENAME TABLE ' . $this->db->quoteTableName($oldName) . ' TO ' . $this->db->quoteTableName($newName);
716
    }
717
718
    /**
719
     * Builds a SQL statement for dropping a DB table.
720
     * @param string $table the table to be dropped. The name will be properly quoted by the method.
721
     * @return string the SQL statement for dropping a DB table.
722
     */
723 39
    public function dropTable($table)
724
    {
725 39
        return 'DROP TABLE ' . $this->db->quoteTableName($table);
726
    }
727
728
    /**
729
     * Builds a SQL statement for adding a primary key constraint to an existing table.
730
     * @param string $name the name of the primary key constraint.
731
     * @param string $table the table that the primary key constraint will be added to.
732
     * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
733
     * @return string the SQL statement for adding a primary key constraint to an existing table.
734
     */
735 6
    public function addPrimaryKey($name, $table, $columns)
736
    {
737 6
        if (is_string($columns)) {
738 4
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
739
        }
740
741 6
        foreach ($columns as $i => $col) {
742 6
            $columns[$i] = $this->db->quoteColumnName($col);
743
        }
744
745 6
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
746 6
            . $this->db->quoteColumnName($name) . ' PRIMARY KEY ('
747 6
            . implode(', ', $columns) . ')';
748
    }
749
750
    /**
751
     * Builds a SQL statement for removing a primary key constraint to an existing table.
752
     * @param string $name the name of the primary key constraint to be removed.
753
     * @param string $table the table that the primary key constraint will be removed from.
754
     * @return string the SQL statement for removing a primary key constraint from an existing table.
755
     */
756 2
    public function dropPrimaryKey($name, $table)
757
    {
758 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
759 2
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
760
    }
761
762
    /**
763
     * Builds a SQL statement for truncating a DB table.
764
     * @param string $table the table to be truncated. The name will be properly quoted by the method.
765
     * @return string the SQL statement for truncating a DB table.
766
     */
767 11
    public function truncateTable($table)
768
    {
769 11
        return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table);
770
    }
771
772
    /**
773
     * Builds a SQL statement for adding a new DB column.
774
     * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
775
     * @param string $column the name of the new column. The name will be properly quoted by the method.
776
     * @param string $type the column type. The [[getColumnType()]] method will be invoked to convert abstract column type (if any)
777
     * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
778
     * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
779
     * @return string the SQL statement for adding a new column.
780
     */
781 4
    public function addColumn($table, $column, $type)
782
    {
783 4
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
784 4
            . ' ADD ' . $this->db->quoteColumnName($column) . ' '
785 4
            . $this->getColumnType($type);
786
    }
787
788
    /**
789
     * Builds a SQL statement for dropping a DB column.
790
     * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
791
     * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
792
     * @return string the SQL statement for dropping a DB column.
793
     */
794
    public function dropColumn($table, $column)
795
    {
796
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
797
            . ' DROP COLUMN ' . $this->db->quoteColumnName($column);
798
    }
799
800
    /**
801
     * Builds a SQL statement for renaming a column.
802
     * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
803
     * @param string $oldName the old name of the column. The name will be properly quoted by the method.
804
     * @param string $newName the new name of the column. The name will be properly quoted by the method.
805
     * @return string the SQL statement for renaming a DB column.
806
     */
807
    public function renameColumn($table, $oldName, $newName)
808
    {
809
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
810
            . ' RENAME COLUMN ' . $this->db->quoteColumnName($oldName)
811
            . ' TO ' . $this->db->quoteColumnName($newName);
812
    }
813
814
    /**
815
     * Builds a SQL statement for changing the definition of a column.
816
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
817
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
818
     * @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract
819
     * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
820
     * in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
821
     * will become 'varchar(255) not null'.
822
     * @return string the SQL statement for changing the definition of a column.
823
     */
824 1
    public function alterColumn($table, $column, $type)
825
    {
826 1
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
827 1
            . $this->db->quoteColumnName($column) . ' '
828 1
            . $this->db->quoteColumnName($column) . ' '
829 1
            . $this->getColumnType($type);
830
    }
831
832
    /**
833
     * Builds a SQL statement for adding a foreign key constraint to an existing table.
834
     * The method will properly quote the table and column names.
835
     * @param string $name the name of the foreign key constraint.
836
     * @param string $table the table that the foreign key constraint will be added to.
837
     * @param string|array $columns the name of the column to that the constraint will be added on.
838
     * If there are multiple columns, separate them with commas or use an array to represent them.
839
     * @param string $refTable the table that the foreign key references to.
840
     * @param string|array $refColumns the name of the column that the foreign key references to.
841
     * If there are multiple columns, separate them with commas or use an array to represent them.
842
     * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
843
     * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
844
     * @return string the SQL statement for adding a foreign key constraint to an existing table.
845
     */
846 8
    public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
847
    {
848 8
        $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
849 8
            . ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name)
850 8
            . ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
851 8
            . ' REFERENCES ' . $this->db->quoteTableName($refTable)
852 8
            . ' (' . $this->buildColumns($refColumns) . ')';
853 8
        if ($delete !== null) {
854 4
            $sql .= ' ON DELETE ' . $delete;
855
        }
856 8
        if ($update !== null) {
857 4
            $sql .= ' ON UPDATE ' . $update;
858
        }
859
860 8
        return $sql;
861
    }
862
863
    /**
864
     * Builds a SQL statement for dropping a foreign key constraint.
865
     * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
866
     * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
867
     * @return string the SQL statement for dropping a foreign key constraint.
868
     */
869 3
    public function dropForeignKey($name, $table)
870
    {
871 3
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
872 3
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
873
    }
874
875
    /**
876
     * Builds a SQL statement for creating a new index.
877
     * @param string $name the name of the index. The name will be properly quoted by the method.
878
     * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
879
     * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns,
880
     * separate them with commas or use an array to represent them. Each column name will be properly quoted
881
     * by the method, unless a parenthesis is found in the name.
882
     * @param bool $unique whether to add UNIQUE constraint on the created index.
883
     * @return string the SQL statement for creating a new index.
884
     */
885 6
    public function createIndex($name, $table, $columns, $unique = false)
886
    {
887 6
        return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
888 6
            . $this->db->quoteTableName($name) . ' ON '
889 6
            . $this->db->quoteTableName($table)
890 6
            . ' (' . $this->buildColumns($columns) . ')';
891
    }
892
893
    /**
894
     * Builds a SQL statement for dropping an index.
895
     * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
896
     * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
897
     * @return string the SQL statement for dropping an index.
898
     */
899 4
    public function dropIndex($name, $table)
900
    {
901 4
        return 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON ' . $this->db->quoteTableName($table);
902
    }
903
904
    /**
905
     * Creates a SQL command for adding an unique constraint to an existing table.
906
     * @param string $name the name of the unique constraint.
907
     * The name will be properly quoted by the method.
908
     * @param string $table the table that the unique constraint will be added to.
909
     * The name will be properly quoted by the method.
910
     * @param string|array $columns the name of the column to that the constraint will be added on.
911
     * If there are multiple columns, separate them with commas.
912
     * The name will be properly quoted by the method.
913
     * @return string the SQL statement for adding an unique constraint to an existing table.
914
     * @since 2.0.13
915
     */
916 6
    public function addUnique($name, $table, $columns)
917
    {
918 6
        if (is_string($columns)) {
919 4
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
920
        }
921 6
        foreach ($columns as $i => $col) {
922 6
            $columns[$i] = $this->db->quoteColumnName($col);
923
        }
924
925 6
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
926 6
            . $this->db->quoteColumnName($name) . ' UNIQUE ('
927 6
            . implode(', ', $columns) . ')';
928
    }
929
930
    /**
931
     * Creates a SQL command for dropping an unique constraint.
932
     * @param string $name the name of the unique constraint to be dropped.
933
     * The name will be properly quoted by the method.
934
     * @param string $table the table whose unique constraint is to be dropped.
935
     * The name will be properly quoted by the method.
936
     * @return string the SQL statement for dropping an unique constraint.
937
     * @since 2.0.13
938
     */
939 2
    public function dropUnique($name, $table)
940
    {
941 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
942 2
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
943
    }
944
945
    /**
946
     * Creates a SQL command for adding a check constraint to an existing table.
947
     * @param string $name the name of the check constraint.
948
     * The name will be properly quoted by the method.
949
     * @param string $table the table that the check constraint will be added to.
950
     * The name will be properly quoted by the method.
951
     * @param string $expression the SQL of the `CHECK` constraint.
952
     * @return string the SQL statement for adding a check constraint to an existing table.
953
     * @since 2.0.13
954
     */
955 2
    public function addCheck($name, $table, $expression)
956
    {
957 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
958 2
            . $this->db->quoteColumnName($name) . ' CHECK (' . $this->db->quoteSql($expression) . ')';
959
    }
960
961
    /**
962
     * Creates a SQL command for dropping a check constraint.
963
     * @param string $name the name of the check constraint to be dropped.
964
     * The name will be properly quoted by the method.
965
     * @param string $table the table whose check constraint is to be dropped.
966
     * The name will be properly quoted by the method.
967
     * @return string the SQL statement for dropping a check constraint.
968
     * @since 2.0.13
969
     */
970 2
    public function dropCheck($name, $table)
971
    {
972 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
973 2
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
974
    }
975
976
    /**
977
     * Creates a SQL command for adding a default value constraint to an existing table.
978
     * @param string $name the name of the default value constraint.
979
     * The name will be properly quoted by the method.
980
     * @param string $table the table that the default value constraint will be added to.
981
     * The name will be properly quoted by the method.
982
     * @param string $column the name of the column to that the constraint will be added on.
983
     * The name will be properly quoted by the method.
984
     * @param mixed $value default value.
985
     * @return string the SQL statement for adding a default value constraint to an existing table.
986
     * @throws NotSupportedException if this is not supported by the underlying DBMS.
987
     * @since 2.0.13
988
     */
989
    public function addDefaultValue($name, $table, $column, $value)
990
    {
991
        throw new NotSupportedException($this->db->getDriverName() . ' does not support adding default value constraints.');
992
    }
993
994
    /**
995
     * Creates a SQL command for dropping a default value constraint.
996
     * @param string $name the name of the default value constraint to be dropped.
997
     * The name will be properly quoted by the method.
998
     * @param string $table the table whose default value constraint is to be dropped.
999
     * The name will be properly quoted by the method.
1000
     * @return string the SQL statement for dropping a default value constraint.
1001
     * @throws NotSupportedException if this is not supported by the underlying DBMS.
1002
     * @since 2.0.13
1003
     */
1004
    public function dropDefaultValue($name, $table)
1005
    {
1006
        throw new NotSupportedException($this->db->getDriverName() . ' does not support dropping default value constraints.');
1007
    }
1008
1009
    /**
1010
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
1011
     * The sequence will be reset such that the primary key of the next new row inserted
1012
     * will have the specified value or 1.
1013
     * @param string $table the name of the table whose primary key sequence will be reset
1014
     * @param array|string $value the value for the primary key of the next new row inserted. If this is not set,
1015
     * the next new row's primary key will have a value 1.
1016
     * @return string the SQL statement for resetting sequence
1017
     * @throws NotSupportedException if this is not supported by the underlying DBMS
1018
     */
1019
    public function resetSequence($table, $value = null)
1020
    {
1021
        throw new NotSupportedException($this->db->getDriverName() . ' does not support resetting sequence.');
1022
    }
1023
1024
    /**
1025
     * Builds a SQL statement for enabling or disabling integrity check.
1026
     * @param bool $check whether to turn on or off the integrity check.
1027
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
1028
     * @param string $table the table name. Defaults to empty string, meaning that no table will be changed.
1029
     * @return string the SQL statement for checking integrity
1030
     * @throws NotSupportedException if this is not supported by the underlying DBMS
1031
     */
1032
    public function checkIntegrity($check = true, $schema = '', $table = '')
1033
    {
1034
        throw new NotSupportedException($this->db->getDriverName() . ' does not support enabling/disabling integrity check.');
1035
    }
1036
1037
    /**
1038
     * Builds a SQL command for adding comment to column.
1039
     *
1040
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
1041
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
1042
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
1043
     * @return string the SQL statement for adding comment on column
1044
     * @since 2.0.8
1045
     */
1046 2
    public function addCommentOnColumn($table, $column, $comment)
1047
    {
1048 2
        return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . ' IS ' . $this->db->quoteValue($comment);
1049
    }
1050
1051
    /**
1052
     * Builds a SQL command for adding comment to table.
1053
     *
1054
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
1055
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
1056
     * @return string the SQL statement for adding comment on table
1057
     * @since 2.0.8
1058
     */
1059 1
    public function addCommentOnTable($table, $comment)
1060
    {
1061 1
        return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS ' . $this->db->quoteValue($comment);
1062
    }
1063
1064
    /**
1065
     * Builds a SQL command for adding comment to column.
1066
     *
1067
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
1068
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
1069
     * @return string the SQL statement for adding comment on column
1070
     * @since 2.0.8
1071
     */
1072 2
    public function dropCommentFromColumn($table, $column)
1073
    {
1074 2
        return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . ' IS NULL';
1075
    }
1076
1077
    /**
1078
     * Builds a SQL command for adding comment to table.
1079
     *
1080
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
1081
     * @return string the SQL statement for adding comment on column
1082
     * @since 2.0.8
1083
     */
1084 1
    public function dropCommentFromTable($table)
1085
    {
1086 1
        return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS NULL';
1087
    }
1088
1089
    /**
1090
     * Creates a SQL View.
1091
     *
1092
     * @param string $viewName the name of the view to be created.
1093
     * @param string|Query $subQuery the select statement which defines the view.
1094
     * This can be either a string or a [[Query]] object.
1095
     * @return string the `CREATE VIEW` SQL statement.
1096
     * @since 2.0.14
1097
     */
1098 3
    public function createView($viewName, $subQuery)
1099
    {
1100 3
        if ($subQuery instanceof Query) {
1101 3
            list($rawQuery, $params) = $this->build($subQuery);
1102 3
            array_walk(
1103 3
                $params,
1104 3
                function(&$param) {
1105 3
                    $param = $this->db->quoteValue($param);
1106 3
                }
1107
            );
1108 3
            $subQuery = strtr($rawQuery, $params);
1109
        }
1110
1111 3
        return 'CREATE VIEW ' . $this->db->quoteTableName($viewName) . ' AS ' . $subQuery;
1112
    }
1113
1114
    /**
1115
     * Drops a SQL View.
1116
     *
1117
     * @param string $viewName the name of the view to be dropped.
1118
     * @return string the `DROP VIEW` SQL statement.
1119
     * @since 2.0.14
1120
     */
1121 3
    public function dropView($viewName)
1122
    {
1123 3
        return 'DROP VIEW ' . $this->db->quoteTableName($viewName);
1124
    }
1125
1126
    /**
1127
     * Converts an abstract column type into a physical column type.
1128
     *
1129
     * The conversion is done using the type map specified in [[typeMap]].
1130
     * The following abstract column types are supported (using MySQL as an example to explain the corresponding
1131
     * physical types):
1132
     *
1133
     * - `pk`: an auto-incremental primary key type, will be converted into "int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY"
1134
     * - `bigpk`: an auto-incremental primary key type, will be converted into "bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY"
1135
     * - `upk`: an unsigned auto-incremental primary key type, will be converted into "int(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY"
1136
     * - `char`: char type, will be converted into "char(1)"
1137
     * - `string`: string type, will be converted into "varchar(255)"
1138
     * - `text`: a long string type, will be converted into "text"
1139
     * - `smallint`: a small integer type, will be converted into "smallint(6)"
1140
     * - `integer`: integer type, will be converted into "int(11)"
1141
     * - `bigint`: a big integer type, will be converted into "bigint(20)"
1142
     * - `boolean`: boolean type, will be converted into "tinyint(1)"
1143
     * - `float``: float number type, will be converted into "float"
1144
     * - `decimal`: decimal number type, will be converted into "decimal"
1145
     * - `datetime`: datetime type, will be converted into "datetime"
1146
     * - `timestamp`: timestamp type, will be converted into "timestamp"
1147
     * - `time`: time type, will be converted into "time"
1148
     * - `date`: date type, will be converted into "date"
1149
     * - `money`: money type, will be converted into "decimal(19,4)"
1150
     * - `binary`: binary data type, will be converted into "blob"
1151
     *
1152
     * If the abstract type contains two or more parts separated by spaces (e.g. "string NOT NULL"), then only
1153
     * the first part will be converted, and the rest of the parts will be appended to the converted result.
1154
     * For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'.
1155
     *
1156
     * For some of the abstract types you can also specify a length or precision constraint
1157
     * by appending it in round brackets directly to the type.
1158
     * For example `string(32)` will be converted into "varchar(32)" on a MySQL database.
1159
     * If the underlying DBMS does not support these kind of constraints for a type it will
1160
     * be ignored.
1161
     *
1162
     * If a type cannot be found in [[typeMap]], it will be returned without any change.
1163
     * @param string|ColumnSchemaBuilder $type abstract column type
1164
     * @return string physical column type.
1165
     */
1166 141
    public function getColumnType($type)
1167
    {
1168 141
        if ($type instanceof ColumnSchemaBuilder) {
1169 33
            $type = $type->__toString();
1170
        }
1171
1172 141
        if (isset($this->typeMap[$type])) {
1173 128
            return $this->typeMap[$type];
1174 77
        } elseif (preg_match('/^(\w+)\((.+?)\)(.*)$/', $type, $matches)) {
1175 39
            if (isset($this->typeMap[$matches[1]])) {
1176 39
                return preg_replace('/\(.+\)/', '(' . $matches[2] . ')', $this->typeMap[$matches[1]]) . $matches[3];
1177
            }
1178 52
        } elseif (preg_match('/^(\w+)\s+/', $type, $matches)) {
1179 49
            if (isset($this->typeMap[$matches[1]])) {
1180 49
                return preg_replace('/^\w+/', $this->typeMap[$matches[1]], $type);
1181
            }
1182
        }
1183
1184 32
        return $type;
1185
    }
1186
1187
    /**
1188
     * @param array $columns
1189
     * @param array $params the binding parameters to be populated
1190
     * @param bool $distinct
1191
     * @param string $selectOption
1192
     * @return string the SELECT clause built from [[Query::$select]].
1193
     */
1194 1160
    public function buildSelect($columns, &$params, $distinct = false, $selectOption = null)
1195
    {
1196 1160
        $select = $distinct ? 'SELECT DISTINCT' : 'SELECT';
1197 1160
        if ($selectOption !== null) {
1198
            $select .= ' ' . $selectOption;
1199
        }
1200
1201 1160
        if (empty($columns)) {
1202 895
            return $select . ' *';
1203
        }
1204
1205 546
        foreach ($columns as $i => $column) {
1206 546
            if ($column instanceof ExpressionInterface) {
1207 42
                if (is_int($i)) {
1208 6
                    $columns[$i] = $this->buildExpression($column, $params);
1209
                } else {
1210 42
                    $columns[$i] = $this->buildExpression($column, $params) . ' AS ' . $this->db->quoteColumnName($i);
1211
                }
1212 537
            } elseif ($column instanceof Query) {
1213
                list($sql, $params) = $this->build($column, $params);
1214
                $columns[$i] = "($sql) AS " . $this->db->quoteColumnName($i);
1215 537
            } elseif (is_string($i)) {
1216 23
                if (strpos($column, '(') === false) {
1217 23
                    $column = $this->db->quoteColumnName($column);
1218
                }
1219 23
                $columns[$i] = "$column AS " . $this->db->quoteColumnName($i);
1220 532
            } elseif (strpos($column, '(') === false) {
1221 448
                if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $column, $matches)) {
1222 6
                    $columns[$i] = $this->db->quoteColumnName($matches[1]) . ' AS ' . $this->db->quoteColumnName($matches[2]);
1223
                } else {
1224 546
                    $columns[$i] = $this->db->quoteColumnName($column);
1225
                }
1226
            }
1227
        }
1228
1229 546
        return $select . ' ' . implode(', ', $columns);
1230
    }
1231
1232
    /**
1233
     * @param array $tables
1234
     * @param array $params the binding parameters to be populated
1235
     * @return string the FROM clause built from [[Query::$from]].
1236
     */
1237 1160
    public function buildFrom($tables, &$params)
1238
    {
1239 1160
        if (empty($tables)) {
1240 349
            return '';
1241
        }
1242
1243 848
        $tables = $this->quoteTableNames($tables, $params);
1244
1245 848
        return 'FROM ' . implode(', ', $tables);
1246
    }
1247
1248
    /**
1249
     * @param array $joins
1250
     * @param array $params the binding parameters to be populated
1251
     * @return string the JOIN clause built from [[Query::$join]].
1252
     * @throws Exception if the $joins parameter is not in proper format
1253
     */
1254 1160
    public function buildJoin($joins, &$params)
1255
    {
1256 1160
        if (empty($joins)) {
1257 1148
            return '';
1258
        }
1259
1260 54
        foreach ($joins as $i => $join) {
1261 54
            if (!is_array($join) || !isset($join[0], $join[1])) {
1262
                throw new Exception('A join clause must be specified as an array of join type, join table, and optionally join condition.');
1263
            }
1264
            // 0:join type, 1:join table, 2:on-condition (optional)
1265 54
            list($joinType, $table) = $join;
1266 54
            $tables = $this->quoteTableNames((array) $table, $params);
1267 54
            $table = reset($tables);
1268 54
            $joins[$i] = "$joinType $table";
1269 54
            if (isset($join[2])) {
1270 54
                $condition = $this->buildCondition($join[2], $params);
1271 54
                if ($condition !== '') {
1272 54
                    $joins[$i] .= ' ON ' . $condition;
1273
                }
1274
            }
1275
        }
1276
1277 54
        return implode($this->separator, $joins);
1278
    }
1279
1280
    /**
1281
     * Quotes table names passed.
1282
     *
1283
     * @param array $tables
1284
     * @param array $params
1285
     * @return array
1286
     */
1287 848
    private function quoteTableNames($tables, &$params)
1288
    {
1289 848
        foreach ($tables as $i => $table) {
1290 848
            if ($table instanceof Query) {
1291 10
                list($sql, $params) = $this->build($table, $params);
1292 10
                $tables[$i] = "($sql) " . $this->db->quoteTableName($i);
1293 848
            } elseif (is_string($i)) {
1294 79
                if (strpos($table, '(') === false) {
1295 70
                    $table = $this->db->quoteTableName($table);
1296
                }
1297 79
                $tables[$i] = "$table " . $this->db->quoteTableName($i);
1298 827
            } elseif (strpos($table, '(') === false) {
1299 820
                if (preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $table, $matches)) { // with alias
1300 21
                    $tables[$i] = $this->db->quoteTableName($matches[1]) . ' ' . $this->db->quoteTableName($matches[2]);
1301
                } else {
1302 848
                    $tables[$i] = $this->db->quoteTableName($table);
1303
                }
1304
            }
1305
        }
1306
1307 848
        return $tables;
1308
    }
1309
1310
    /**
1311
     * @param string|array $condition
1312
     * @param array $params the binding parameters to be populated
1313
     * @return string the WHERE clause built from [[Query::$where]].
1314
     */
1315 1246
    public function buildWhere($condition, &$params)
1316
    {
1317 1246
        $where = $this->buildCondition($condition, $params);
1318
1319 1246
        return $where === '' ? '' : 'WHERE ' . $where;
1320
    }
1321
1322
    /**
1323
     * @param array $columns
1324
     * @return string the GROUP BY clause
1325
     */
1326 1160
    public function buildGroupBy($columns)
1327
    {
1328 1160
        if (empty($columns)) {
1329 1154
            return '';
1330
        }
1331 21
        foreach ($columns as $i => $column) {
1332 21
            if ($column instanceof ExpressionInterface) {
1333 3
                $columns[$i] = $this->buildExpression($column);
1334 21
            } elseif (strpos($column, '(') === false) {
1335 21
                $columns[$i] = $this->db->quoteColumnName($column);
1336
            }
1337
        }
1338
1339 21
        return 'GROUP BY ' . implode(', ', $columns);
1340
    }
1341
1342
    /**
1343
     * @param string|array $condition
1344
     * @param array $params the binding parameters to be populated
1345
     * @return string the HAVING clause built from [[Query::$having]].
1346
     */
1347 1160
    public function buildHaving($condition, &$params)
1348
    {
1349 1160
        $having = $this->buildCondition($condition, $params);
1350
1351 1160
        return $having === '' ? '' : 'HAVING ' . $having;
1352
    }
1353
1354
    /**
1355
     * Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL.
1356
     * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET)
1357
     * @param array $orderBy the order by columns. See [[Query::orderBy]] for more details on how to specify this parameter.
1358
     * @param int $limit the limit number. See [[Query::limit]] for more details.
1359
     * @param int $offset the offset number. See [[Query::offset]] for more details.
1360
     * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any)
1361
     */
1362 1160
    public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset)
1363
    {
1364 1160
        $orderBy = $this->buildOrderBy($orderBy);
1365 1160
        if ($orderBy !== '') {
1366 180
            $sql .= $this->separator . $orderBy;
1367
        }
1368 1160
        $limit = $this->buildLimit($limit, $offset);
1369 1160
        if ($limit !== '') {
1370 91
            $sql .= $this->separator . $limit;
1371
        }
1372
1373 1160
        return $sql;
1374
    }
1375
1376
    /**
1377
     * @param array $columns
1378
     * @return string the ORDER BY clause built from [[Query::$orderBy]].
1379
     */
1380 1160
    public function buildOrderBy($columns)
1381
    {
1382 1160
        if (empty($columns)) {
1383 1125
            return '';
1384
        }
1385 180
        $orders = [];
1386 180
        foreach ($columns as $name => $direction) {
1387 180
            if ($direction instanceof ExpressionInterface) {
1388 3
                $orders[] = $this->buildExpression($direction);
1389
            } else {
1390 180
                $orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : '');
1391
            }
1392
        }
1393
1394 180
        return 'ORDER BY ' . implode(', ', $orders);
1395
    }
1396
1397
    /**
1398
     * @param int $limit
1399
     * @param int $offset
1400
     * @return string the LIMIT and OFFSET clauses
1401
     */
1402 420
    public function buildLimit($limit, $offset)
1403
    {
1404 420
        $sql = '';
1405 420
        if ($this->hasLimit($limit)) {
1406 25
            $sql = 'LIMIT ' . $limit;
1407
        }
1408 420
        if ($this->hasOffset($offset)) {
1409 3
            $sql .= ' OFFSET ' . $offset;
1410
        }
1411
1412 420
        return ltrim($sql);
1413
    }
1414
1415
    /**
1416
     * Checks to see if the given limit is effective.
1417
     * @param mixed $limit the given limit
1418
     * @return bool whether the limit is effective
1419
     */
1420 761
    protected function hasLimit($limit)
1421
    {
1422 761
        return ($limit instanceof ExpressionInterface) || ctype_digit((string) $limit);
1423
    }
1424
1425
    /**
1426
     * Checks to see if the given offset is effective.
1427
     * @param mixed $offset the given offset
1428
     * @return bool whether the offset is effective
1429
     */
1430 761
    protected function hasOffset($offset)
1431
    {
1432 761
        return ($offset instanceof ExpressionInterface) || ctype_digit((string) $offset) && (string) $offset !== '0';
1433
    }
1434
1435
    /**
1436
     * @param array $unions
1437
     * @param array $params the binding parameters to be populated
1438
     * @return string the UNION clause built from [[Query::$union]].
1439
     */
1440 819
    public function buildUnion($unions, &$params)
1441
    {
1442 819
        if (empty($unions)) {
1443 819
            return '';
1444
        }
1445
1446 8
        $result = '';
1447
1448 8
        foreach ($unions as $i => $union) {
1449 8
            $query = $union['query'];
1450 8
            if ($query instanceof Query) {
1451 8
                list($unions[$i]['query'], $params) = $this->build($query, $params);
1452
            }
1453
1454 8
            $result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . '( ' . $unions[$i]['query'] . ' ) ';
1455
        }
1456
1457 8
        return trim($result);
1458
    }
1459
1460
    /**
1461
     * Processes columns and properly quotes them if necessary.
1462
     * It will join all columns into a string with comma as separators.
1463
     * @param string|array $columns the columns to be processed
1464
     * @return string the processing result
1465
     */
1466 32
    public function buildColumns($columns)
1467
    {
1468 32
        if (!is_array($columns)) {
1469 27
            if (strpos($columns, '(') !== false) {
1470
                return $columns;
1471
            }
1472
1473 27
            $rawColumns = $columns;
1474 27
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
1475 27
            if ($columns === false) {
1476
                throw new InvalidArgumentException("$rawColumns is not valid columns.");
1477
            }
1478
        }
1479 32
        foreach ($columns as $i => $column) {
1480 32
            if ($column instanceof ExpressionInterface) {
1481
                $columns[$i] = $this->buildExpression($column);
1482 32
            } elseif (strpos($column, '(') === false) {
1483 32
                $columns[$i] = $this->db->quoteColumnName($column);
1484
            }
1485
        }
1486
1487 32
        return implode(', ', $columns);
1488
    }
1489
1490
    /**
1491
     * Parses the condition specification and generates the corresponding SQL expression.
1492
     * @param string|array|ExpressionInterface $condition the condition specification. Please refer to [[Query::where()]]
1493
     * on how to specify a condition.
1494
     * @param array $params the binding parameters to be populated
1495
     * @return string the generated SQL expression
1496
     */
1497 1246
    public function buildCondition($condition, &$params)
1498
    {
1499 1246
        if (is_array($condition)) {
1500 980
            if (empty($condition)) {
1501 3
                return '';
1502
            }
1503
1504 980
            $condition = $this->createConditionFromArray($condition);
1505
        }
1506
1507 1246
        if ($condition instanceof ExpressionInterface) {
1508 1001
            return $this->buildExpression($condition, $params);
1509
        }
1510
1511 1227
        return (string) $condition;
1512
    }
1513
1514
    /**
1515
     * Transforms $condition defined in array format (as described in [[Query::where()]]
1516
     * to instance of [[yii\db\condition\ConditionInterface|ConditionInterface]] according to
1517
     * [[conditionClasses]] map.
1518
     *
1519
     * @param string|array $condition
1520
     * @see conditionClasses
1521
     * @return ConditionInterface
1522
     * @since 2.0.14
1523
     */
1524 980
    public function createConditionFromArray($condition)
1525
    {
1526 980
        if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
1527 587
            $operator = strtoupper(array_shift($condition));
1528 587
            if (isset($this->conditionClasses[$operator])) {
1529 509
                $className = $this->conditionClasses[$operator];
1530
            } else {
1531 84
                $className = 'yii\db\conditions\SimpleCondition';
1532
            }
1533
            /** @var ConditionInterface $className */
1534 587
            return $className::fromArrayDefinition($operator, $condition);
1535
        }
1536
1537
        // hash format: 'column1' => 'value1', 'column2' => 'value2', ...
1538 691
        return new HashCondition($condition);
0 ignored issues
show
Bug introduced by
It seems like $condition defined by parameter $condition on line 1524 can also be of type string; however, yii\db\conditions\HashCondition::__construct() does only seem to accept array|null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
1539
    }
1540
1541
    /**
1542
     * Creates a condition based on column-value pairs.
1543
     * @param array $condition the condition specification.
1544
     * @param array $params the binding parameters to be populated
1545
     * @return string the generated SQL expression
1546
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1547
     */
1548
    public function buildHashCondition($condition, &$params)
1549
    {
1550
        return $this->buildCondition(new HashCondition($condition), $params);
1551
    }
1552
1553
    /**
1554
     * Connects two or more SQL expressions with the `AND` or `OR` operator.
1555
     * @param string $operator the operator to use for connecting the given operands
1556
     * @param array $operands the SQL expressions to connect.
1557
     * @param array $params the binding parameters to be populated
1558
     * @return string the generated SQL expression
1559
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1560
     */
1561
    public function buildAndCondition($operator, $operands, &$params)
1562
    {
1563
        array_unshift($operands, $operator);
1564
        return $this->buildCondition($operands, $params);
1565
    }
1566
1567
    /**
1568
     * Inverts an SQL expressions with `NOT` operator.
1569
     * @param string $operator the operator to use for connecting the given operands
1570
     * @param array $operands the SQL expressions to connect.
1571
     * @param array $params the binding parameters to be populated
1572
     * @return string the generated SQL expression
1573
     * @throws InvalidArgumentException if wrong number of operands have been given.
1574
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1575
     */
1576
    public function buildNotCondition($operator, $operands, &$params)
1577
    {
1578
        array_unshift($operands, $operator);
1579
        return $this->buildCondition($operands, $params);
1580
    }
1581
1582
    /**
1583
     * Creates an SQL expressions with the `BETWEEN` operator.
1584
     * @param string $operator the operator to use (e.g. `BETWEEN` or `NOT BETWEEN`)
1585
     * @param array $operands the first operand is the column name. The second and third operands
1586
     * describe the interval that column value should be in.
1587
     * @param array $params the binding parameters to be populated
1588
     * @return string the generated SQL expression
1589
     * @throws InvalidArgumentException if wrong number of operands have been given.
1590
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1591
     */
1592
    public function buildBetweenCondition($operator, $operands, &$params)
1593
    {
1594
        array_unshift($operands, $operator);
1595
        return $this->buildCondition($operands, $params);
1596
    }
1597
1598
    /**
1599
     * Creates an SQL expressions with the `IN` operator.
1600
     * @param string $operator the operator to use (e.g. `IN` or `NOT IN`)
1601
     * @param array $operands the first operand is the column name. If it is an array
1602
     * a composite IN condition will be generated.
1603
     * The second operand is an array of values that column value should be among.
1604
     * If it is an empty array the generated expression will be a `false` value if
1605
     * operator is `IN` and empty if operator is `NOT IN`.
1606
     * @param array $params the binding parameters to be populated
1607
     * @return string the generated SQL expression
1608
     * @throws Exception if wrong number of operands have been given.
1609
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1610
     */
1611
    public function buildInCondition($operator, $operands, &$params)
1612
    {
1613
        array_unshift($operands, $operator);
1614
        return $this->buildCondition($operands, $params);
1615
    }
1616
1617
    /**
1618
     * Creates an SQL expressions with the `LIKE` operator.
1619
     * @param string $operator the operator to use (e.g. `LIKE`, `NOT LIKE`, `OR LIKE` or `OR NOT LIKE`)
1620
     * @param array $operands an array of two or three operands
1621
     *
1622
     * - The first operand is the column name.
1623
     * - The second operand is a single value or an array of values that column value
1624
     *   should be compared with. If it is an empty array the generated expression will
1625
     *   be a `false` value if operator is `LIKE` or `OR LIKE`, and empty if operator
1626
     *   is `NOT LIKE` or `OR NOT LIKE`.
1627
     * - An optional third operand can also be provided to specify how to escape special characters
1628
     *   in the value(s). The operand should be an array of mappings from the special characters to their
1629
     *   escaped counterparts. If this operand is not provided, a default escape mapping will be used.
1630
     *   You may use `false` or an empty array to indicate the values are already escaped and no escape
1631
     *   should be applied. Note that when using an escape mapping (or the third operand is not provided),
1632
     *   the values will be automatically enclosed within a pair of percentage characters.
1633
     * @param array $params the binding parameters to be populated
1634
     * @return string the generated SQL expression
1635
     * @throws InvalidArgumentException if wrong number of operands have been given.
1636
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1637
     */
1638
    public function buildLikeCondition($operator, $operands, &$params)
1639
    {
1640
        array_unshift($operands, $operator);
1641
        return $this->buildCondition($operands, $params);
1642
    }
1643
1644
    /**
1645
     * Creates an SQL expressions with the `EXISTS` operator.
1646
     * @param string $operator the operator to use (e.g. `EXISTS` or `NOT EXISTS`)
1647
     * @param array $operands contains only one element which is a [[Query]] object representing the sub-query.
1648
     * @param array $params the binding parameters to be populated
1649
     * @return string the generated SQL expression
1650
     * @throws InvalidArgumentException if the operand is not a [[Query]] object.
1651
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1652
     */
1653
    public function buildExistsCondition($operator, $operands, &$params)
1654
    {
1655
        array_unshift($operands, $operator);
1656
        return $this->buildCondition($operands, $params);
1657
    }
1658
1659
    /**
1660
     * Creates an SQL expressions like `"column" operator value`.
1661
     * @param string $operator the operator to use. Anything could be used e.g. `>`, `<=`, etc.
1662
     * @param array $operands contains two column names.
1663
     * @param array $params the binding parameters to be populated
1664
     * @return string the generated SQL expression
1665
     * @throws InvalidArgumentException if wrong number of operands have been given.
1666
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1667
     */
1668
    public function buildSimpleCondition($operator, $operands, &$params)
1669
    {
1670
        array_unshift($operands, $operator);
1671
        return $this->buildCondition($operands, $params);
1672
    }
1673
1674
    /**
1675
     * Creates a SELECT EXISTS() SQL statement.
1676
     * @param string $rawSql the subquery in a raw form to select from.
1677
     * @return string the SELECT EXISTS() SQL statement.
1678
     * @since 2.0.8
1679
     */
1680 70
    public function selectExists($rawSql)
1681
    {
1682 70
        return 'SELECT EXISTS(' . $rawSql . ')';
1683
    }
1684
1685
    /**
1686
     * Helper method to add $value to $params array using [[PARAM_PREFIX]].
1687
     *
1688
     * @param string|null $value
1689
     * @param array $params passed by reference
1690
     * @return string the placeholder name in $params array
1691
     *
1692
     * @since 2.0.14
1693
     */
1694 1031
    public function bindParam($value, &$params)
1695
    {
1696 1031
        $phName = self::PARAM_PREFIX . count($params);
1697 1031
        $params[$phName] = $value;
1698
1699 1031
        return $phName;
1700
    }
1701
}
1702