Completed
Push — master ( be658f...d6bd62 )
by Carsten
68:33 queued 62:00
created

QueryBuilder::renameColumn()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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