Completed
Push — query-alias ( e06046...9802bc )
by Carsten
40:39
created

QueryBuilder::build()   C

Complexity

Conditions 9
Paths 16

Size

Total Lines 49
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 37
CRAP Score 9

Importance

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