QueryBuilder.php 41.4 KB
Newer Older
w  
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
w  
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
8
namespace yii\db;
w  
Qiang Xue committed
9

10
use yii\base\InvalidParamException;
Qiang Xue committed
11
use yii\base\NotSupportedException;
w  
Qiang Xue committed
12

w  
Qiang Xue committed
13
/**
Qiang Xue committed
14
 * QueryBuilder builds a SELECT SQL statement based on the specification given as a [[Query]] object.
w  
Qiang Xue committed
15
 *
Qiang Xue committed
16
 * QueryBuilder can also be used to build SQL statements such as INSERT, UPDATE, DELETE, CREATE TABLE,
Qiang Xue committed
17 18
 * from a [[Query]] object.
 *
w  
Qiang Xue committed
19 20 21
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
22
class QueryBuilder extends \yii\base\Object
w  
Qiang Xue committed
23
{
24 25 26 27 28
	/**
	 * The prefix for automatically generated query binding parameters.
	 */
	const PARAM_PREFIX = ':qp';

Qiang Xue committed
29 30 31
	/**
	 * @var Connection the database connection.
	 */
Qiang Xue committed
32
	public $db;
Qiang Xue committed
33 34 35 36 37
	/**
	 * @var string the separator between different fragments of a SQL statement.
	 * Defaults to an empty space. This is mainly used by [[build()]] when generating a SQL statement.
	 */
	public $separator = " ";
Qiang Xue committed
38 39 40 41 42
	/**
	 * @var array the abstract column types mapped to physical column types.
	 * This is mainly used to support creating/modifying tables using DB-independent data type specifications.
	 * Child classes should override this property to declare supported type mappings.
	 */
Alexander Makarov committed
43
	public $typeMap = [];
w  
Qiang Xue committed
44

Qiang Xue committed
45 46
	/**
	 * Constructor.
Qiang Xue committed
47
	 * @param Connection $connection the database connection.
Qiang Xue committed
48
	 * @param array $config name-value pairs that will be used to initialize the object properties
Qiang Xue committed
49
	 */
Alexander Makarov committed
50
	public function __construct($connection, $config = [])
w  
Qiang Xue committed
51
	{
Qiang Xue committed
52
		$this->db = $connection;
Qiang Xue committed
53
		parent::__construct($config);
w  
Qiang Xue committed
54 55
	}

Qiang Xue committed
56
	/**
Qiang Xue committed
57
	 * Generates a SELECT SQL statement from a [[Query]] object.
58 59 60
	 * @param Query $query the [[Query]] object from which the SQL statement will be generated.
	 * @param array $params the parameters to be bound to the generated SQL statement. These parameters will
	 * be included in the result with the additional parameters generated during the query building process.
61
	 * @return array the generated SQL statement (the first array element) and the corresponding
62 63
	 * parameters to be bound to the SQL statement (the second array element). The parameters returned
	 * include those provided in `$params`.
Qiang Xue committed
64
	 */
65
	public function build($query, $params = [])
w  
Qiang Xue committed
66
	{
67 68 69 70 71 72 73 74 75 76 77 78 79 80
		$params = empty($params) ? $query->params : array_merge($params, $query->params);

		$select = $query->select;
		$from = $query->from;
		if ($from === null && $query instanceof ActiveQuery) {
			/** @var ActiveRecord $modelClass */
			$modelClass = $query->modelClass;
			$tableName = $modelClass::tableName();
			$from = [$tableName];
			if ($select === null && !empty($query->join)) {
				$select = ["$tableName.*"];
			}
		}

Alexander Makarov committed
81
		$clauses = [
82 83
			$this->buildSelect($select, $params, $query->distinct, $query->selectOption),
			$this->buildFrom($from, $params),
84 85
			$this->buildJoin($query->join, $params),
			$this->buildWhere($query->where, $params),
Qiang Xue committed
86
			$this->buildGroupBy($query->groupBy),
87
			$this->buildHaving($query->having, $params),
Qiang Xue committed
88
			$this->buildOrderBy($query->orderBy),
Qiang Xue committed
89
			$this->buildLimit($query->limit, $query->offset),
90
			$this->buildUnion($query->union, $params),
Alexander Makarov committed
91 92
		];
		return [implode($this->separator, array_filter($clauses)), $params];
w  
Qiang Xue committed
93 94 95
	}

	/**
Qiang Xue committed
96
	 * Creates an INSERT SQL statement.
Qiang Xue committed
97 98 99
	 * For example,
	 *
	 * ~~~
Alexander Makarov committed
100
	 * $sql = $queryBuilder->insert('tbl_user', [
Qiang Xue committed
101 102
	 *	 'name' => 'Sam',
	 *	 'age' => 30,
Alexander Makarov committed
103
	 * ], $params);
Qiang Xue committed
104 105
	 * ~~~
	 *
Qiang Xue committed
106 107
	 * The method will properly escape the table and column names.
	 *
w  
Qiang Xue committed
108
	 * @param string $table the table that new rows will be inserted into.
resurtm committed
109
	 * @param array $columns the column data (name => value) to be inserted into the table.
Qiang Xue committed
110 111
	 * @param array $params the binding parameters that will be generated by this method.
	 * They should be bound to the DB command later.
112
	 * @return string the INSERT SQL
w  
Qiang Xue committed
113
	 */
Qiang Xue committed
114
	public function insert($table, $columns, &$params)
w  
Qiang Xue committed
115
	{
116 117 118
		if (($tableSchema = $this->db->getTableSchema($table)) !== null) {
			$columnSchemas = $tableSchema->columns;
		} else {
Alexander Makarov committed
119
			$columnSchemas = [];
120
		}
Alexander Makarov committed
121 122
		$names = [];
		$placeholders = [];
w  
Qiang Xue committed
123
		foreach ($columns as $name => $value) {
Qiang Xue committed
124
			$names[] = $this->db->quoteColumnName($name);
w  
Qiang Xue committed
125 126 127 128 129
			if ($value instanceof Expression) {
				$placeholders[] = $value->expression;
				foreach ($value->params as $n => $v) {
					$params[$n] = $v;
				}
Qiang Xue committed
130
			} else {
131 132
				$phName = self::PARAM_PREFIX . count($params);
				$placeholders[] = $phName;
Qiang Xue committed
133
				$params[$phName] = !is_array($value) && isset($columnSchemas[$name]) ? $columnSchemas[$name]->typecast($value) : $value;
w  
Qiang Xue committed
134 135 136
			}
		}

Qiang Xue committed
137
		return 'INSERT INTO ' . $this->db->quoteTableName($table)
w  
Qiang Xue committed
138 139 140 141
			. ' (' . implode(', ', $names) . ') VALUES ('
			. implode(', ', $placeholders) . ')';
	}

Qiang Xue committed
142 143 144 145 146
	/**
	 * Generates a batch INSERT SQL statement.
	 * For example,
	 *
	 * ~~~
147
	 * $sql = $queryBuilder->batchInsert('tbl_user', ['name', 'age'], [
Alexander Makarov committed
148 149 150
	 *     ['Tom', 30],
	 *     ['Jane', 20],
	 *     ['Linda', 25],
151
	 * ]);
Qiang Xue committed
152 153
	 * ~~~
	 *
154
	 * Note that the values in each row must match the corresponding column names.
Qiang Xue committed
155 156 157 158 159 160
	 *
	 * @param string $table the table that new rows will be inserted into.
	 * @param array $columns the column names
	 * @param array $rows the rows to be batch inserted into the table
	 * @return string the batch INSERT SQL statement
	 */
161
	public function batchInsert($table, $columns, $rows)
Qiang Xue committed
162
	{
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
		if (($tableSchema = $this->db->getTableSchema($table)) !== null) {
			$columnSchemas = $tableSchema->columns;
		} else {
			$columnSchemas = [];
		}

		foreach ($columns as $i => $name) {
			$columns[$i] = $this->db->quoteColumnName($name);
		}

		$values = [];
		foreach ($rows as $row) {
			$vs = [];
			foreach ($row as $i => $value) {
				if (!is_array($value) && isset($columnSchemas[$columns[$i]])) {
					$value = $columnSchemas[$columns[$i]]->typecast($value);
				}
180 181
				$vs[] = is_string($value) ? $this->db->quoteValue($value)
					: ( is_null($value) ? 'null' : $value );
182 183 184
			}
			$values[] = '(' . implode(', ', $vs) . ')';
		}
Qiang Xue committed
185

186 187
		return 'INSERT INTO ' . $this->db->quoteTableName($table)
		. ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
Qiang Xue committed
188 189
	}

w  
Qiang Xue committed
190
	/**
Qiang Xue committed
191
	 * Creates an UPDATE SQL statement.
Qiang Xue committed
192 193 194
	 * For example,
	 *
	 * ~~~
Alexander Makarov committed
195 196
	 * $params = [];
	 * $sql = $queryBuilder->update('tbl_user', ['status' => 1], 'age > 30', $params);
Qiang Xue committed
197 198
	 * ~~~
	 *
Qiang Xue committed
199 200
	 * The method will properly escape the table and column names.
	 *
w  
Qiang Xue committed
201
	 * @param string $table the table to be updated.
resurtm committed
202
	 * @param array $columns the column data (name => value) to be updated.
203
	 * @param array|string $condition the condition that will be put in the WHERE part. Please
Qiang Xue committed
204
	 * refer to [[Query::where()]] on how to specify condition.
Qiang Xue committed
205 206
	 * @param array $params the binding parameters that will be modified by this method
	 * so that they can be bound to the DB command later.
207
	 * @return string the UPDATE SQL
w  
Qiang Xue committed
208
	 */
209
	public function update($table, $columns, $condition, &$params)
w  
Qiang Xue committed
210
	{
211 212 213
		if (($tableSchema = $this->db->getTableSchema($table)) !== null) {
			$columnSchemas = $tableSchema->columns;
		} else {
Alexander Makarov committed
214
			$columnSchemas = [];
215 216
		}

Alexander Makarov committed
217
		$lines = [];
w  
Qiang Xue committed
218 219
		foreach ($columns as $name => $value) {
			if ($value instanceof Expression) {
Qiang Xue committed
220
				$lines[] = $this->db->quoteColumnName($name) . '=' . $value->expression;
w  
Qiang Xue committed
221 222 223
				foreach ($value->params as $n => $v) {
					$params[$n] = $v;
				}
Qiang Xue committed
224
			} else {
225 226
				$phName = self::PARAM_PREFIX . count($params);
				$lines[] = $this->db->quoteColumnName($name) . '=' . $phName;
Qiang Xue committed
227
				$params[$phName] = !is_array($value) && isset($columnSchemas[$name]) ? $columnSchemas[$name]->typecast($value) : $value;
w  
Qiang Xue committed
228 229
			}
		}
w  
Qiang Xue committed
230

231 232 233
		$sql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $lines);
		$where = $this->buildWhere($condition, $params);
		return $where === '' ? $sql : $sql . ' ' . $where;
w  
Qiang Xue committed
234 235 236
	}

	/**
Qiang Xue committed
237
	 * Creates a DELETE SQL statement.
Qiang Xue committed
238 239 240 241 242 243
	 * For example,
	 *
	 * ~~~
	 * $sql = $queryBuilder->delete('tbl_user', 'status = 0');
	 * ~~~
	 *
Qiang Xue committed
244 245
	 * The method will properly escape the table and column names.
	 *
w  
Qiang Xue committed
246
	 * @param string $table the table where the data will be deleted from.
247
	 * @param array|string $condition the condition that will be put in the WHERE part. Please
Qiang Xue committed
248
	 * refer to [[Query::where()]] on how to specify condition.
249 250
	 * @param array $params the binding parameters that will be modified by this method
	 * so that they can be bound to the DB command later.
251
	 * @return string the DELETE SQL
w  
Qiang Xue committed
252
	 */
253
	public function delete($table, $condition, &$params)
w  
Qiang Xue committed
254
	{
Qiang Xue committed
255
		$sql = 'DELETE FROM ' . $this->db->quoteTableName($table);
256 257
		$where = $this->buildWhere($condition, $params);
		return $where === '' ? $sql : $sql . ' ' . $where;
w  
Qiang Xue committed
258 259
	}

w  
Qiang Xue committed
260 261 262
	/**
	 * Builds a SQL statement for creating a new DB table.
	 *
resurtm committed
263
	 * The columns in the new  table should be specified as name-definition pairs (e.g. 'name' => 'string'),
w  
Qiang Xue committed
264 265
	 * where name stands for a column name which will be properly quoted by the method, and definition
	 * stands for the column type which can contain an abstract DB type.
Qiang Xue committed
266
	 * The [[getColumnType()]] method will be invoked to convert any abstract type into a physical one.
w  
Qiang Xue committed
267 268 269 270
	 *
	 * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
	 * inserted into the generated SQL.
	 *
Qiang Xue committed
271 272 273
	 * For example,
	 *
	 * ~~~
Alexander Makarov committed
274
	 * $sql = $queryBuilder->createTable('tbl_user', [
Qiang Xue committed
275 276 277
	 *	 'id' => 'pk',
	 *	 'name' => 'string',
	 *	 'age' => 'integer',
Alexander Makarov committed
278
	 * ]);
Qiang Xue committed
279 280
	 * ~~~
	 *
w  
Qiang Xue committed
281
	 * @param string $table the name of the table to be created. The name will be properly quoted by the method.
resurtm committed
282
	 * @param array $columns the columns (name => definition) in the new table.
w  
Qiang Xue committed
283 284 285 286 287
	 * @param string $options additional SQL fragment that will be appended to the generated SQL.
	 * @return string the SQL statement for creating a new DB table.
	 */
	public function createTable($table, $columns, $options = null)
	{
Alexander Makarov committed
288
		$cols = [];
w  
Qiang Xue committed
289 290
		foreach ($columns as $name => $type) {
			if (is_string($name)) {
Qiang Xue committed
291
				$cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type);
Qiang Xue committed
292
			} else {
w  
Qiang Xue committed
293
				$cols[] = "\t" . $type;
Qiang Xue committed
294
			}
w  
Qiang Xue committed
295
		}
Qiang Xue committed
296
		$sql = "CREATE TABLE " . $this->db->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)";
w  
Qiang Xue committed
297 298 299 300 301
		return $options === null ? $sql : $sql . ' ' . $options;
	}

	/**
	 * Builds a SQL statement for renaming a DB table.
Qiang Xue committed
302
	 * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
w  
Qiang Xue committed
303 304 305
	 * @param string $newName the new table name. The name will be properly quoted by the method.
	 * @return string the SQL statement for renaming a DB table.
	 */
Qiang Xue committed
306
	public function renameTable($oldName, $newName)
w  
Qiang Xue committed
307
	{
Qiang Xue committed
308
		return 'RENAME TABLE ' . $this->db->quoteTableName($oldName) . ' TO ' . $this->db->quoteTableName($newName);
w  
Qiang Xue committed
309 310 311 312 313 314 315 316 317
	}

	/**
	 * Builds a SQL statement for dropping a DB table.
	 * @param string $table the table to be dropped. The name will be properly quoted by the method.
	 * @return string the SQL statement for dropping a DB table.
	 */
	public function dropTable($table)
	{
Qiang Xue committed
318
		return "DROP TABLE " . $this->db->quoteTableName($table);
w  
Qiang Xue committed
319
	}
320

321 322 323 324 325 326 327
	/**
	 * Builds a SQL statement for adding a primary key constraint to an existing table.
	 * @param string $name the name of the primary key constraint.
	 * @param string $table the table that the primary key constraint will be added to.
	 * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
	 * @return string the SQL statement for adding a primary key constraint to an existing table.
	 */
328
	public function addPrimaryKey($name, $table, $columns)
329
	{
330
		if (is_string($columns)) {
Alexander Makarov committed
331
			$columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
332
		}
Alexander Makarov committed
333 334 335

		foreach ($columns as $i => $col) {
			$columns[$i] = $this->db->quoteColumnName($col);
336
		}
337

338 339
		return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
			. $this->db->quoteColumnName($name) . '  PRIMARY KEY ('
340
			. implode(', ', $columns). ' )';
Alexander Makarov committed
341
	}
342

343
	/**
344 345 346 347
	 * Builds a SQL statement for removing a primary key constraint to an existing table.
	 * @param string $name the name of the primary key constraint to be removed.
	 * @param string $table the table that the primary key constraint will be removed from.
	 * @return string the SQL statement for removing a primary key constraint from an existing table.	 *
348
	 */
349
	public function dropPrimaryKey($name, $table)
350
	{
351 352
		return 'ALTER TABLE ' . $this->db->quoteTableName($table)
			. ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
Alexander Makarov committed
353
	}
w  
Qiang Xue committed
354 355 356 357 358 359 360

	/**
	 * Builds a SQL statement for truncating a DB table.
	 * @param string $table the table to be truncated. The name will be properly quoted by the method.
	 * @return string the SQL statement for truncating a DB table.
	 */
	public function truncateTable($table)
w  
Qiang Xue committed
361
	{
Qiang Xue committed
362
		return "TRUNCATE TABLE " . $this->db->quoteTableName($table);
w  
Qiang Xue committed
363 364 365 366 367 368
	}

	/**
	 * Builds a SQL statement for adding a new DB column.
	 * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
	 * @param string $column the name of the new column. The name will be properly quoted by the method.
Qiang Xue committed
369
	 * @param string $type the column type. The [[getColumnType()]] method will be invoked to convert abstract column type (if any)
w  
Qiang Xue committed
370 371 372 373 374 375
	 * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
	 * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
	 * @return string the SQL statement for adding a new column.
	 */
	public function addColumn($table, $column, $type)
	{
Qiang Xue committed
376 377
		return 'ALTER TABLE ' . $this->db->quoteTableName($table)
			. ' ADD ' . $this->db->quoteColumnName($column) . ' '
w  
Qiang Xue committed
378 379
			. $this->getColumnType($type);
	}
w  
Qiang Xue committed
380

w  
Qiang Xue committed
381 382 383 384 385 386 387 388
	/**
	 * Builds a SQL statement for dropping a DB column.
	 * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
	 * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
	 * @return string the SQL statement for dropping a DB column.
	 */
	public function dropColumn($table, $column)
	{
Qiang Xue committed
389 390
		return "ALTER TABLE " . $this->db->quoteTableName($table)
			. " DROP COLUMN " . $this->db->quoteColumnName($column);
w  
Qiang Xue committed
391 392 393 394 395
	}

	/**
	 * Builds a SQL statement for renaming a column.
	 * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
Qiang Xue committed
396
	 * @param string $oldName the old name of the column. The name will be properly quoted by the method.
w  
Qiang Xue committed
397 398 399
	 * @param string $newName the new name of the column. The name will be properly quoted by the method.
	 * @return string the SQL statement for renaming a DB column.
	 */
Qiang Xue committed
400
	public function renameColumn($table, $oldName, $newName)
w  
Qiang Xue committed
401
	{
Qiang Xue committed
402 403 404
		return "ALTER TABLE " . $this->db->quoteTableName($table)
			. " RENAME COLUMN " . $this->db->quoteColumnName($oldName)
			. " TO " . $this->db->quoteColumnName($newName);
w  
Qiang Xue committed
405 406 407 408 409 410
	}

	/**
	 * Builds a SQL statement for changing the definition of a column.
	 * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
	 * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
Qiang Xue committed
411 412 413 414
	 * @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract
	 * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
	 * in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
	 * will become 'varchar(255) not null'.
w  
Qiang Xue committed
415 416 417 418
	 * @return string the SQL statement for changing the definition of a column.
	 */
	public function alterColumn($table, $column, $type)
	{
Qiang Xue committed
419 420 421
		return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
			. $this->db->quoteColumnName($column) . ' '
			. $this->db->quoteColumnName($column) . ' '
w  
Qiang Xue committed
422 423 424 425 426 427 428 429
			. $this->getColumnType($type);
	}

	/**
	 * Builds a SQL statement for adding a foreign key constraint to an existing table.
	 * The method will properly quote the table and column names.
	 * @param string $name the name of the foreign key constraint.
	 * @param string $table the table that the foreign key constraint will be added to.
Qiang Xue committed
430 431
	 * @param string|array $columns the name of the column to that the constraint will be added on.
	 * If there are multiple columns, separate them with commas or use an array to represent them.
w  
Qiang Xue committed
432
	 * @param string $refTable the table that the foreign key references to.
Qiang Xue committed
433 434
	 * @param string|array $refColumns the name of the column that the foreign key references to.
	 * If there are multiple columns, separate them with commas or use an array to represent them.
w  
Qiang Xue committed
435 436 437 438 439 440
	 * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
	 * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
	 * @return string the SQL statement for adding a foreign key constraint to an existing table.
	 */
	public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
	{
Qiang Xue committed
441 442
		$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
			. ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name)
Qiang Xue committed
443
			. ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
Qiang Xue committed
444
			. ' REFERENCES ' . $this->db->quoteTableName($refTable)
Qiang Xue committed
445
			. ' (' . $this->buildColumns($refColumns) . ')';
Qiang Xue committed
446
		if ($delete !== null) {
w  
Qiang Xue committed
447
			$sql .= ' ON DELETE ' . $delete;
Qiang Xue committed
448 449
		}
		if ($update !== null) {
w  
Qiang Xue committed
450
			$sql .= ' ON UPDATE ' . $update;
Qiang Xue committed
451
		}
w  
Qiang Xue committed
452 453 454 455 456 457 458 459 460 461 462
		return $sql;
	}

	/**
	 * Builds a SQL statement for dropping a foreign key constraint.
	 * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
	 * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
	 * @return string the SQL statement for dropping a foreign key constraint.
	 */
	public function dropForeignKey($name, $table)
	{
Qiang Xue committed
463 464
		return 'ALTER TABLE ' . $this->db->quoteTableName($table)
			. ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
w  
Qiang Xue committed
465 466 467 468 469 470
	}

	/**
	 * Builds a SQL statement for creating a new index.
	 * @param string $name the name of the index. The name will be properly quoted by the method.
	 * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
Qiang Xue committed
471 472 473
	 * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns,
	 * separate them with commas or use an array to represent them. Each column name will be properly quoted
	 * by the method, unless a parenthesis is found in the name.
w  
Qiang Xue committed
474 475 476
	 * @param boolean $unique whether to add UNIQUE constraint on the created index.
	 * @return string the SQL statement for creating a new index.
	 */
Qiang Xue committed
477
	public function createIndex($name, $table, $columns, $unique = false)
w  
Qiang Xue committed
478 479
	{
		return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
Qiang Xue committed
480 481
			. $this->db->quoteTableName($name) . ' ON '
			. $this->db->quoteTableName($table)
Qiang Xue committed
482
			. ' (' . $this->buildColumns($columns) . ')';
w  
Qiang Xue committed
483 484 485 486 487 488 489 490 491 492
	}

	/**
	 * Builds a SQL statement for dropping an index.
	 * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
	 * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
	 * @return string the SQL statement for dropping an index.
	 */
	public function dropIndex($name, $table)
	{
Qiang Xue committed
493
		return 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON ' . $this->db->quoteTableName($table);
w  
Qiang Xue committed
494 495
	}

w  
Qiang Xue committed
496
	/**
Qiang Xue committed
497
	 * Creates a SQL statement for resetting the sequence value of a table's primary key.
w  
Qiang Xue committed
498 499
	 * The sequence will be reset such that the primary key of the next new row inserted
	 * will have the specified value or 1.
Qiang Xue committed
500
	 * @param string $table the name of the table whose primary key sequence will be reset
501
	 * @param array|string $value the value for the primary key of the next new row inserted. If this is not set,
w  
Qiang Xue committed
502
	 * the next new row's primary key will have a value 1.
Qiang Xue committed
503 504
	 * @return string the SQL statement for resetting sequence
	 * @throws NotSupportedException if this is not supported by the underlying DBMS
w  
Qiang Xue committed
505 506 507
	 */
	public function resetSequence($table, $value = null)
	{
Qiang Xue committed
508
		throw new NotSupportedException($this->db->getDriverName() . ' does not support resetting sequence.');
w  
Qiang Xue committed
509 510 511
	}

	/**
Qiang Xue committed
512
	 * Builds a SQL statement for enabling or disabling integrity check.
w  
Qiang Xue committed
513 514
	 * @param boolean $check whether to turn on or off the integrity check.
	 * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
resurtm committed
515
	 * @param string $table the table name. Defaults to empty string, meaning that no table will be changed.
Qiang Xue committed
516 517
	 * @return string the SQL statement for checking integrity
	 * @throws NotSupportedException if this is not supported by the underlying DBMS
w  
Qiang Xue committed
518
	 */
resurtm committed
519
	public function checkIntegrity($check = true, $schema = '', $table = '')
w  
Qiang Xue committed
520
	{
Qiang Xue committed
521
		throw new NotSupportedException($this->db->getDriverName() . ' does not support enabling/disabling integrity check.');
w  
Qiang Xue committed
522 523 524 525
	}

	/**
	 * Converts an abstract column type into a physical column type.
Qiang Xue committed
526
	 * The conversion is done using the type map specified in [[typeMap]].
Qiang Xue committed
527
	 * The following abstract column types are supported (using MySQL as an example to explain the corresponding
w  
Qiang Xue committed
528
	 * physical types):
Qiang Xue committed
529
	 *
Qiang Xue committed
530
	 * - `pk`: an auto-incremental primary key type, will be converted into "int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY"
531
	 * - `bigpk`: an auto-incremental primary key type, will be converted into "bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY"
Qiang Xue committed
532 533 534 535 536 537 538 539 540 541 542 543 544 545
	 * - `string`: string type, will be converted into "varchar(255)"
	 * - `text`: a long string type, will be converted into "text"
	 * - `smallint`: a small integer type, will be converted into "smallint(6)"
	 * - `integer`: integer type, will be converted into "int(11)"
	 * - `bigint`: a big integer type, will be converted into "bigint(20)"
	 * - `boolean`: boolean type, will be converted into "tinyint(1)"
	 * - `float``: float number type, will be converted into "float"
	 * - `decimal`: decimal number type, will be converted into "decimal"
	 * - `datetime`: datetime type, will be converted into "datetime"
	 * - `timestamp`: timestamp type, will be converted into "timestamp"
	 * - `time`: time type, will be converted into "time"
	 * - `date`: date type, will be converted into "date"
	 * - `money`: money type, will be converted into "decimal(19,4)"
	 * - `binary`: binary data type, will be converted into "blob"
w  
Qiang Xue committed
546 547
	 *
	 * If the abstract type contains two or more parts separated by spaces (e.g. "string NOT NULL"), then only
Qiang Xue committed
548
	 * the first part will be converted, and the rest of the parts will be appended to the converted result.
w  
Qiang Xue committed
549
	 * For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'.
Qiang Xue committed
550
	 *
551 552 553 554 555
	 * For some of the abstract types you can also specify a length or precision constraint
	 * by prepending it in round brackets directly to the type.
	 * For example `string(32)` will be converted into "varchar(32)" on a MySQL database.
	 * If the underlying DBMS does not support these kind of constraints for a type it will
	 * be ignored.
556
	 *
Qiang Xue committed
557
	 * If a type cannot be found in [[typeMap]], it will be returned without any change.
w  
Qiang Xue committed
558 559 560
	 * @param string $type abstract column type
	 * @return string physical column type.
	 */
Qiang Xue committed
561 562
	public function getColumnType($type)
	{
w  
Qiang Xue committed
563 564
		if (isset($this->typeMap[$type])) {
			return $this->typeMap[$type];
565
		} elseif (preg_match('/^(\w+)\((.+?)\)(.*)$/', $type, $matches)) {
566 567 568
			if (isset($this->typeMap[$matches[1]])) {
				return preg_replace('/\(.+\)/', '(' . $matches[2] . ')', $this->typeMap[$matches[1]]) . $matches[3];
			}
Qiang Xue committed
569
		} elseif (preg_match('/^(\w+)\s+/', $type, $matches)) {
Qiang Xue committed
570 571
			if (isset($this->typeMap[$matches[1]])) {
				return preg_replace('/^\w+/', $this->typeMap[$matches[1]], $type);
Qiang Xue committed
572 573 574 575 576 577
			}
		}
		return $type;
	}

	/**
Qiang Xue committed
578
	 * @param array $columns
579
	 * @param array $params the binding parameters to be populated
Qiang Xue committed
580 581
	 * @param boolean $distinct
	 * @param string $selectOption
Carsten Brandt committed
582
	 * @return string the SELECT clause built from [[Query::$select]].
Qiang Xue committed
583
	 */
584
	public function buildSelect($columns, &$params, $distinct = false, $selectOption = null)
w  
Qiang Xue committed
585
	{
Qiang Xue committed
586 587 588
		$select = $distinct ? 'SELECT DISTINCT' : 'SELECT';
		if ($selectOption !== null) {
			$select .= ' ' . $selectOption;
w  
Qiang Xue committed
589
		}
w  
Qiang Xue committed
590

w  
Qiang Xue committed
591 592 593 594
		if (empty($columns)) {
			return $select . ' *';
		}

595
		foreach ($columns as $i => $column) {
596 597 598 599 600 601 602 603
			if ($column instanceof Expression) {
				$columns[$i] = $column->expression;
				$params = array_merge($params, $column->params);
			} elseif (is_string($i)) {
				if (strpos($column, '(') === false) {
					$column = $this->db->quoteColumnName($column);
				}
				$columns[$i] = "$column AS " . $this->db->quoteColumnName($i);;
604 605
			} elseif (strpos($column, '(') === false) {
				if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $column, $matches)) {
Qiang Xue committed
606
					$columns[$i] = $this->db->quoteColumnName($matches[1]) . ' AS ' . $this->db->quoteColumnName($matches[2]);
607
				} else {
Qiang Xue committed
608
					$columns[$i] = $this->db->quoteColumnName($column);
w  
Qiang Xue committed
609 610 611 612
				}
			}
		}

613
		return $select . ' ' . implode(', ', $columns);
w  
Qiang Xue committed
614 615
	}

Qiang Xue committed
616
	/**
Qiang Xue committed
617
	 * @param array $tables
618
	 * @param array $params the binding parameters to be populated
Carsten Brandt committed
619
	 * @return string the FROM clause built from [[Query::$from]].
Qiang Xue committed
620
	 */
621
	public function buildFrom($tables, &$params)
w  
Qiang Xue committed
622
	{
Qiang Xue committed
623
		if (empty($tables)) {
Qiang Xue committed
624 625 626
			return '';
		}

627
		foreach ($tables as $i => $table) {
628 629 630 631 632 633 634 635 636
			if ($table instanceof Query) {
				list($sql, $params) = $this->build($table, $params);
				$tables[$i] = "($sql) " . $this->db->quoteTableName($i);
			} elseif (is_string($i)) {
				if (strpos($table, '(') === false) {
					$table = $this->db->quoteTableName($table);
				}
				$tables[$i] = "$table " . $this->db->quoteTableName($i);
			} elseif (strpos($table, '(') === false) {
637
				if (preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $table, $matches)) { // with alias
Qiang Xue committed
638
					$tables[$i] = $this->db->quoteTableName($matches[1]) . ' ' . $this->db->quoteTableName($matches[2]);
639
				} else {
Qiang Xue committed
640
					$tables[$i] = $this->db->quoteTableName($table);
Qiang Xue committed
641 642 643 644
				}
			}
		}

645
		return 'FROM ' . implode(', ', $tables);
w  
Qiang Xue committed
646
	}
w  
Qiang Xue committed
647

Qiang Xue committed
648
	/**
Qiang Xue committed
649
	 * @param string|array $joins
650
	 * @param array $params the binding parameters to be populated
Carsten Brandt committed
651
	 * @return string the JOIN clause built from [[Query::$join]].
Qiang Xue committed
652
	 * @throws Exception if the $joins parameter is not in proper format
Qiang Xue committed
653
	 */
654
	public function buildJoin($joins, &$params)
w  
Qiang Xue committed
655 656 657 658
	{
		if (empty($joins)) {
			return '';
		}
w  
Qiang Xue committed
659

w  
Qiang Xue committed
660
		foreach ($joins as $i => $join) {
661 662 663 664 665 666 667 668 669
			if (!is_array($join) || !isset($join[0], $join[1])) {
				throw new Exception('A join clause must be specified as an array of join type, join table, and optionally join condition.');
			}
			// 0:join type, 1:join table, 2:on-condition (optional)
			list ($joinType, $table) = $join;
			if (is_array($table)) {
				$query = reset($table);
				if (!$query instanceof Query) {
					throw new Exception('The sub-query for join must be an instance of yii\db\Query.');
Qiang Xue committed
670
				}
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
				$alias = $this->db->quoteTableName(key($table));
				list ($sql, $params) = $this->build($query, $params);
				$table = "($sql) $alias";
			} elseif (strpos($table, '(') === false) {
				if (preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $table, $matches)) { // with alias
					$table = $this->db->quoteTableName($matches[1]) . ' ' . $this->db->quoteTableName($matches[2]);
				} else {
					$table = $this->db->quoteTableName($table);
				}
			}
			$joins[$i] = "$joinType $table";
			if (isset($join[2])) {
				$condition = $this->buildCondition($join[2], $params);
				if ($condition !== '') {
					$joins[$i] .= ' ON ' . $condition;
w  
Qiang Xue committed
686 687 688
				}
			}
		}
w  
Qiang Xue committed
689

Qiang Xue committed
690
		return implode($this->separator, $joins);
w  
Qiang Xue committed
691 692
	}

Qiang Xue committed
693
	/**
Qiang Xue committed
694
	 * @param string|array $condition
695
	 * @param array $params the binding parameters to be populated
Carsten Brandt committed
696
	 * @return string the WHERE clause built from [[Query::$where]].
Qiang Xue committed
697
	 */
698
	public function buildWhere($condition, &$params)
w  
Qiang Xue committed
699
	{
700
		$where = $this->buildCondition($condition, $params);
Qiang Xue committed
701
		return $where === '' ? '' : 'WHERE ' . $where;
w  
Qiang Xue committed
702 703
	}

Qiang Xue committed
704
	/**
Qiang Xue committed
705
	 * @param array $columns
Qiang Xue committed
706
	 * @return string the GROUP BY clause
Qiang Xue committed
707
	 */
Qiang Xue committed
708
	public function buildGroupBy($columns)
w  
Qiang Xue committed
709
	{
Qiang Xue committed
710
		return empty($columns) ? '' : 'GROUP BY ' . $this->buildColumns($columns);
w  
Qiang Xue committed
711 712
	}

Qiang Xue committed
713
	/**
Qiang Xue committed
714
	 * @param string|array $condition
715
	 * @param array $params the binding parameters to be populated
Carsten Brandt committed
716
	 * @return string the HAVING clause built from [[Query::$having]].
Qiang Xue committed
717
	 */
718
	public function buildHaving($condition, &$params)
w  
Qiang Xue committed
719
	{
720
		$having = $this->buildCondition($condition, $params);
Qiang Xue committed
721
		return $having === '' ? '' : 'HAVING ' . $having;
w  
Qiang Xue committed
722 723
	}

Qiang Xue committed
724
	/**
Qiang Xue committed
725
	 * @param array $columns
Carsten Brandt committed
726
	 * @return string the ORDER BY clause built from [[Query::$orderBy]].
Qiang Xue committed
727
	 */
Qiang Xue committed
728
	public function buildOrderBy($columns)
w  
Qiang Xue committed
729
	{
Qiang Xue committed
730
		if (empty($columns)) {
w  
Qiang Xue committed
731 732
			return '';
		}
Alexander Makarov committed
733
		$orders = [];
Qiang Xue committed
734
		foreach ($columns as $name => $direction) {
735 736
			if ($direction instanceof Expression) {
				$orders[] = $direction->expression;
737
			} else {
738
				$orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : '');
Qiang Xue committed
739 740
			}
		}
Qiang Xue committed
741 742

		return 'ORDER BY ' . implode(', ', $orders);
w  
Qiang Xue committed
743 744
	}

Qiang Xue committed
745
	/**
Qiang Xue committed
746 747
	 * @param integer $limit
	 * @param integer $offset
Carsten Brandt committed
748
	 * @return string the LIMIT and OFFSET clauses built from [[Query::$limit]].
Qiang Xue committed
749
	 */
Qiang Xue committed
750
	public function buildLimit($limit, $offset)
w  
Qiang Xue committed
751
	{
w  
Qiang Xue committed
752
		$sql = '';
753 754
		if ($this->hasLimit($limit)) {
			$sql = 'LIMIT ' . $limit;
w  
Qiang Xue committed
755
		}
756 757
		if ($this->hasOffset($offset)) {
			$sql .= ' OFFSET ' . $offset;
w  
Qiang Xue committed
758 759
		}
		return ltrim($sql);
w  
Qiang Xue committed
760 761
	}

762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
	/**
	 * Checks to see if the given limit is effective.
	 * @param mixed $limit the given limit
	 * @return boolean whether the limit is effective
	 */
	protected function hasLimit($limit)
	{
		return is_string($limit) && ctype_digit($limit) || is_integer($limit) && $limit >= 0;
	}

	/**
	 * Checks to see if the given offset is effective.
	 * @param mixed $offset the given offset
	 * @return boolean whether the offset is effective
	 */
	protected function hasOffset($offset)
	{
		return is_integer($offset) && $offset > 0 || is_string($offset) && ctype_digit($offset) && $offset !== '0';
	}

Qiang Xue committed
782
	/**
Qiang Xue committed
783
	 * @param array $unions
784
	 * @param array $params the binding parameters to be populated
Carsten Brandt committed
785
	 * @return string the UNION clause built from [[Query::$union]].
Qiang Xue committed
786
	 */
787
	public function buildUnion($unions, &$params)
w  
Qiang Xue committed
788
	{
w  
Qiang Xue committed
789 790 791
		if (empty($unions)) {
			return '';
		}
Ivan Pomortsev committed
792
		
Ivan Pomortsev committed
793
		$result = '';
Ivan Pomortsev committed
794
		
w  
Qiang Xue committed
795
		foreach ($unions as $i => $union) {
Ivan Pomortsev committed
796 797
			$query = $union['query'];
			if ($query instanceof Query) {
798
				list($unions[$i]['query'], $params) = $this->build($query, $params);
w  
Qiang Xue committed
799
			}
Ivan Pomortsev committed
800 801
			
			$result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . '( ' . $unions[$i]['query'] . ' ) ';
w  
Qiang Xue committed
802
		}
Ivan Pomortsev committed
803
		
Ivan Pomortsev committed
804
		return trim($result);
w  
Qiang Xue committed
805
	}
Qiang Xue committed
806 807 808 809 810 811 812

	/**
	 * Processes columns and properly quote them if necessary.
	 * It will join all columns into a string with comma as separators.
	 * @param string|array $columns the columns to be processed
	 * @return string the processing result
	 */
813
	public function buildColumns($columns)
Qiang Xue committed
814
	{
815 816 817 818 819
		if (!is_array($columns)) {
			if (strpos($columns, '(') !== false) {
				return $columns;
			} else {
				$columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
Qiang Xue committed
820
			}
821 822
		}
		foreach ($columns as $i => $column) {
823 824
			if ($column instanceof Expression) {
				$columns[$i] = $column->expression;
825
			} elseif (strpos($column, '(') === false) {
Qiang Xue committed
826
				$columns[$i] = $this->db->quoteColumnName($column);
Qiang Xue committed
827 828 829 830
			}
		}
		return is_array($columns) ? implode(', ', $columns) : $columns;
	}
831 832 833 834 835 836 837 838


	/**
	 * Parses the condition specification and generates the corresponding SQL expression.
	 * @param string|array $condition the condition specification. Please refer to [[Query::where()]]
	 * on how to specify a condition.
	 * @param array $params the binding parameters to be populated
	 * @return string the generated SQL expression
839
	 * @throws InvalidParamException if the condition is in bad format
840 841 842
	 */
	public function buildCondition($condition, &$params)
	{
Alexander Makarov committed
843
		static $builders = [
844
			'NOT' => 'buildNotCondition',
845 846 847 848 849 850 851 852 853 854
			'AND' => 'buildAndCondition',
			'OR' => 'buildAndCondition',
			'BETWEEN' => 'buildBetweenCondition',
			'NOT BETWEEN' => 'buildBetweenCondition',
			'IN' => 'buildInCondition',
			'NOT IN' => 'buildInCondition',
			'LIKE' => 'buildLikeCondition',
			'NOT LIKE' => 'buildLikeCondition',
			'OR LIKE' => 'buildLikeCondition',
			'OR NOT LIKE' => 'buildLikeCondition',
855 856
			'EXISTS' => 'buildExistsCondition',
			'NOT EXISTS' => 'buildExistsCondition',
Alexander Makarov committed
857
		];
858 859 860

		if (!is_array($condition)) {
			return (string)$condition;
861
		} elseif (empty($condition)) {
862 863 864 865 866 867 868 869 870
			return '';
		}
		if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
			$operator = strtoupper($condition[0]);
			if (isset($builders[$operator])) {
				$method = $builders[$operator];
				array_shift($condition);
				return $this->$method($operator, $condition, $params);
			} else {
871
				throw new InvalidParamException('Found unknown operator in query: ' . $operator);
872
			}
resurtm committed
873
		} else { // hash format: 'column1' => 'value1', 'column2' => 'value2', ...
874 875 876 877
			return $this->buildHashCondition($condition, $params);
		}
	}

878 879 880 881 882 883 884
	/**
	 * Creates a condition based on column-value pairs.
	 * @param array $condition the condition specification.
	 * @param array $params the binding parameters to be populated
	 * @return string the generated SQL expression
	 */
	public function buildHashCondition($condition, &$params)
885
	{
Alexander Makarov committed
886
		$parts = [];
887 888
		foreach ($condition as $column => $value) {
			if (is_array($value)) { // IN condition
Alexander Makarov committed
889
				$parts[] = $this->buildInCondition('IN', [$column, $value], $params);
890 891 892 893 894 895
			} else {
				if (strpos($column, '(') === false) {
					$column = $this->db->quoteColumnName($column);
				}
				if ($value === null) {
					$parts[] = "$column IS NULL";
896 897 898 899 900
				} elseif ($value instanceof Expression) {
					$parts[] = "$column=" . $value->expression;
					foreach ($value->params as $n => $v) {
						$params[$n] = $v;
					}
901 902 903 904 905 906 907 908 909 910
				} else {
					$phName = self::PARAM_PREFIX . count($params);
					$parts[] = "$column=$phName";
					$params[$phName] = $value;
				}
			}
		}
		return count($parts) === 1 ? $parts[0] : '(' . implode(') AND (', $parts) . ')';
	}

911 912 913 914 915 916 917 918
	/**
	 * Connects two or more SQL expressions with the `AND` or `OR` operator.
	 * @param string $operator the operator to use for connecting the given operands
	 * @param array $operands the SQL expressions to connect.
	 * @param array $params the binding parameters to be populated
	 * @return string the generated SQL expression
	 */
	public function buildAndCondition($operator, $operands, &$params)
919
	{
Alexander Makarov committed
920
		$parts = [];
921 922 923 924 925 926 927 928
		foreach ($operands as $operand) {
			if (is_array($operand)) {
				$operand = $this->buildCondition($operand, $params);
			}
			if ($operand !== '') {
				$parts[] = $operand;
			}
		}
929
		if (!empty($parts)) {
930 931 932 933 934 935
			return '(' . implode(") $operator (", $parts) . ')';
		} else {
			return '';
		}
	}

936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
	/**
	 * Inverts an SQL expressions with `NOT` operator.
	 * @param string $operator the operator to use for connecting the given operands
	 * @param array $operands the SQL expressions to connect.
	 * @param array $params the binding parameters to be populated
	 * @return string the generated SQL expression
	 * @throws InvalidParamException if wrong number of operands have been given.
	 */
	public function buildNotCondition($operator, $operands, &$params)
	{
		if (count($operands) != 1) {
			throw new InvalidParamException("Operator '$operator' requires exactly one operand.");
		}

		$operand = reset($operands);
		if (is_array($operand)) {
			$operand = $this->buildCondition($operand, $params);
		}
		if ($operand === '') {
			return '';
		}
		return "$operator ($operand)";
	}

960 961 962 963 964 965 966
	/**
	 * Creates an SQL expressions with the `BETWEEN` operator.
	 * @param string $operator the operator to use (e.g. `BETWEEN` or `NOT BETWEEN`)
	 * @param array $operands the first operand is the column name. The second and third operands
	 * describe the interval that column value should be in.
	 * @param array $params the binding parameters to be populated
	 * @return string the generated SQL expression
967
	 * @throws InvalidParamException if wrong number of operands have been given.
968 969
	 */
	public function buildBetweenCondition($operator, $operands, &$params)
970 971
	{
		if (!isset($operands[0], $operands[1], $operands[2])) {
972
			throw new InvalidParamException("Operator '$operator' requires three operands.");
973 974 975 976 977 978 979 980 981
		}

		list($column, $value1, $value2) = $operands;

		if (strpos($column, '(') === false) {
			$column = $this->db->quoteColumnName($column);
		}
		$phName1 = self::PARAM_PREFIX . count($params);
		$params[$phName1] = $value1;
Qiang Xue committed
982
		$phName2 = self::PARAM_PREFIX . count($params);
983 984 985 986 987
		$params[$phName2] = $value2;

		return "$column $operator $phName1 AND $phName2";
	}

988 989 990 991 992 993 994 995 996 997 998 999 1000
	/**
	 * Creates an SQL expressions with the `IN` operator.
	 * @param string $operator the operator to use (e.g. `IN` or `NOT IN`)
	 * @param array $operands the first operand is the column name. If it is an array
	 * a composite IN condition will be generated.
	 * The second operand is an array of values that column value should be among.
	 * If it is an empty array the generated expression will be a `false` value if
	 * operator is `IN` and empty if operator is `NOT IN`.
	 * @param array $params the binding parameters to be populated
	 * @return string the generated SQL expression
	 * @throws Exception if wrong number of operands have been given.
	 */
	public function buildInCondition($operator, $operands, &$params)
1001 1002 1003 1004 1005 1006 1007 1008 1009
	{
		if (!isset($operands[0], $operands[1])) {
			throw new Exception("Operator '$operator' requires two operands.");
		}

		list($column, $values) = $operands;

		$values = (array)$values;

Alexander Makarov committed
1010
		if (empty($values) || $column === []) {
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
			return $operator === 'IN' ? '0=1' : '';
		}

		if (count($column) > 1) {
			return $this->buildCompositeInCondition($operator, $column, $values, $params);
		} elseif (is_array($column)) {
			$column = reset($column);
		}
		foreach ($values as $i => $value) {
			if (is_array($value)) {
				$value = isset($value[$column]) ? $value[$column] : null;
			}
			if ($value === null) {
				$values[$i] = 'NULL';
1025 1026 1027 1028 1029
			} elseif ($value instanceof Expression) {
				$values[$i] = $value->expression;
				foreach ($value->params as $n => $v) {
					$params[$n] = $v;
				}
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
			} else {
				$phName = self::PARAM_PREFIX . count($params);
				$params[$phName] = $value;
				$values[$i] = $phName;
			}
		}
		if (strpos($column, '(') === false) {
			$column = $this->db->quoteColumnName($column);
		}

		if (count($values) > 1) {
			return "$column $operator (" . implode(', ', $values) . ')';
		} else {
			$operator = $operator === 'IN' ? '=' : '<>';
1044
			return $column . $operator . reset($values);
1045 1046 1047 1048 1049
		}
	}

	protected function buildCompositeInCondition($operator, $columns, $values, &$params)
	{
Alexander Makarov committed
1050
		$vss = [];
1051
		foreach ($values as $value) {
Alexander Makarov committed
1052
			$vs = [];
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
			foreach ($columns as $column) {
				if (isset($value[$column])) {
					$phName = self::PARAM_PREFIX . count($params);
					$params[$phName] = $value[$column];
					$vs[] = $phName;
				} else {
					$vs[] = 'NULL';
				}
			}
			$vss[] = '(' . implode(', ', $vs) . ')';
		}
Qiang Xue committed
1064 1065 1066 1067 1068
		foreach ($columns as $i => $column) {
			if (strpos($column, '(') === false) {
				$columns[$i] = $this->db->quoteColumnName($column);
			}
		}
1069 1070 1071
		return '(' . implode(', ', $columns) . ") $operator (" . implode(', ', $vss) . ')';
	}

1072 1073 1074
	/**
	 * Creates an SQL expressions with the `LIKE` operator.
	 * @param string $operator the operator to use (e.g. `LIKE`, `NOT LIKE`, `OR LIKE` or `OR NOT LIKE`)
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
	 * @param array $operands an array of two or three operands
	 *
	 * - The first operand is the column name.
	 * - The second operand is a single value or an array of values that column value
	 *   should be compared with. If it is an empty array the generated expression will
	 *   be a `false` value if operator is `LIKE` or `OR LIKE`, and empty if operator
	 *   is `NOT LIKE` or `OR NOT LIKE`.
	 * - An optional third operand can also be provided to specify how to escape special characters
	 *   in the value(s). The operand should be an array of mappings from the special characters to their
	 *   escaped counterparts. If this operand is not provided, a default escape mapping will be used.
	 *   You may use `false` or an empty array to indicate the values are already escaped and no escape
	 *   should be applied. Note that when using an escape mapping (or the third operand is not provided),
	 *   the values will be automatically enclosed within a pair of percentage characters.
1088 1089
	 * @param array $params the binding parameters to be populated
	 * @return string the generated SQL expression
1090
	 * @throws InvalidParamException if wrong number of operands have been given.
1091 1092
	 */
	public function buildLikeCondition($operator, $operands, &$params)
1093 1094
	{
		if (!isset($operands[0], $operands[1])) {
1095
			throw new InvalidParamException("Operator '$operator' requires two operands.");
1096 1097
		}

1098 1099 1100
		$escape = isset($operands[2]) ? $operands[2] : ['%'=>'\%', '_'=>'\_', '\\'=>'\\\\'];
		unset($operands[2]);

1101 1102 1103 1104
		list($column, $values) = $operands;

		$values = (array)$values;

1105
		if (empty($values)) {
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
			return $operator === 'LIKE' || $operator === 'OR LIKE' ? '0=1' : '';
		}

		if ($operator === 'LIKE' || $operator === 'NOT LIKE') {
			$andor = ' AND ';
		} else {
			$andor = ' OR ';
			$operator = $operator === 'OR LIKE' ? 'LIKE' : 'NOT LIKE';
		}

		if (strpos($column, '(') === false) {
			$column = $this->db->quoteColumnName($column);
		}

Alexander Makarov committed
1120
		$parts = [];
1121 1122
		foreach ($values as $value) {
			$phName = self::PARAM_PREFIX . count($params);
1123
			$params[$phName] = empty($escape) ? $value : ('%' . strtr($value, $escape) . '%');
1124 1125 1126 1127 1128
			$parts[] = "$column $operator $phName";
		}

		return implode($andor, $parts);
	}
1129 1130 1131 1132

	/**
	 * Creates an SQL expressions with the `EXISTS` operator.
	 * @param string $operator the operator to use (e.g. `EXISTS` or `NOT EXISTS`)
1133
	 * @param array $operands contains only one element which is a [[Query]] object representing the sub-query.
1134 1135
	 * @param array $params the binding parameters to be populated
	 * @return string the generated SQL expression
1136
	 * @throws InvalidParamException if the operand is not a [[Query]] object.
1137 1138 1139
	 */
	public function buildExistsCondition($operator, $operands, &$params)
	{
1140 1141 1142 1143
		if ($operands[0] instanceof Query) {
			list($sql, $params) = $this->build($operands[0], $params);
			return "$operator ($sql)";
		} else {
1144 1145
			throw new InvalidParamException('Subquery for EXISTS operator must be a Query object.');
		}
1146
	}
w  
Qiang Xue committed
1147
}