Completed
Push — master ( 01636a...5e01dd )
by Dmitry
70:16 queued 67:10
created

QueryBuilder::dropForeignKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
crap 1
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
 * @author Qiang Xue <[email protected]>
26
 * @since 2.0
27
 */
28
class QueryBuilder extends \yii\base\BaseObject
29
{
30
    /**
31
     * The prefix for automatically generated query binding parameters.
32
     */
33
    const PARAM_PREFIX = ':qp';
34
35
    /**
36
     * @var Connection the database connection.
37
     */
38
    public $db;
39
    /**
40
     * @var string the separator between different fragments of a SQL statement.
41
     * Defaults to an empty space. This is mainly used by [[build()]] when generating a SQL statement.
42
     */
43
    public $separator = ' ';
44
    /**
45
     * @var array the abstract column types mapped to physical column types.
46
     * This is mainly used to support creating/modifying tables using DB-independent data type specifications.
47
     * Child classes should override this property to declare supported type mappings.
48
     */
49
    public $typeMap = [];
50
51
    /**
52
     * @var array map of query condition to builder methods.
53
     * These methods are used by [[buildCondition]] to build SQL conditions from array syntax.
54
     * @deprecated since 2.0.14. Is not used, will be dropped in 2.1.0.
55
     */
56
    protected $conditionBuilders = [];
57
58
    /**
59
     * @var array map of condition aliases to condition classes. For example:
60
     *
61
     * ```php
62
     * return [
63
     *     'LIKE' => yii\db\condition\LikeCondition::class,
64
     * ];
65
     * ```
66
     *
67
     * This property is used by [[createConditionFromArray]] method.
68
     * See default condition classes list in [[defaultConditionClasses()]] method.
69
     *
70
     * In case you want to add custom conditions support, use the [[setConditionClasses()]] method.
71
     *
72
     * @see setConditonClasses()
73
     * @see defaultConditionClasses()
74
     * @since 2.0.14
75
     */
76
    protected $conditionClasses = [];
77
78
    /**
79
     * @var string[]|ExpressionBuilderInterface[] maps expression class to expression builder class.
80
     * For example:
81
     *
82
     * ```php
83
     * [
84
     *    yii\db\Expression::class => yii\db\ExpressionBuilder::class
85
     * ]
86
     * ```
87
     * This property is mainly used by [[buildExpression()]] to build SQL expressions form expression objects.
88
     * See default values in [[defaultExpressionBuilders()]] method.
89
     *
90
     *
91
     * To override existing builders or add custom, use [[setExpressionBuilder()]] method. New items will be added
92
     * to the end of this array.
93
     *
94
     * To find a builder, [[buildExpression()]] will check the expression class for its exact presence in this map.
95
     * In case it is NOT present, the array will be iterated in reverse direction, checking whether the expression
96
     * extends the class, defined in this map.
97
     *
98
     * @see setExpressionBuilders()
99
     * @see defaultExpressionBuilders()
100
     * @since 2.0.14
101
     */
102
    protected $expressionBuilders = [];
103
104
    /**
105
     * Constructor.
106
     * @param Connection $connection the database connection.
107
     * @param array $config name-value pairs that will be used to initialize the object properties
108
     */
109 1425
    public function __construct($connection, $config = [])
110
    {
111 1425
        $this->db = $connection;
112 1425
        parent::__construct($config);
113 1425
    }
114
115
    /**
116
     * {@inheritdoc}
117
     */
118 1425
    public function init()
119
    {
120 1425
        parent::init();
121
122 1425
        $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...
123 1425
        $this->conditionClasses = array_merge($this->defaultConditionClasses(), $this->conditionClasses);
124 1425
    }
125
126
    /**
127
     * Contains array of default condition classes. Extend this method, if you want to change
128
     * default condition classes for the query builder. See [[conditionClasses]] docs for details.
129
     *
130
     * @return array
131
     * @see conditionClasses
132
     * @since 2.0.14
133
     */
134 1425
    protected function defaultConditionClasses()
135
    {
136
        return [
137 1425
            'NOT' => 'yii\db\conditions\NotCondition',
138
            'AND' => 'yii\db\conditions\AndCondition',
139
            'OR' => 'yii\db\conditions\OrCondition',
140
            'BETWEEN' => 'yii\db\conditions\BetweenCondition',
141
            'NOT BETWEEN' => 'yii\db\conditions\BetweenCondition',
142
            'IN' => 'yii\db\conditions\InCondition',
143
            'NOT IN' => 'yii\db\conditions\InCondition',
144
            'LIKE' => 'yii\db\conditions\LikeCondition',
145
            'NOT LIKE' => 'yii\db\conditions\LikeCondition',
146
            'OR LIKE' => 'yii\db\conditions\LikeCondition',
147
            'OR NOT LIKE' => 'yii\db\conditions\LikeCondition',
148
            'EXISTS' => 'yii\db\conditions\ExistsCondition',
149
            'NOT EXISTS' => 'yii\db\conditions\ExistsCondition',
150
        ];
151
    }
152
153
    /**
154
     * Contains array of default expression builders. Extend this method and override it, if you want to change
155
     * default expression builders for this query builder. See [[expressionBuilders]] docs for details.
156
     *
157
     * @return array
158
     * @see $expressionBuilders
159
     * @since 2.0.14
160
     */
161 1425
    protected function defaultExpressionBuilders()
162
    {
163
        return [
164 1425
            'yii\db\Query' => 'yii\db\QueryExpressionBuilder',
165
            'yii\db\PdoValue' => 'yii\db\PdoValueBuilder',
166
            'yii\db\Expression' => 'yii\db\ExpressionBuilder',
167
            'yii\db\conditions\ConjunctionCondition' => 'yii\db\conditions\ConjunctionConditionBuilder',
168
            'yii\db\conditions\NotCondition' => 'yii\db\conditions\NotConditionBuilder',
169
            'yii\db\conditions\AndCondition' => 'yii\db\conditions\ConjunctionConditionBuilder',
170
            'yii\db\conditions\OrCondition' => 'yii\db\conditions\ConjunctionConditionBuilder',
171
            'yii\db\conditions\BetweenCondition' => 'yii\db\conditions\BetweenConditionBuilder',
172
            'yii\db\conditions\InCondition' => 'yii\db\conditions\InConditionBuilder',
173
            'yii\db\conditions\LikeCondition' => 'yii\db\conditions\LikeConditionBuilder',
174
            'yii\db\conditions\ExistsCondition' => 'yii\db\conditions\ExistsConditionBuilder',
175
            'yii\db\conditions\SimpleCondition' => 'yii\db\conditions\SimpleConditionBuilder',
176
            'yii\db\conditions\HashCondition' => 'yii\db\conditions\HashConditionBuilder',
177
            'yii\db\conditions\BetweenColumnsCondition' => 'yii\db\conditions\BetweenColumnsConditionBuilder',
178
        ];
179
    }
180
181
    /**
182
     * Setter for [[expressionBuilders]] property.
183
     *
184
     * @param string[] $builders array of builder that should be merged with [[expressionBuilders]]
185
     * @since 2.0.14
186
     * @see expressionBuilders
187
     */
188
    public function setExpressionBuilders($builders)
189
    {
190
        $this->expressionBuilders = array_merge($this->expressionBuilders, $builders);
191
    }
192
193
    /**
194
     * Generates a SELECT SQL statement from a [[Query]] object.
195
     *
196
     * @param Query $query the [[Query]] object from which the SQL statement will be generated.
197
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will
198
     * be included in the result with the additional parameters generated during the query building process.
199
     * @return array the generated SQL statement (the first array element) and the corresponding
200
     * parameters to be bound to the SQL statement (the second array element). The parameters returned
201
     * include those provided in `$params`.
202
     */
203 814
    public function build($query, $params = [])
204
    {
205 814
        $query = $query->prepare($this);
206
207 814
        $params = empty($params) ? $query->params : array_merge($params, $query->params);
208
209
        $clauses = [
210 814
            $this->buildSelect($query->select, $params, $query->distinct, $query->selectOption),
211 814
            $this->buildFrom($query->from, $params),
212 814
            $this->buildJoin($query->join, $params),
213 814
            $this->buildWhere($query->where, $params),
214 814
            $this->buildGroupBy($query->groupBy),
215 814
            $this->buildHaving($query->having, $params),
216
        ];
217
218 814
        $sql = implode($this->separator, array_filter($clauses));
219 814
        $sql = $this->buildOrderByAndLimit($sql, $query->orderBy, $query->limit, $query->offset);
220
221 814
        if (!empty($query->orderBy)) {
222 108
            foreach ($query->orderBy as $expression) {
223 108
                if ($expression instanceof ExpressionInterface) {
224 108
                    $this->buildExpression($expression, $params);
225
                }
226
            }
227
        }
228 814
        if (!empty($query->groupBy)) {
229 18
            foreach ($query->groupBy as $expression) {
230 18
                if ($expression instanceof ExpressionInterface) {
231 18
                    $this->buildExpression($expression, $params);
232
                }
233
            }
234
        }
235
236 814
        $union = $this->buildUnion($query->union, $params);
237 814
        if ($union !== '') {
238 8
            $sql = "($sql){$this->separator}$union";
239
        }
240
241 814
        return [$sql, $params];
242
    }
243
244
    /**
245
     * Builds given $expression
246
     *
247
     * @param ExpressionInterface $expression the expression to be built
248
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will
249
     * be included in the result with the additional parameters generated during the expression building process.
250
     * @return string the SQL statement that will not be neither quoted nor encoded before passing to DBMS
251
     * @see ExpressionInterface
252
     * @see ExpressionBuilderInterface
253
     * @see expressionBuilders
254
     * @since 2.0.14
255
     * @throws InvalidArgumentException when $expression building is not supported by this QueryBuilder.
256
     */
257 1057
    public function buildExpression(ExpressionInterface $expression, &$params = [])
258
    {
259 1057
        $builder = $this->getExpressionBuilder($expression);
260
261 1057
        return $builder->build($expression, $params);
262
    }
263
264
    /**
265
     * Gets object of [[ExpressionBuilderInterface]] that is suitable for $expression.
266
     * Uses [[expressionBuilders]] array to find a suitable builder class.
267
     *
268
     * @param ExpressionInterface $expression
269
     * @return ExpressionBuilderInterface
270
     * @see expressionBuilders
271
     * @since 2.0.14
272
     * @throws InvalidArgumentException when $expression building is not supported by this QueryBuilder.
273
     */
274 1057
    public function getExpressionBuilder(ExpressionInterface $expression)
275
    {
276 1057
        $className = get_class($expression);
277
278 1057
        if (!isset($this->expressionBuilders[$className])) {
279
            foreach (array_reverse($this->expressionBuilders) as $expressionClass => $builderClass) {
280
                if (is_subclass_of($expression, $expressionClass)) {
281
                    $this->expressionBuilders[$className] = $builderClass;
282
                    break;
283
                }
284
            }
285
286
            if (!isset($this->expressionBuilders[$className])) {
287
                throw new InvalidArgumentException('Expression of class ' . $className . ' can not be built in ' . get_class($this));
288
            }
289
        }
290
291 1057
        if ($this->expressionBuilders[$className] === __CLASS__) {
292
            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...
293
        }
294
295 1057
        if (!is_object($this->expressionBuilders[$className])) {
296 1013
            $this->expressionBuilders[$className] = new $this->expressionBuilders[$className]($this);
297
        }
298
299 1057
        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 299 which is incompatible with the return type documented by yii\db\QueryBuilder::getExpressionBuilder of type yii\db\ExpressionBuilderInterface.
Loading history...
300
    }
301
302
    /**
303
     * Creates an INSERT SQL statement.
304
     * For example,
305
     * ```php
306
     * $sql = $queryBuilder->insert('user', [
307
     *     'name' => 'Sam',
308
     *     'age' => 30,
309
     * ], $params);
310
     * ```
311
     * The method will properly escape the table and column names.
312
     *
313
     * @param string $table the table that new rows will be inserted into.
314
     * @param array|Query $columns the column data (name => value) to be inserted into the table or instance
315
     * of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement.
316
     * Passing of [[yii\db\Query|Query]] is available since version 2.0.11.
317
     * @param array $params the binding parameters that will be generated by this method.
318
     * They should be bound to the DB command later.
319
     * @return string the INSERT SQL
320
     */
321 532
    public function insert($table, $columns, &$params)
322
    {
323 532
        list($names, $placeholders, $values, $params) = $this->prepareInsertValues($table, $columns, $params);
324 523
        return 'INSERT INTO ' . $this->db->quoteTableName($table)
325 523
            . (!empty($names) ? ' (' . implode(', ', $names) . ')' : '')
326 523
            . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : $values);
327
    }
328
329
    /**
330
     * Prepares a `VALUES` part for an `INSERT` SQL statement.
331
     *
332
     * @param string $table the table that new rows will be inserted into.
333
     * @param array|Query $columns the column data (name => value) to be inserted into the table or instance
334
     * of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement.
335
     * @param array $params the binding parameters that will be generated by this method.
336
     * They should be bound to the DB command later.
337
     * @return array array of column names, placeholders, values and params.
338
     * @since 2.0.14
339
     */
340 546
    protected function prepareInsertValues($table, $columns, $params = [])
341
    {
342 546
        $schema = $this->db->getSchema();
343 546
        $tableSchema = $schema->getTableSchema($table);
344 546
        $columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
345 546
        $names = [];
346 546
        $placeholders = [];
347 546
        $values = ' DEFAULT VALUES';
348 546
        if ($columns instanceof Query) {
349 42
            list($names, $values, $params) = $this->prepareInsertSelectSubQuery($columns, $schema, $params);
350
        } else {
351 510
            foreach ($columns as $name => $value) {
352 506
                $names[] = $schema->quoteColumnName($name);
353 506
                $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
354
355 506
                if ($value instanceof ExpressionInterface) {
356 116
                    $placeholders[] = $this->buildExpression($value, $params);
357 500
                } elseif ($value instanceof \yii\db\Query) {
358
                    list($sql, $params) = $this->build($value, $params);
359
                    $placeholders[] = "($sql)";
360
                } else {
361 506
                    $placeholders[] = $this->bindParam($value, $params);
362
                }
363
            }
364
        }
365 537
        return [$names, $placeholders, $values, $params];
366
    }
367
368
    /**
369
     * Prepare select-subquery and field names for INSERT INTO ... SELECT SQL statement.
370
     *
371
     * @param Query $columns Object, which represents select query.
372
     * @param \yii\db\Schema $schema Schema object to quote column name.
373
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will
374
     * be included in the result with the additional parameters generated during the query building process.
375
     * @return array array of column names, values and params.
376
     * @throws InvalidArgumentException if query's select does not contain named parameters only.
377
     * @since 2.0.11
378
     */
379 42
    protected function prepareInsertSelectSubQuery($columns, $schema, $params = [])
380
    {
381 42
        if (!is_array($columns->select) || empty($columns->select) || in_array('*', $columns->select)) {
382 9
            throw new InvalidArgumentException('Expected select query object with enumerated (named) parameters');
383
        }
384
385 33
        list($values, $params) = $this->build($columns, $params);
386 33
        $names = [];
387 33
        $values = ' ' . $values;
388 33
        foreach ($columns->select as $title => $field) {
389 33
            if (is_string($title)) {
390 27
                $names[] = $schema->quoteColumnName($title);
391 24
            } elseif (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $field, $matches)) {
392 3
                $names[] = $schema->quoteColumnName($matches[2]);
393
            } else {
394 33
                $names[] = $schema->quoteColumnName($field);
395
            }
396
        }
397
398 33
        return [$names, $values, $params];
399
    }
400
401
    /**
402
     * Generates a batch INSERT SQL statement.
403
     *
404
     * For example,
405
     *
406
     * ```php
407
     * $sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
408
     *     ['Tom', 30],
409
     *     ['Jane', 20],
410
     *     ['Linda', 25],
411
     * ]);
412
     * ```
413
     *
414
     * Note that the values in each row must match the corresponding column names.
415
     *
416
     * The method will properly escape the column names, and quote the values to be inserted.
417
     *
418
     * @param string $table the table that new rows will be inserted into.
419
     * @param array $columns the column names
420
     * @param array|\Generator $rows the rows to be batch inserted into the table
421
     * @param array $params the binding parameters. This parameter exists since 2.0.14
422
     * @return string the batch INSERT SQL statement
423
     */
424 27
    public function batchInsert($table, $columns, $rows, &$params = [])
425
    {
426 27
        if (empty($rows)) {
427 2
            return '';
428
        }
429
430 26
        $schema = $this->db->getSchema();
431 26
        if (($tableSchema = $schema->getTableSchema($table)) !== null) {
432 20
            $columnSchemas = $tableSchema->columns;
433
        } else {
434 6
            $columnSchemas = [];
435
        }
436
437 26
        $values = [];
438 26
        foreach ($rows as $row) {
439 24
            $vs = [];
440 24
            foreach ($row as $i => $value) {
441 24
                if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
442 15
                    $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
443
                }
444 24
                if (is_string($value)) {
445 16
                    $value = $schema->quoteValue($value);
446 15
                } elseif (is_float($value)) {
447
                    // ensure type cast always has . as decimal separator in all locales
448 2
                    $value = StringHelper::floatToString($value);
449 15
                } elseif ($value === false) {
450 4
                    $value = 0;
451 15
                } elseif ($value === null) {
452 8
                    $value = 'NULL';
453 10
                } elseif ($value instanceof ExpressionInterface) {
454 6
                    $value = $this->buildExpression($value, $params);
455
                }
456 24
                $vs[] = $value;
457
            }
458 24
            $values[] = '(' . implode(', ', $vs) . ')';
459
        }
460 26
        if (empty($values)) {
461 2
            return '';
462
        }
463
464 24
        foreach ($columns as $i => $name) {
465 22
            $columns[$i] = $schema->quoteColumnName($name);
466
        }
467
468 24
        return 'INSERT INTO ' . $schema->quoteTableName($table)
469 24
        . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
470
    }
471
472
    /**
473
     * Creates an SQL statement to insert rows into a database table if
474
     * they do not already exist (matching unique constraints),
475
     * or update them if they do.
476
     *
477
     * For example,
478
     *
479
     * ```php
480
     * $sql = $queryBuilder->upsert('pages', [
481
     *     'name' => 'Front page',
482
     *     'url' => 'http://example.com/', // url is unique
483
     *     'visits' => 0,
484
     * ], [
485
     *     'visits' => new \yii\db\Expression('visits + 1'),
486
     * ], $params);
487
     * ```
488
     *
489
     * The method will properly escape the table and column names.
490
     *
491
     * @param string $table the table that new rows will be inserted into/updated in.
492
     * @param array|Query $insertColumns the column data (name => value) to be inserted into the table or instance
493
     * of [[Query]] to perform `INSERT INTO ... SELECT` SQL statement.
494
     * @param array|bool $updateColumns the column data (name => value) to be updated if they already exist.
495
     * If `true` is passed, the column data will be updated to match the insert column data.
496
     * If `false` is passed, no update will be performed if the column data already exists.
497
     * @param array $params the binding parameters that will be generated by this method.
498
     * They should be bound to the DB command later.
499
     * @return string the resulting SQL.
500
     * @throws NotSupportedException if this is not supported by the underlying DBMS.
501
     * @since 2.0.14
502
     */
503
    public function upsert($table, $insertColumns, $updateColumns, &$params)
504
    {
505
        throw new NotSupportedException($this->db->getDriverName() . ' does not support upsert statements.');
506
    }
507
508
    /**
509
     * @param string $table
510
     * @param array|Query $insertColumns
511
     * @param array|bool $updateColumns
512
     * @param Constraint[] $constraints this parameter recieves a matched constraint list.
513
     * The constraints will be unique by their column names.
514
     * @return array
515
     * @since 2.0.14
516
     */
517 66
    protected function prepareUpsertColumns($table, $insertColumns, $updateColumns, &$constraints = [])
518
    {
519 66
        if ($insertColumns instanceof Query) {
520 24
            list($insertNames) = $this->prepareInsertSelectSubQuery($insertColumns, $this->db->getSchema());
521
        } else {
522 42
            $insertNames = array_map([$this->db, 'quoteColumnName'], array_keys($insertColumns));
523
        }
524 66
        $uniqueNames = $this->getTableUniqueColumnNames($table, $insertNames, $constraints);
525 66
        $uniqueNames = array_map([$this->db, 'quoteColumnName'], $uniqueNames);
526 66
        if ($updateColumns !== true) {
527 36
            return [$uniqueNames, $insertNames, null];
528
        }
529
530 30
        return [$uniqueNames, $insertNames, array_diff($insertNames, $uniqueNames)];
531
    }
532
533
    /**
534
     * Returns all column names belonging to constraints enforcing uniqueness (`PRIMARY KEY`, `UNIQUE INDEX`, etc.)
535
     * for the named table removing constraints which did not cover the specified column list.
536
     * The column list will be unique by column names.
537
     *
538
     * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
539
     * @param string[] $columns source column list.
540
     * @param Constraint[] $constraints this parameter optionally recieves a matched constraint list.
541
     * The constraints will be unique by their column names.
542
     * @return string[] column list.
543
     */
544 66
    private function getTableUniqueColumnNames($name, $columns, &$constraints = [])
545
    {
546 66
        $schema = $this->db->getSchema();
547 66
        if (!$schema instanceof ConstraintFinderInterface) {
548
            return [];
549
        }
550
551 66
        $constraints = [];
552 66
        $primaryKey = $schema->getTablePrimaryKey($name);
553 66
        if ($primaryKey !== null) {
554 49
            $constraints[] = $primaryKey;
555
        }
556 66
        foreach ($schema->getTableIndexes($name) as $constraint) {
557 66
            if ($constraint->isUnique) {
558 66
                $constraints[] = $constraint;
559
            }
560
        }
561 66
        $constraints = array_merge($constraints, $schema->getTableUniques($name));
562
        // Remove duplicates
563
        $constraints = array_combine(array_map(function (Constraint $constraint) {
564 66
            $columns = $constraint->columnNames;
565 66
            sort($columns, SORT_STRING);
566 66
            return json_encode($columns);
567 66
        }, $constraints), $constraints);
568 66
        $columnNames = [];
569
        // Remove all constraints which do not cover the specified column list
570
        $constraints = array_values(array_filter($constraints, function (Constraint $constraint) use ($schema, $columns, &$columnNames) {
571 66
            $constraintColumnNames = array_map([$schema, 'quoteColumnName'], $constraint->columnNames);
572 66
            $result = !array_diff($constraintColumnNames, $columns);
573 66
            if ($result) {
574 57
                $columnNames = array_merge($columnNames, $constraintColumnNames);
575
            }
576 66
            return $result;
577 66
        }));
578 66
        return array_unique($columnNames);
579
    }
580
581
    /**
582
     * Creates an UPDATE SQL statement.
583
     *
584
     * For example,
585
     *
586
     * ```php
587
     * $params = [];
588
     * $sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params);
589
     * ```
590
     *
591
     * The method will properly escape the table and column names.
592
     *
593
     * @param string $table the table to be updated.
594
     * @param array $columns the column data (name => value) to be updated.
595
     * @param array|string $condition the condition that will be put in the WHERE part. Please
596
     * refer to [[Query::where()]] on how to specify condition.
597
     * @param array $params the binding parameters that will be modified by this method
598
     * so that they can be bound to the DB command later.
599
     * @return string the UPDATE SQL
600
     */
601 128
    public function update($table, $columns, $condition, &$params)
602
    {
603 128
        list($lines, $params) = $this->prepareUpdateSets($table, $columns, $params);
604 128
        $sql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $lines);
605 128
        $where = $this->buildWhere($condition, $params);
606 128
        return $where === '' ? $sql : $sql . ' ' . $where;
607
    }
608
609
    /**
610
     * Prepares a `SET` parts for an `UPDATE` SQL statement.
611
     * @param string $table the table to be updated.
612
     * @param array $columns the column data (name => value) to be updated.
613
     * @param array $params the binding parameters that will be modified by this method
614
     * so that they can be bound to the DB command later.
615
     * @return array an array `SET` parts for an `UPDATE` SQL statement (the first array element) and params (the second array element).
616
     * @since 2.0.14
617
     */
618 160
    protected function prepareUpdateSets($table, $columns, $params = [])
619
    {
620 160
        $tableSchema = $this->db->getTableSchema($table);
621 160
        $columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
622 160
        $sets = [];
623 160
        foreach ($columns as $name => $value) {
624 160
            if ($value instanceof ExpressionInterface) {
625 85
                $sets[] = $this->db->quoteColumnName($name) . '=' . $this->buildExpression($value, $params);
626
            } else {
627 125
                $phName = $this->bindParam(
628 125
                    isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value,
629 125
                    $params
630
                );
631 160
                $sets[] = $this->db->quoteColumnName($name) . '=' . $phName;
632
            }
633
        }
634 160
        return [$sets, $params];
635
    }
636
637
    /**
638
     * Creates a DELETE SQL statement.
639
     *
640
     * For example,
641
     *
642
     * ```php
643
     * $sql = $queryBuilder->delete('user', 'status = 0');
644
     * ```
645
     *
646
     * The method will properly escape the table and column names.
647
     *
648
     * @param string $table the table where the data will be deleted from.
649
     * @param array|string $condition the condition that will be put in the WHERE part. Please
650
     * refer to [[Query::where()]] on how to specify condition.
651
     * @param array $params the binding parameters that will be modified by this method
652
     * so that they can be bound to the DB command later.
653
     * @return string the DELETE SQL
654
     */
655 353
    public function delete($table, $condition, &$params)
656
    {
657 353
        $sql = 'DELETE FROM ' . $this->db->quoteTableName($table);
658 353
        $where = $this->buildWhere($condition, $params);
659
660 353
        return $where === '' ? $sql : $sql . ' ' . $where;
661
    }
662
663
    /**
664
     * Builds a SQL statement for creating a new DB table.
665
     *
666
     * The columns in the new  table should be specified as name-definition pairs (e.g. 'name' => 'string'),
667
     * where name stands for a column name which will be properly quoted by the method, and definition
668
     * stands for the column type which can contain an abstract DB type.
669
     * The [[getColumnType()]] method will be invoked to convert any abstract type into a physical one.
670
     *
671
     * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
672
     * inserted into the generated SQL.
673
     *
674
     * For example,
675
     *
676
     * ```php
677
     * $sql = $queryBuilder->createTable('user', [
678
     *  'id' => 'pk',
679
     *  'name' => 'string',
680
     *  'age' => 'integer',
681
     * ]);
682
     * ```
683
     *
684
     * @param string $table the name of the table to be created. The name will be properly quoted by the method.
685
     * @param array $columns the columns (name => definition) in the new table.
686
     * @param string $options additional SQL fragment that will be appended to the generated SQL.
687
     * @return string the SQL statement for creating a new DB table.
688
     */
689 137
    public function createTable($table, $columns, $options = null)
690
    {
691 137
        $cols = [];
692 137
        foreach ($columns as $name => $type) {
693 137
            if (is_string($name)) {
694 137
                $cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type);
695
            } else {
696 137
                $cols[] = "\t" . $type;
697
            }
698
        }
699 137
        $sql = 'CREATE TABLE ' . $this->db->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)";
700
701 137
        return $options === null ? $sql : $sql . ' ' . $options;
702
    }
703
704
    /**
705
     * Builds a SQL statement for renaming a DB table.
706
     * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
707
     * @param string $newName the new table name. The name will be properly quoted by the method.
708
     * @return string the SQL statement for renaming a DB table.
709
     */
710 1
    public function renameTable($oldName, $newName)
711
    {
712 1
        return 'RENAME TABLE ' . $this->db->quoteTableName($oldName) . ' TO ' . $this->db->quoteTableName($newName);
713
    }
714
715
    /**
716
     * Builds a SQL statement for dropping a DB table.
717
     * @param string $table the table to be dropped. The name will be properly quoted by the method.
718
     * @return string the SQL statement for dropping a DB table.
719
     */
720 39
    public function dropTable($table)
721
    {
722 39
        return 'DROP TABLE ' . $this->db->quoteTableName($table);
723
    }
724
725
    /**
726
     * Builds a SQL statement for adding a primary key constraint to an existing table.
727
     * @param string $name the name of the primary key constraint.
728
     * @param string $table the table that the primary key constraint will be added to.
729
     * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
730
     * @return string the SQL statement for adding a primary key constraint to an existing table.
731
     */
732 6
    public function addPrimaryKey($name, $table, $columns)
733
    {
734 6
        if (is_string($columns)) {
735 4
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
736
        }
737
738 6
        foreach ($columns as $i => $col) {
739 6
            $columns[$i] = $this->db->quoteColumnName($col);
740
        }
741
742 6
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
743 6
            . $this->db->quoteColumnName($name) . ' PRIMARY KEY ('
744 6
            . implode(', ', $columns) . ')';
745
    }
746
747
    /**
748
     * Builds a SQL statement for removing a primary key constraint to an existing table.
749
     * @param string $name the name of the primary key constraint to be removed.
750
     * @param string $table the table that the primary key constraint will be removed from.
751
     * @return string the SQL statement for removing a primary key constraint from an existing table.
752
     */
753 2
    public function dropPrimaryKey($name, $table)
754
    {
755 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
756 2
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
757
    }
758
759
    /**
760
     * Builds a SQL statement for truncating a DB table.
761
     * @param string $table the table to be truncated. The name will be properly quoted by the method.
762
     * @return string the SQL statement for truncating a DB table.
763
     */
764 11
    public function truncateTable($table)
765
    {
766 11
        return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table);
767
    }
768
769
    /**
770
     * Builds a SQL statement for adding a new DB column.
771
     * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
772
     * @param string $column the name of the new column. The name will be properly quoted by the method.
773
     * @param string $type the column type. The [[getColumnType()]] method will be invoked to convert abstract column type (if any)
774
     * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
775
     * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
776
     * @return string the SQL statement for adding a new column.
777
     */
778 4
    public function addColumn($table, $column, $type)
779
    {
780 4
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
781 4
            . ' ADD ' . $this->db->quoteColumnName($column) . ' '
782 4
            . $this->getColumnType($type);
783
    }
784
785
    /**
786
     * Builds a SQL statement for dropping a DB column.
787
     * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
788
     * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
789
     * @return string the SQL statement for dropping a DB column.
790
     */
791
    public function dropColumn($table, $column)
792
    {
793
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
794
            . ' DROP COLUMN ' . $this->db->quoteColumnName($column);
795
    }
796
797
    /**
798
     * Builds a SQL statement for renaming a column.
799
     * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
800
     * @param string $oldName the old name of the column. The name will be properly quoted by the method.
801
     * @param string $newName the new name of the column. The name will be properly quoted by the method.
802
     * @return string the SQL statement for renaming a DB column.
803
     */
804
    public function renameColumn($table, $oldName, $newName)
805
    {
806
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
807
            . ' RENAME COLUMN ' . $this->db->quoteColumnName($oldName)
808
            . ' TO ' . $this->db->quoteColumnName($newName);
809
    }
810
811
    /**
812
     * Builds a SQL statement for changing the definition of a column.
813
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
814
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
815
     * @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract
816
     * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
817
     * in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
818
     * will become 'varchar(255) not null'.
819
     * @return string the SQL statement for changing the definition of a column.
820
     */
821 1
    public function alterColumn($table, $column, $type)
822
    {
823 1
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
824 1
            . $this->db->quoteColumnName($column) . ' '
825 1
            . $this->db->quoteColumnName($column) . ' '
826 1
            . $this->getColumnType($type);
827
    }
828
829
    /**
830
     * Builds a SQL statement for adding a foreign key constraint to an existing table.
831
     * The method will properly quote the table and column names.
832
     * @param string $name the name of the foreign key constraint.
833
     * @param string $table the table that the foreign key constraint will be added to.
834
     * @param string|array $columns the name of the column to that the constraint will be added on.
835
     * If there are multiple columns, separate them with commas or use an array to represent them.
836
     * @param string $refTable the table that the foreign key references to.
837
     * @param string|array $refColumns the name of the column that the foreign key references to.
838
     * If there are multiple columns, separate them with commas or use an array to represent them.
839
     * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
840
     * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
841
     * @return string the SQL statement for adding a foreign key constraint to an existing table.
842
     */
843 8
    public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
844
    {
845 8
        $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
846 8
            . ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name)
847 8
            . ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
848 8
            . ' REFERENCES ' . $this->db->quoteTableName($refTable)
849 8
            . ' (' . $this->buildColumns($refColumns) . ')';
850 8
        if ($delete !== null) {
851 4
            $sql .= ' ON DELETE ' . $delete;
852
        }
853 8
        if ($update !== null) {
854 4
            $sql .= ' ON UPDATE ' . $update;
855
        }
856
857 8
        return $sql;
858
    }
859
860
    /**
861
     * Builds a SQL statement for dropping a foreign key constraint.
862
     * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
863
     * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
864
     * @return string the SQL statement for dropping a foreign key constraint.
865
     */
866 3
    public function dropForeignKey($name, $table)
867
    {
868 3
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
869 3
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
870
    }
871
872
    /**
873
     * Builds a SQL statement for creating a new index.
874
     * @param string $name the name of the index. The name will be properly quoted by the method.
875
     * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
876
     * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns,
877
     * separate them with commas or use an array to represent them. Each column name will be properly quoted
878
     * by the method, unless a parenthesis is found in the name.
879
     * @param bool $unique whether to add UNIQUE constraint on the created index.
880
     * @return string the SQL statement for creating a new index.
881
     */
882 6
    public function createIndex($name, $table, $columns, $unique = false)
883
    {
884 6
        return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
885 6
            . $this->db->quoteTableName($name) . ' ON '
886 6
            . $this->db->quoteTableName($table)
887 6
            . ' (' . $this->buildColumns($columns) . ')';
888
    }
889
890
    /**
891
     * Builds a SQL statement for dropping an index.
892
     * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
893
     * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
894
     * @return string the SQL statement for dropping an index.
895
     */
896 4
    public function dropIndex($name, $table)
897
    {
898 4
        return 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON ' . $this->db->quoteTableName($table);
899
    }
900
901
    /**
902
     * Creates a SQL command for adding an unique constraint to an existing table.
903
     * @param string $name the name of the unique constraint.
904
     * The name will be properly quoted by the method.
905
     * @param string $table the table that the unique constraint will be added to.
906
     * The name will be properly quoted by the method.
907
     * @param string|array $columns the name of the column to that the constraint will be added on.
908
     * If there are multiple columns, separate them with commas.
909
     * The name will be properly quoted by the method.
910
     * @return string the SQL statement for adding an unique constraint to an existing table.
911
     * @since 2.0.13
912
     */
913 6
    public function addUnique($name, $table, $columns)
914
    {
915 6
        if (is_string($columns)) {
916 4
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
917
        }
918 6
        foreach ($columns as $i => $col) {
919 6
            $columns[$i] = $this->db->quoteColumnName($col);
920
        }
921
922 6
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
923 6
            . $this->db->quoteColumnName($name) . ' UNIQUE ('
924 6
            . implode(', ', $columns) . ')';
925
    }
926
927
    /**
928
     * Creates a SQL command for dropping an unique constraint.
929
     * @param string $name the name of the unique constraint to be dropped.
930
     * The name will be properly quoted by the method.
931
     * @param string $table the table whose unique constraint is to be dropped.
932
     * The name will be properly quoted by the method.
933
     * @return string the SQL statement for dropping an unique constraint.
934
     * @since 2.0.13
935
     */
936 2
    public function dropUnique($name, $table)
937
    {
938 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
939 2
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
940
    }
941
942
    /**
943
     * Creates a SQL command for adding a check constraint to an existing table.
944
     * @param string $name the name of the check constraint.
945
     * The name will be properly quoted by the method.
946
     * @param string $table the table that the check constraint will be added to.
947
     * The name will be properly quoted by the method.
948
     * @param string $expression the SQL of the `CHECK` constraint.
949
     * @return string the SQL statement for adding a check constraint to an existing table.
950
     * @since 2.0.13
951
     */
952 2
    public function addCheck($name, $table, $expression)
953
    {
954 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
955 2
            . $this->db->quoteColumnName($name) . ' CHECK (' . $this->db->quoteSql($expression) . ')';
956
    }
957
958
    /**
959
     * Creates a SQL command for dropping a check constraint.
960
     * @param string $name the name of the check constraint to be dropped.
961
     * The name will be properly quoted by the method.
962
     * @param string $table the table whose check constraint is to be dropped.
963
     * The name will be properly quoted by the method.
964
     * @return string the SQL statement for dropping a check constraint.
965
     * @since 2.0.13
966
     */
967 2
    public function dropCheck($name, $table)
968
    {
969 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
970 2
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
971
    }
972
973
    /**
974
     * Creates a SQL command for adding a default value constraint to an existing table.
975
     * @param string $name the name of the default value constraint.
976
     * The name will be properly quoted by the method.
977
     * @param string $table the table that the default value constraint will be added to.
978
     * The name will be properly quoted by the method.
979
     * @param string $column the name of the column to that the constraint will be added on.
980
     * The name will be properly quoted by the method.
981
     * @param mixed $value default value.
982
     * @return string the SQL statement for adding a default value constraint to an existing table.
983
     * @throws NotSupportedException if this is not supported by the underlying DBMS.
984
     * @since 2.0.13
985
     */
986
    public function addDefaultValue($name, $table, $column, $value)
987
    {
988
        throw new NotSupportedException($this->db->getDriverName() . ' does not support adding default value constraints.');
989
    }
990
991
    /**
992
     * Creates a SQL command for dropping a default value constraint.
993
     * @param string $name the name of the default value constraint to be dropped.
994
     * The name will be properly quoted by the method.
995
     * @param string $table the table whose default value constraint is to be dropped.
996
     * The name will be properly quoted by the method.
997
     * @return string the SQL statement for dropping a default value constraint.
998
     * @throws NotSupportedException if this is not supported by the underlying DBMS.
999
     * @since 2.0.13
1000
     */
1001
    public function dropDefaultValue($name, $table)
1002
    {
1003
        throw new NotSupportedException($this->db->getDriverName() . ' does not support dropping default value constraints.');
1004
    }
1005
1006
    /**
1007
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
1008
     * The sequence will be reset such that the primary key of the next new row inserted
1009
     * will have the specified value or 1.
1010
     * @param string $table the name of the table whose primary key sequence will be reset
1011
     * @param array|string $value the value for the primary key of the next new row inserted. If this is not set,
1012
     * the next new row's primary key will have a value 1.
1013
     * @return string the SQL statement for resetting sequence
1014
     * @throws NotSupportedException if this is not supported by the underlying DBMS
1015
     */
1016
    public function resetSequence($table, $value = null)
1017
    {
1018
        throw new NotSupportedException($this->db->getDriverName() . ' does not support resetting sequence.');
1019
    }
1020
1021
    /**
1022
     * Builds a SQL statement for enabling or disabling integrity check.
1023
     * @param bool $check whether to turn on or off the integrity check.
1024
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
1025
     * @param string $table the table name. Defaults to empty string, meaning that no table will be changed.
1026
     * @return string the SQL statement for checking integrity
1027
     * @throws NotSupportedException if this is not supported by the underlying DBMS
1028
     */
1029
    public function checkIntegrity($check = true, $schema = '', $table = '')
1030
    {
1031
        throw new NotSupportedException($this->db->getDriverName() . ' does not support enabling/disabling integrity check.');
1032
    }
1033
1034
    /**
1035
     * Builds a SQL command for adding comment to column.
1036
     *
1037
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
1038
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
1039
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
1040
     * @return string the SQL statement for adding comment on column
1041
     * @since 2.0.8
1042
     */
1043 2
    public function addCommentOnColumn($table, $column, $comment)
1044
    {
1045 2
        return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . ' IS ' . $this->db->quoteValue($comment);
1046
    }
1047
1048
    /**
1049
     * Builds a SQL command for adding comment to table.
1050
     *
1051
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
1052
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
1053
     * @return string the SQL statement for adding comment on table
1054
     * @since 2.0.8
1055
     */
1056 1
    public function addCommentOnTable($table, $comment)
1057
    {
1058 1
        return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS ' . $this->db->quoteValue($comment);
1059
    }
1060
1061
    /**
1062
     * Builds a SQL command for adding comment to column.
1063
     *
1064
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
1065
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
1066
     * @return string the SQL statement for adding comment on column
1067
     * @since 2.0.8
1068
     */
1069 2
    public function dropCommentFromColumn($table, $column)
1070
    {
1071 2
        return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . ' IS NULL';
1072
    }
1073
1074
    /**
1075
     * Builds a SQL command for adding comment to table.
1076
     *
1077
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
1078
     * @return string the SQL statement for adding comment on column
1079
     * @since 2.0.8
1080
     */
1081 1
    public function dropCommentFromTable($table)
1082
    {
1083 1
        return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS NULL';
1084
    }
1085
1086
    /**
1087
     * Creates a SQL View.
1088
     *
1089
     * @param string $viewName the name of the view to be created.
1090
     * @param string|Query $subQuery the select statement which defines the view.
1091
     * This can be either a string or a [[Query]] object.
1092
     * @return string the `CREATE VIEW` SQL statement.
1093
     * @since 2.0.14
1094
     */
1095 3
    public function createView($viewName, $subQuery)
1096
    {
1097 3
        if ($subQuery instanceof Query) {
1098 3
            list($rawQuery, $params) = $this->build($subQuery);
1099 3
            array_walk(
1100 3
                $params,
1101 3
                function(&$param) {
1102 3
                    $param = $this->db->quoteValue($param);
1103 3
                }
1104
            );
1105 3
            $subQuery = strtr($rawQuery, $params);
1106
        }
1107
1108 3
        return 'CREATE VIEW ' . $this->db->quoteTableName($viewName) . ' AS ' . $subQuery;
1109
    }
1110
1111
    /**
1112
     * Drops a SQL View.
1113
     *
1114
     * @param string $viewName the name of the view to be dropped.
1115
     * @return string the `DROP VIEW` SQL statement.
1116
     * @since 2.0.14
1117
     */
1118 3
    public function dropView($viewName)
1119
    {
1120 3
        return 'DROP VIEW ' . $this->db->quoteTableName($viewName);
1121
    }
1122
1123
    /**
1124
     * Converts an abstract column type into a physical column type.
1125
     *
1126
     * The conversion is done using the type map specified in [[typeMap]].
1127
     * The following abstract column types are supported (using MySQL as an example to explain the corresponding
1128
     * physical types):
1129
     *
1130
     * - `pk`: an auto-incremental primary key type, will be converted into "int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY"
1131
     * - `bigpk`: an auto-incremental primary key type, will be converted into "bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY"
1132
     * - `upk`: an unsigned auto-incremental primary key type, will be converted into "int(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY"
1133
     * - `char`: char type, will be converted into "char(1)"
1134
     * - `string`: string type, will be converted into "varchar(255)"
1135
     * - `text`: a long string type, will be converted into "text"
1136
     * - `smallint`: a small integer type, will be converted into "smallint(6)"
1137
     * - `integer`: integer type, will be converted into "int(11)"
1138
     * - `bigint`: a big integer type, will be converted into "bigint(20)"
1139
     * - `boolean`: boolean type, will be converted into "tinyint(1)"
1140
     * - `float``: float number type, will be converted into "float"
1141
     * - `decimal`: decimal number type, will be converted into "decimal"
1142
     * - `datetime`: datetime type, will be converted into "datetime"
1143
     * - `timestamp`: timestamp type, will be converted into "timestamp"
1144
     * - `time`: time type, will be converted into "time"
1145
     * - `date`: date type, will be converted into "date"
1146
     * - `money`: money type, will be converted into "decimal(19,4)"
1147
     * - `binary`: binary data type, will be converted into "blob"
1148
     *
1149
     * If the abstract type contains two or more parts separated by spaces (e.g. "string NOT NULL"), then only
1150
     * the first part will be converted, and the rest of the parts will be appended to the converted result.
1151
     * For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'.
1152
     *
1153
     * For some of the abstract types you can also specify a length or precision constraint
1154
     * by appending it in round brackets directly to the type.
1155
     * For example `string(32)` will be converted into "varchar(32)" on a MySQL database.
1156
     * If the underlying DBMS does not support these kind of constraints for a type it will
1157
     * be ignored.
1158
     *
1159
     * If a type cannot be found in [[typeMap]], it will be returned without any change.
1160
     * @param string|ColumnSchemaBuilder $type abstract column type
1161
     * @return string physical column type.
1162
     */
1163 141
    public function getColumnType($type)
1164
    {
1165 141
        if ($type instanceof ColumnSchemaBuilder) {
1166 33
            $type = $type->__toString();
1167
        }
1168
1169 141
        if (isset($this->typeMap[$type])) {
1170 128
            return $this->typeMap[$type];
1171 77
        } elseif (preg_match('/^(\w+)\((.+?)\)(.*)$/', $type, $matches)) {
1172 39
            if (isset($this->typeMap[$matches[1]])) {
1173 39
                return preg_replace('/\(.+\)/', '(' . $matches[2] . ')', $this->typeMap[$matches[1]]) . $matches[3];
1174
            }
1175 52
        } elseif (preg_match('/^(\w+)\s+/', $type, $matches)) {
1176 49
            if (isset($this->typeMap[$matches[1]])) {
1177 49
                return preg_replace('/^\w+/', $this->typeMap[$matches[1]], $type);
1178
            }
1179
        }
1180
1181 32
        return $type;
1182
    }
1183
1184
    /**
1185
     * @param array $columns
1186
     * @param array $params the binding parameters to be populated
1187
     * @param bool $distinct
1188
     * @param string $selectOption
1189
     * @return string the SELECT clause built from [[Query::$select]].
1190
     */
1191 1153
    public function buildSelect($columns, &$params, $distinct = false, $selectOption = null)
1192
    {
1193 1153
        $select = $distinct ? 'SELECT DISTINCT' : 'SELECT';
1194 1153
        if ($selectOption !== null) {
1195
            $select .= ' ' . $selectOption;
1196
        }
1197
1198 1153
        if (empty($columns)) {
1199 888
            return $select . ' *';
1200
        }
1201
1202 546
        foreach ($columns as $i => $column) {
1203 546
            if ($column instanceof ExpressionInterface) {
1204 42
                if (is_int($i)) {
1205 6
                    $columns[$i] = $this->buildExpression($column, $params);
1206
                } else {
1207 42
                    $columns[$i] = $this->buildExpression($column, $params) . ' AS ' . $this->db->quoteColumnName($i);
1208
                }
1209 537
            } elseif ($column instanceof Query) {
1210
                list($sql, $params) = $this->build($column, $params);
1211
                $columns[$i] = "($sql) AS " . $this->db->quoteColumnName($i);
1212 537
            } elseif (is_string($i)) {
1213 23
                if (strpos($column, '(') === false) {
1214 23
                    $column = $this->db->quoteColumnName($column);
1215
                }
1216 23
                $columns[$i] = "$column AS " . $this->db->quoteColumnName($i);
1217 532
            } elseif (strpos($column, '(') === false) {
1218 448
                if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $column, $matches)) {
1219 6
                    $columns[$i] = $this->db->quoteColumnName($matches[1]) . ' AS ' . $this->db->quoteColumnName($matches[2]);
1220
                } else {
1221 546
                    $columns[$i] = $this->db->quoteColumnName($column);
1222
                }
1223
            }
1224
        }
1225
1226 546
        return $select . ' ' . implode(', ', $columns);
1227
    }
1228
1229
    /**
1230
     * @param array $tables
1231
     * @param array $params the binding parameters to be populated
1232
     * @return string the FROM clause built from [[Query::$from]].
1233
     */
1234 1153
    public function buildFrom($tables, &$params)
1235
    {
1236 1153
        if (empty($tables)) {
1237 349
            return '';
1238
        }
1239
1240 841
        $tables = $this->quoteTableNames($tables, $params);
1241
1242 841
        return 'FROM ' . implode(', ', $tables);
1243
    }
1244
1245
    /**
1246
     * @param array $joins
1247
     * @param array $params the binding parameters to be populated
1248
     * @return string the JOIN clause built from [[Query::$join]].
1249
     * @throws Exception if the $joins parameter is not in proper format
1250
     */
1251 1153
    public function buildJoin($joins, &$params)
1252
    {
1253 1153
        if (empty($joins)) {
1254 1141
            return '';
1255
        }
1256
1257 54
        foreach ($joins as $i => $join) {
1258 54
            if (!is_array($join) || !isset($join[0], $join[1])) {
1259
                throw new Exception('A join clause must be specified as an array of join type, join table, and optionally join condition.');
1260
            }
1261
            // 0:join type, 1:join table, 2:on-condition (optional)
1262 54
            list($joinType, $table) = $join;
1263 54
            $tables = $this->quoteTableNames((array) $table, $params);
1264 54
            $table = reset($tables);
1265 54
            $joins[$i] = "$joinType $table";
1266 54
            if (isset($join[2])) {
1267 54
                $condition = $this->buildCondition($join[2], $params);
1268 54
                if ($condition !== '') {
1269 54
                    $joins[$i] .= ' ON ' . $condition;
1270
                }
1271
            }
1272
        }
1273
1274 54
        return implode($this->separator, $joins);
1275
    }
1276
1277
    /**
1278
     * Quotes table names passed.
1279
     *
1280
     * @param array $tables
1281
     * @param array $params
1282
     * @return array
1283
     */
1284 841
    private function quoteTableNames($tables, &$params)
1285
    {
1286 841
        foreach ($tables as $i => $table) {
1287 841
            if ($table instanceof Query) {
1288 10
                list($sql, $params) = $this->build($table, $params);
1289 10
                $tables[$i] = "($sql) " . $this->db->quoteTableName($i);
1290 841
            } elseif (is_string($i)) {
1291 79
                if (strpos($table, '(') === false) {
1292 70
                    $table = $this->db->quoteTableName($table);
1293
                }
1294 79
                $tables[$i] = "$table " . $this->db->quoteTableName($i);
1295 820
            } elseif (strpos($table, '(') === false) {
1296 813
                if (preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $table, $matches)) { // with alias
1297 21
                    $tables[$i] = $this->db->quoteTableName($matches[1]) . ' ' . $this->db->quoteTableName($matches[2]);
1298
                } else {
1299 841
                    $tables[$i] = $this->db->quoteTableName($table);
1300
                }
1301
            }
1302
        }
1303
1304 841
        return $tables;
1305
    }
1306
1307
    /**
1308
     * @param string|array $condition
1309
     * @param array $params the binding parameters to be populated
1310
     * @return string the WHERE clause built from [[Query::$where]].
1311
     */
1312 1232
    public function buildWhere($condition, &$params)
1313
    {
1314 1232
        $where = $this->buildCondition($condition, $params);
1315
1316 1232
        return $where === '' ? '' : 'WHERE ' . $where;
1317
    }
1318
1319
    /**
1320
     * @param array $columns
1321
     * @return string the GROUP BY clause
1322
     */
1323 1153
    public function buildGroupBy($columns)
1324
    {
1325 1153
        if (empty($columns)) {
1326 1147
            return '';
1327
        }
1328 21
        foreach ($columns as $i => $column) {
1329 21
            if ($column instanceof ExpressionInterface) {
1330 3
                $columns[$i] = $this->buildExpression($column);
1331 21
            } elseif (strpos($column, '(') === false) {
1332 21
                $columns[$i] = $this->db->quoteColumnName($column);
1333
            }
1334
        }
1335
1336 21
        return 'GROUP BY ' . implode(', ', $columns);
1337
    }
1338
1339
    /**
1340
     * @param string|array $condition
1341
     * @param array $params the binding parameters to be populated
1342
     * @return string the HAVING clause built from [[Query::$having]].
1343
     */
1344 1153
    public function buildHaving($condition, &$params)
1345
    {
1346 1153
        $having = $this->buildCondition($condition, $params);
1347
1348 1153
        return $having === '' ? '' : 'HAVING ' . $having;
1349
    }
1350
1351
    /**
1352
     * Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL.
1353
     * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET)
1354
     * @param array $orderBy the order by columns. See [[Query::orderBy]] for more details on how to specify this parameter.
1355
     * @param int $limit the limit number. See [[Query::limit]] for more details.
1356
     * @param int $offset the offset number. See [[Query::offset]] for more details.
1357
     * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any)
1358
     */
1359 1153
    public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset)
1360
    {
1361 1153
        $orderBy = $this->buildOrderBy($orderBy);
1362 1153
        if ($orderBy !== '') {
1363 180
            $sql .= $this->separator . $orderBy;
1364
        }
1365 1153
        $limit = $this->buildLimit($limit, $offset);
1366 1153
        if ($limit !== '') {
1367 91
            $sql .= $this->separator . $limit;
1368
        }
1369
1370 1153
        return $sql;
1371
    }
1372
1373
    /**
1374
     * @param array $columns
1375
     * @return string the ORDER BY clause built from [[Query::$orderBy]].
1376
     */
1377 1153
    public function buildOrderBy($columns)
1378
    {
1379 1153
        if (empty($columns)) {
1380 1118
            return '';
1381
        }
1382 180
        $orders = [];
1383 180
        foreach ($columns as $name => $direction) {
1384 180
            if ($direction instanceof ExpressionInterface) {
1385 3
                $orders[] = $this->buildExpression($direction);
1386
            } else {
1387 180
                $orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : '');
1388
            }
1389
        }
1390
1391 180
        return 'ORDER BY ' . implode(', ', $orders);
1392
    }
1393
1394
    /**
1395
     * @param int $limit
1396
     * @param int $offset
1397
     * @return string the LIMIT and OFFSET clauses
1398
     */
1399 418
    public function buildLimit($limit, $offset)
1400
    {
1401 418
        $sql = '';
1402 418
        if ($this->hasLimit($limit)) {
1403 25
            $sql = 'LIMIT ' . $limit;
1404
        }
1405 418
        if ($this->hasOffset($offset)) {
1406 3
            $sql .= ' OFFSET ' . $offset;
1407
        }
1408
1409 418
        return ltrim($sql);
1410
    }
1411
1412
    /**
1413
     * Checks to see if the given limit is effective.
1414
     * @param mixed $limit the given limit
1415
     * @return bool whether the limit is effective
1416
     */
1417 757
    protected function hasLimit($limit)
1418
    {
1419 757
        return ($limit instanceof ExpressionInterface) || ctype_digit((string) $limit);
1420
    }
1421
1422
    /**
1423
     * Checks to see if the given offset is effective.
1424
     * @param mixed $offset the given offset
1425
     * @return bool whether the offset is effective
1426
     */
1427 757
    protected function hasOffset($offset)
1428
    {
1429 757
        return ($offset instanceof ExpressionInterface) || ctype_digit((string) $offset) && (string) $offset !== '0';
1430
    }
1431
1432
    /**
1433
     * @param array $unions
1434
     * @param array $params the binding parameters to be populated
1435
     * @return string the UNION clause built from [[Query::$union]].
1436
     */
1437 814
    public function buildUnion($unions, &$params)
1438
    {
1439 814
        if (empty($unions)) {
1440 814
            return '';
1441
        }
1442
1443 8
        $result = '';
1444
1445 8
        foreach ($unions as $i => $union) {
1446 8
            $query = $union['query'];
1447 8
            if ($query instanceof Query) {
1448 8
                list($unions[$i]['query'], $params) = $this->build($query, $params);
1449
            }
1450
1451 8
            $result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . '( ' . $unions[$i]['query'] . ' ) ';
1452
        }
1453
1454 8
        return trim($result);
1455
    }
1456
1457
    /**
1458
     * Processes columns and properly quotes them if necessary.
1459
     * It will join all columns into a string with comma as separators.
1460
     * @param string|array $columns the columns to be processed
1461
     * @return string the processing result
1462
     */
1463 32
    public function buildColumns($columns)
1464
    {
1465 32
        if (!is_array($columns)) {
1466 27
            if (strpos($columns, '(') !== false) {
1467
                return $columns;
1468
            }
1469
1470 27
            $rawColumns = $columns;
1471 27
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
1472 27
            if ($columns === false) {
1473
                throw new InvalidArgumentException("$rawColumns is not valid columns.");
1474
            }
1475
        }
1476 32
        foreach ($columns as $i => $column) {
1477 32
            if ($column instanceof ExpressionInterface) {
1478
                $columns[$i] = $this->buildExpression($column);
1479 32
            } elseif (strpos($column, '(') === false) {
1480 32
                $columns[$i] = $this->db->quoteColumnName($column);
1481
            }
1482
        }
1483
1484 32
        return implode(', ', $columns);
1485
    }
1486
1487
    /**
1488
     * Parses the condition specification and generates the corresponding SQL expression.
1489
     * @param string|array|ExpressionInterface $condition the condition specification. Please refer to [[Query::where()]]
1490
     * on how to specify a condition.
1491
     * @param array $params the binding parameters to be populated
1492
     * @return string the generated SQL expression
1493
     */
1494 1232
    public function buildCondition($condition, &$params)
1495
    {
1496 1232
        if (is_array($condition)) {
1497 968
            if (empty($condition)) {
1498 3
                return '';
1499
            }
1500
1501 968
            $condition = $this->createConditionFromArray($condition);
1502
        }
1503
1504 1232
        if ($condition instanceof ExpressionInterface) {
1505 989
            return $this->buildExpression($condition, $params);
1506
        }
1507
1508 1215
        return (string) $condition;
1509
    }
1510
1511
    /**
1512
     * Transforms $condition defined in array format (as described in [[Query::where()]]
1513
     * to instance of [[yii\db\condition\ConditionInterface|ConditionInterface]] according to
1514
     * [[conditionClasses]] map.
1515
     *
1516
     * @param string|array $condition
1517
     * @see conditionClasses
1518
     * @return ConditionInterface
1519
     * @since 2.0.14
1520
     */
1521 968
    public function createConditionFromArray($condition)
1522
    {
1523 968
        if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
1524 584
            $operator = strtoupper(array_shift($condition));
1525 584
            if (isset($this->conditionClasses[$operator])) {
1526 506
                $className = $this->conditionClasses[$operator];
1527
            } else {
1528 84
                $className = 'yii\db\conditions\SimpleCondition';
1529
            }
1530
            /** @var ConditionInterface $className */
1531 584
            return $className::fromArrayDefinition($operator, $condition);
1532
        }
1533
1534
        // hash format: 'column1' => 'value1', 'column2' => 'value2', ...
1535 679
        return new HashCondition($condition);
0 ignored issues
show
Bug introduced by
It seems like $condition defined by parameter $condition on line 1521 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...
1536
    }
1537
1538
    /**
1539
     * Creates a condition based on column-value pairs.
1540
     * @param array $condition the condition specification.
1541
     * @param array $params the binding parameters to be populated
1542
     * @return string the generated SQL expression
1543
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1544
     */
1545
    public function buildHashCondition($condition, &$params)
1546
    {
1547
        return $this->buildCondition(new HashCondition($condition), $params);
1548
    }
1549
1550
    /**
1551
     * Connects two or more SQL expressions with the `AND` or `OR` operator.
1552
     * @param string $operator the operator to use for connecting the given operands
1553
     * @param array $operands the SQL expressions to connect.
1554
     * @param array $params the binding parameters to be populated
1555
     * @return string the generated SQL expression
1556
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1557
     */
1558
    public function buildAndCondition($operator, $operands, &$params)
1559
    {
1560
        array_unshift($operands, $operator);
1561
        return $this->buildCondition($operands, $params);
1562
    }
1563
1564
    /**
1565
     * Inverts an SQL expressions with `NOT` operator.
1566
     * @param string $operator the operator to use for connecting the given operands
1567
     * @param array $operands the SQL expressions to connect.
1568
     * @param array $params the binding parameters to be populated
1569
     * @return string the generated SQL expression
1570
     * @throws InvalidArgumentException if wrong number of operands have been given.
1571
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1572
     */
1573
    public function buildNotCondition($operator, $operands, &$params)
1574
    {
1575
        array_unshift($operands, $operator);
1576
        return $this->buildCondition($operands, $params);
1577
    }
1578
1579
    /**
1580
     * Creates an SQL expressions with the `BETWEEN` operator.
1581
     * @param string $operator the operator to use (e.g. `BETWEEN` or `NOT BETWEEN`)
1582
     * @param array $operands the first operand is the column name. The second and third operands
1583
     * describe the interval that column value should be in.
1584
     * @param array $params the binding parameters to be populated
1585
     * @return string the generated SQL expression
1586
     * @throws InvalidArgumentException if wrong number of operands have been given.
1587
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1588
     */
1589
    public function buildBetweenCondition($operator, $operands, &$params)
1590
    {
1591
        array_unshift($operands, $operator);
1592
        return $this->buildCondition($operands, $params);
1593
    }
1594
1595
    /**
1596
     * Creates an SQL expressions with the `IN` operator.
1597
     * @param string $operator the operator to use (e.g. `IN` or `NOT IN`)
1598
     * @param array $operands the first operand is the column name. If it is an array
1599
     * a composite IN condition will be generated.
1600
     * The second operand is an array of values that column value should be among.
1601
     * If it is an empty array the generated expression will be a `false` value if
1602
     * operator is `IN` and empty if operator is `NOT IN`.
1603
     * @param array $params the binding parameters to be populated
1604
     * @return string the generated SQL expression
1605
     * @throws Exception if wrong number of operands have been given.
1606
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1607
     */
1608
    public function buildInCondition($operator, $operands, &$params)
1609
    {
1610
        array_unshift($operands, $operator);
1611
        return $this->buildCondition($operands, $params);
1612
    }
1613
1614
    /**
1615
     * Creates an SQL expressions with the `LIKE` operator.
1616
     * @param string $operator the operator to use (e.g. `LIKE`, `NOT LIKE`, `OR LIKE` or `OR NOT LIKE`)
1617
     * @param array $operands an array of two or three operands
1618
     *
1619
     * - The first operand is the column name.
1620
     * - The second operand is a single value or an array of values that column value
1621
     *   should be compared with. If it is an empty array the generated expression will
1622
     *   be a `false` value if operator is `LIKE` or `OR LIKE`, and empty if operator
1623
     *   is `NOT LIKE` or `OR NOT LIKE`.
1624
     * - An optional third operand can also be provided to specify how to escape special characters
1625
     *   in the value(s). The operand should be an array of mappings from the special characters to their
1626
     *   escaped counterparts. If this operand is not provided, a default escape mapping will be used.
1627
     *   You may use `false` or an empty array to indicate the values are already escaped and no escape
1628
     *   should be applied. Note that when using an escape mapping (or the third operand is not provided),
1629
     *   the values will be automatically enclosed within a pair of percentage characters.
1630
     * @param array $params the binding parameters to be populated
1631
     * @return string the generated SQL expression
1632
     * @throws InvalidArgumentException if wrong number of operands have been given.
1633
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1634
     */
1635
    public function buildLikeCondition($operator, $operands, &$params)
1636
    {
1637
        array_unshift($operands, $operator);
1638
        return $this->buildCondition($operands, $params);
1639
    }
1640
1641
    /**
1642
     * Creates an SQL expressions with the `EXISTS` operator.
1643
     * @param string $operator the operator to use (e.g. `EXISTS` or `NOT EXISTS`)
1644
     * @param array $operands contains only one element which is a [[Query]] object representing the sub-query.
1645
     * @param array $params the binding parameters to be populated
1646
     * @return string the generated SQL expression
1647
     * @throws InvalidArgumentException if the operand is not a [[Query]] object.
1648
     * @deprecated since 2.0.14. Use `buildCondition()` instead.
1649
     */
1650
    public function buildExistsCondition($operator, $operands, &$params)
1651
    {
1652
        array_unshift($operands, $operator);
1653
        return $this->buildCondition($operands, $params);
1654
    }
1655
1656
    /**
1657
     * Creates an SQL expressions like `"column" operator value`.
1658
     * @param string $operator the operator to use. Anything could be used e.g. `>`, `<=`, etc.
1659
     * @param array $operands contains two column names.
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 buildSimpleCondition($operator, $operands, &$params)
1666
    {
1667
        array_unshift($operands, $operator);
1668
        return $this->buildCondition($operands, $params);
1669
    }
1670
1671
    /**
1672
     * Creates a SELECT EXISTS() SQL statement.
1673
     * @param string $rawSql the subquery in a raw form to select from.
1674
     * @return string the SELECT EXISTS() SQL statement.
1675
     * @since 2.0.8
1676
     */
1677 67
    public function selectExists($rawSql)
1678
    {
1679 67
        return 'SELECT EXISTS(' . $rawSql . ')';
1680
    }
1681
1682
    /**
1683
     * Helper method to add $value to $params array using [[PARAM_PREFIX]].
1684
     *
1685
     * @param string|null $value
1686
     * @param array $params passed by reference
1687
     * @return string the placeholder name in $params array
1688
     *
1689
     * @since 2.0.14
1690
     */
1691 1022
    public function bindParam($value, &$params)
1692
    {
1693 1022
        $phName = self::PARAM_PREFIX . count($params);
1694 1022
        $params[$phName] = $value;
1695
1696 1022
        return $phName;
1697
    }
1698
}
1699