Completed
Push — master ( c54ead...79679b )
by Dmitry
15:11 queued 21s
created

QueryBuilder::dropColumn()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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