QueryBuilder.php 30.8 KB
Newer Older
w  
Qiang Xue committed
1 2
<?php
/**
Qiang Xue committed
3
 * QueryBuilder class file.
w  
Qiang Xue committed
4 5
 *
 * @link http://www.yiiframework.com/
Qiang Xue committed
6
 * @copyright Copyright &copy; 2008 Yii Software LLC
w  
Qiang Xue committed
7 8 9
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
10
namespace yii\db;
w  
Qiang Xue committed
11

w  
Qiang Xue committed
12
use yii\db\Exception;
Qiang Xue committed
13
use yii\base\NotSupportedException;
w  
Qiang Xue committed
14

w  
Qiang Xue committed
15
/**
Qiang Xue committed
16
 * QueryBuilder builds a SELECT SQL statement based on the specification given as a [[Query]] object.
w  
Qiang Xue committed
17
 *
Qiang Xue committed
18
 * QueryBuilder can also be used to build SQL statements such as INSERT, UPDATE, DELETE, CREATE TABLE,
Qiang Xue committed
19 20
 * from a [[Query]] object.
 *
w  
Qiang Xue committed
21 22 23
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
24
class QueryBuilder extends \yii\base\Object
w  
Qiang Xue committed
25
{
Qiang Xue committed
26 27 28
	/**
	 * @var Connection the database connection.
	 */
Qiang Xue committed
29
	public $db;
Qiang Xue committed
30 31 32 33 34
	/**
	 * @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
35 36 37 38 39 40
	/**
	 * @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.
	 */
	public $typeMap = array();
w  
Qiang Xue committed
41

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

Qiang Xue committed
53
	/**
Qiang Xue committed
54 55
	 * Generates a SELECT SQL statement from a [[Query]] object.
	 * @param Query $query the [[Query]] object from which the SQL statement will be generated
Qiang Xue committed
56
	 * @return string the generated SQL statement
Qiang Xue committed
57
	 */
w  
Qiang Xue committed
58 59
	public function build($query)
	{
Qiang Xue committed
60
		$clauses = array(
Qiang Xue committed
61 62 63 64
			$this->buildSelect($query->select, $query->distinct, $query->selectOption),
			$this->buildFrom($query->from),
			$this->buildJoin($query->join),
			$this->buildWhere($query->where),
65
			$this->buildGroup($query->groupBy),
Qiang Xue committed
66 67
			$this->buildHaving($query->having),
			$this->buildUnion($query->union),
68
			$this->buildOrder($query->orderBy),
Qiang Xue committed
69
			$this->buildLimit($query->limit, $query->offset),
Qiang Xue committed
70 71
		);
		return implode($this->separator, array_filter($clauses));
w  
Qiang Xue committed
72 73 74
	}

	/**
Qiang Xue committed
75
	 * Creates an INSERT SQL statement.
Qiang Xue committed
76 77 78 79
	 * For example,
	 *
	 * ~~~
	 * $sql = $queryBuilder->insert('tbl_user', array(
Qiang Xue committed
80 81
	 *	 'name' => 'Sam',
	 *	 'age' => 30,
Qiang Xue committed
82
	 * ), $params);
Qiang Xue committed
83 84
	 * ~~~
	 *
Qiang Xue committed
85 86
	 * The method will properly escape the table and column names.
	 *
w  
Qiang Xue committed
87 88
	 * @param string $table the table that new rows will be inserted into.
	 * @param array $columns the column data (name=>value) to be inserted into the table.
Qiang Xue committed
89 90
	 * @param array $params the binding parameters that will be generated by this method.
	 * They should be bound to the DB command later.
91
	 * @return string the INSERT SQL
w  
Qiang Xue committed
92
	 */
Qiang Xue committed
93
	public function insert($table, $columns, &$params)
w  
Qiang Xue committed
94 95 96 97 98
	{
		$names = array();
		$placeholders = array();
		$count = 0;
		foreach ($columns as $name => $value) {
Qiang Xue committed
99
			$names[] = $this->db->quoteColumnName($name);
w  
Qiang Xue committed
100 101 102 103 104
			if ($value instanceof Expression) {
				$placeholders[] = $value->expression;
				foreach ($value->params as $n => $v) {
					$params[$n] = $v;
				}
Qiang Xue committed
105
			} else {
w  
Qiang Xue committed
106 107 108 109 110 111
				$placeholders[] = ':p' . $count;
				$params[':p' . $count] = $value;
				$count++;
			}
		}

Qiang Xue committed
112
		return 'INSERT INTO ' . $this->db->quoteTableName($table)
w  
Qiang Xue committed
113 114 115 116
			. ' (' . implode(', ', $names) . ') VALUES ('
			. implode(', ', $placeholders) . ')';
	}

Qiang Xue committed
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
	/**
	 * Generates a batch INSERT SQL statement.
	 * For example,
	 *
	 * ~~~
	 * $connection->createCommand()->batchInsert('tbl_user', array('name', 'age'), array(
	 *     array('Tom', 30),
	 *     array('Jane', 20),
	 *     array('Linda', 25),
	 * ))->execute();
	 * ~~~
	 *
	 * Not that the values in each row must match the corresponding column names.
	 *
	 * @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
	 * @param array $params the parameters to be bound to the command
	 * @return string the batch INSERT SQL statement
	 * @throws NotSupportedException if this is not supported by the underlying DBMS
	 */
	public function batchInsert($table, $columns, $rows, $params = array())
	{
		throw new NotSupportedException($this->db->getDriverName() . ' does not support batch insert.');

	}

w  
Qiang Xue committed
144
	/**
Qiang Xue committed
145
	 * Creates an UPDATE SQL statement.
Qiang Xue committed
146 147 148 149 150
	 * For example,
	 *
	 * ~~~
	 * $params = array();
	 * $sql = $queryBuilder->update('tbl_user', array(
Qiang Xue committed
151
	 *	 'status' => 1,
Qiang Xue committed
152 153 154
	 * ), 'age > 30', $params);
	 * ~~~
	 *
Qiang Xue committed
155 156
	 * The method will properly escape the table and column names.
	 *
w  
Qiang Xue committed
157 158
	 * @param string $table the table to be updated.
	 * @param array $columns the column data (name=>value) to be updated.
Qiang Xue committed
159 160
	 * @param mixed $condition the condition that will be put in the WHERE part. Please
	 * refer to [[Query::where()]] on how to specify condition.
Qiang Xue committed
161 162
	 * @param array $params the binding parameters that will be modified by this method
	 * so that they can be bound to the DB command later.
163
	 * @return string the UPDATE SQL
w  
Qiang Xue committed
164
	 */
Qiang Xue committed
165
	public function update($table, $columns, $condition = '', &$params)
w  
Qiang Xue committed
166 167 168 169 170
	{
		$lines = array();
		$count = 0;
		foreach ($columns as $name => $value) {
			if ($value instanceof Expression) {
Qiang Xue committed
171
				$lines[] = $this->db->quoteColumnName($name) . '=' . $value->expression;
w  
Qiang Xue committed
172 173 174
				foreach ($value->params as $n => $v) {
					$params[$n] = $v;
				}
Qiang Xue committed
175
			} else {
Qiang Xue committed
176
				$lines[] = $this->db->quoteColumnName($name) . '=:p' . $count;
w  
Qiang Xue committed
177 178 179 180
				$params[':p' . $count] = $value;
				$count++;
			}
		}
Qiang Xue committed
181
		$sql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $lines);
Qiang Xue committed
182
		if (($where = $this->buildCondition($condition)) !== '') {
w  
Qiang Xue committed
183 184
			$sql .= ' WHERE ' . $where;
		}
w  
Qiang Xue committed
185

w  
Qiang Xue committed
186 187 188 189
		return $sql;
	}

	/**
Qiang Xue committed
190
	 * Creates a DELETE SQL statement.
Qiang Xue committed
191 192 193 194 195 196
	 * For example,
	 *
	 * ~~~
	 * $sql = $queryBuilder->delete('tbl_user', 'status = 0');
	 * ~~~
	 *
Qiang Xue committed
197 198
	 * The method will properly escape the table and column names.
	 *
w  
Qiang Xue committed
199
	 * @param string $table the table where the data will be deleted from.
Qiang Xue committed
200 201
	 * @param mixed $condition the condition that will be put in the WHERE part. Please
	 * refer to [[Query::where()]] on how to specify condition.
202
	 * @return string the DELETE SQL
w  
Qiang Xue committed
203
	 */
Qiang Xue committed
204
	public function delete($table, $condition = '')
w  
Qiang Xue committed
205
	{
Qiang Xue committed
206
		$sql = 'DELETE FROM ' . $this->db->quoteTableName($table);
Qiang Xue committed
207
		if (($where = $this->buildCondition($condition)) !== '') {
w  
Qiang Xue committed
208 209 210
			$sql .= ' WHERE ' . $where;
		}
		return $sql;
w  
Qiang Xue committed
211 212
	}

w  
Qiang Xue committed
213 214 215 216 217 218
	/**
	 * Builds a SQL statement for creating a new DB table.
	 *
	 * The columns in the new  table should be specified as name-definition pairs (e.g. 'name'=>'string'),
	 * 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
219
	 * The [[getColumnType()]] method will be invoked to convert any abstract type into a physical one.
w  
Qiang Xue committed
220 221 222 223
	 *
	 * 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
224 225 226 227
	 * For example,
	 *
	 * ~~~
	 * $sql = $queryBuilder->createTable('tbl_user', array(
Qiang Xue committed
228 229 230
	 *	 'id' => 'pk',
	 *	 'name' => 'string',
	 *	 'age' => 'integer',
Qiang Xue committed
231 232 233
	 * ));
	 * ~~~
	 *
w  
Qiang Xue committed
234 235 236 237 238 239 240 241
	 * @param string $table the name of the table to be created. The name will be properly quoted by the method.
	 * @param array $columns the columns (name=>definition) in the new table.
	 * @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)
	{
		$cols = array();
w  
Qiang Xue committed
242 243
		foreach ($columns as $name => $type) {
			if (is_string($name)) {
Qiang Xue committed
244
				$cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type);
Qiang Xue committed
245
			} else {
w  
Qiang Xue committed
246
				$cols[] = "\t" . $type;
Qiang Xue committed
247
			}
w  
Qiang Xue committed
248
		}
Qiang Xue committed
249
		$sql = "CREATE TABLE " . $this->db->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)";
w  
Qiang Xue committed
250 251 252 253 254
		return $options === null ? $sql : $sql . ' ' . $options;
	}

	/**
	 * Builds a SQL statement for renaming a DB table.
Qiang Xue committed
255
	 * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
w  
Qiang Xue committed
256 257 258
	 * @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
259
	public function renameTable($oldName, $newName)
w  
Qiang Xue committed
260
	{
Qiang Xue committed
261
		return 'RENAME TABLE ' . $this->db->quoteTableName($oldName) . ' TO ' . $this->db->quoteTableName($newName);
w  
Qiang Xue committed
262 263 264 265 266 267 268 269 270
	}

	/**
	 * 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
271
		return "DROP TABLE " . $this->db->quoteTableName($table);
w  
Qiang Xue committed
272 273 274 275 276 277 278 279
	}

	/**
	 * 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
280
	{
Qiang Xue committed
281
		return "TRUNCATE TABLE " . $this->db->quoteTableName($table);
w  
Qiang Xue committed
282 283 284 285 286 287
	}

	/**
	 * 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
288
	 * @param string $type the column type. The [[getColumnType()]] method will be invoked to convert abstract column type (if any)
w  
Qiang Xue committed
289 290 291 292 293 294
	 * 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
295 296
		return 'ALTER TABLE ' . $this->db->quoteTableName($table)
			. ' ADD ' . $this->db->quoteColumnName($column) . ' '
w  
Qiang Xue committed
297 298
			. $this->getColumnType($type);
	}
w  
Qiang Xue committed
299

w  
Qiang Xue committed
300 301 302 303 304 305 306 307
	/**
	 * 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
308 309
		return "ALTER TABLE " . $this->db->quoteTableName($table)
			. " DROP COLUMN " . $this->db->quoteColumnName($column);
w  
Qiang Xue committed
310 311 312 313 314
	}

	/**
	 * 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
315
	 * @param string $oldName the old name of the column. The name will be properly quoted by the method.
w  
Qiang Xue committed
316 317 318
	 * @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
319
	public function renameColumn($table, $oldName, $newName)
w  
Qiang Xue committed
320
	{
Qiang Xue committed
321 322 323
		return "ALTER TABLE " . $this->db->quoteTableName($table)
			. " RENAME COLUMN " . $this->db->quoteColumnName($oldName)
			. " TO " . $this->db->quoteColumnName($newName);
w  
Qiang Xue committed
324 325 326 327 328 329
	}

	/**
	 * 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
330 331 332 333
	 * @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
334 335 336 337
	 * @return string the SQL statement for changing the definition of a column.
	 */
	public function alterColumn($table, $column, $type)
	{
Qiang Xue committed
338 339 340
		return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
			. $this->db->quoteColumnName($column) . ' '
			. $this->db->quoteColumnName($column) . ' '
w  
Qiang Xue committed
341 342 343 344 345 346 347 348
			. $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
349 350
	 * @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
351
	 * @param string $refTable the table that the foreign key references to.
Qiang Xue committed
352 353
	 * @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
354 355 356 357 358 359
	 * @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
360 361
		$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
			. ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name)
Qiang Xue committed
362
			. ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
Qiang Xue committed
363
			. ' REFERENCES ' . $this->db->quoteTableName($refTable)
Qiang Xue committed
364
			. ' (' . $this->buildColumns($refColumns) . ')';
Qiang Xue committed
365
		if ($delete !== null) {
w  
Qiang Xue committed
366
			$sql .= ' ON DELETE ' . $delete;
Qiang Xue committed
367 368
		}
		if ($update !== null) {
w  
Qiang Xue committed
369
			$sql .= ' ON UPDATE ' . $update;
Qiang Xue committed
370
		}
w  
Qiang Xue committed
371 372 373 374 375 376 377 378 379 380 381
		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
382 383
		return 'ALTER TABLE ' . $this->db->quoteTableName($table)
			. ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
w  
Qiang Xue committed
384 385 386 387 388 389
	}

	/**
	 * 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
390 391 392
	 * @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
393 394 395
	 * @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
396
	public function createIndex($name, $table, $columns, $unique = false)
w  
Qiang Xue committed
397 398
	{
		return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
Qiang Xue committed
399 400
			. $this->db->quoteTableName($name) . ' ON '
			. $this->db->quoteTableName($table)
Qiang Xue committed
401
			. ' (' . $this->buildColumns($columns) . ')';
w  
Qiang Xue committed
402 403 404 405 406 407 408 409 410 411
	}

	/**
	 * 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
412
		return 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON ' . $this->db->quoteTableName($table);
w  
Qiang Xue committed
413 414
	}

w  
Qiang Xue committed
415
	/**
Qiang Xue committed
416
	 * Creates a SQL statement for resetting the sequence value of a table's primary key.
w  
Qiang Xue committed
417 418
	 * 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
419
	 * @param string $table the name of the table whose primary key sequence will be reset
w  
Qiang Xue committed
420 421
	 * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
	 * the next new row's primary key will have a value 1.
Qiang Xue committed
422 423
	 * @return string the SQL statement for resetting sequence
	 * @throws NotSupportedException if this is not supported by the underlying DBMS
w  
Qiang Xue committed
424 425 426
	 */
	public function resetSequence($table, $value = null)
	{
Qiang Xue committed
427
		throw new NotSupportedException($this->db->getDriverName() . ' does not support resetting sequence.');
w  
Qiang Xue committed
428 429 430
	}

	/**
Qiang Xue committed
431
	 * Builds a SQL statement for enabling or disabling integrity check.
w  
Qiang Xue committed
432 433
	 * @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.
Qiang Xue committed
434 435
	 * @return string the SQL statement for checking integrity
	 * @throws NotSupportedException if this is not supported by the underlying DBMS
w  
Qiang Xue committed
436 437 438
	 */
	public function checkIntegrity($check = true, $schema = '')
	{
Qiang Xue committed
439
		throw new NotSupportedException($this->db->getDriverName() . ' does not support enabling/disabling integrity check.');
w  
Qiang Xue committed
440 441 442 443
	}

	/**
	 * Converts an abstract column type into a physical column type.
Qiang Xue committed
444
	 * The conversion is done using the type map specified in [[typeMap]].
Qiang Xue committed
445
	 * The following abstract column types are supported (using MySQL as an example to explain the corresponding
w  
Qiang Xue committed
446
	 * physical types):
Qiang Xue committed
447
	 *
Qiang Xue committed
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
	 * - `pk`: an auto-incremental primary key type, will be converted into "int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY"
	 * - `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
463 464
	 *
	 * If the abstract type contains two or more parts separated by spaces (e.g. "string NOT NULL"), then only
Qiang Xue committed
465
	 * the first part will be converted, and the rest of the parts will be appended to the converted result.
w  
Qiang Xue committed
466
	 * For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'.
Qiang Xue committed
467 468
	 *
	 * If a type cannot be found in [[typeMap]], it will be returned without any change.
w  
Qiang Xue committed
469 470 471
	 * @param string $type abstract column type
	 * @return string physical column type.
	 */
Qiang Xue committed
472 473
	public function getColumnType($type)
	{
w  
Qiang Xue committed
474 475
		if (isset($this->typeMap[$type])) {
			return $this->typeMap[$type];
Qiang Xue committed
476 477 478 479 480 481 482 483 484
		} elseif (preg_match('/^(\w+)\s+/', $type, $matches)) {
			if (isset($this->typeMap[$matches[0]])) {
				return preg_replace('/^\w+/', $this->typeMap[$matches[0]], $type);
			}
		}
		return $type;
	}

	/**
Qiang Xue committed
485
	 * Parses the condition specification and generates the corresponding SQL expression.
Qiang Xue committed
486
	 * @param string|array $condition the condition specification. Please refer to [[Query::where()]]
Qiang Xue committed
487 488 489
	 * on how to specify a condition.
	 * @return string the generated SQL expression
	 * @throws \yii\db\Exception if the condition is in bad format
Qiang Xue committed
490 491 492
	 */
	public function buildCondition($condition)
	{
Qiang Xue committed
493
		static $builders = array(
Qiang Xue committed
494 495 496 497 498 499 500 501 502 503
			'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',
Qiang Xue committed
504 505
		);

Qiang Xue committed
506
		if (!is_array($condition)) {
Qiang Xue committed
507
			return (string)$condition;
Qiang Xue committed
508 509 510
		} elseif ($condition === array()) {
			return '';
		}
Qiang Xue committed
511
		if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
Qiang Xue committed
512
			$operator = strtoupper($condition[0]);
Qiang Xue committed
513 514 515 516 517 518 519 520 521 522 523
			if (isset($builders[$operator])) {
				$method = $builders[$operator];
				array_shift($condition);
				return $this->$method($operator, $condition);
			} else {
				throw new Exception('Found unknown operator in query: ' . $operator);
			}
		} else { // hash format: 'column1'=>'value1', 'column2'=>'value2', ...
			return $this->buildHashCondition($condition);
		}
	}
Qiang Xue committed
524

Qiang Xue committed
525 526 527 528 529 530 531 532
	private function buildHashCondition($condition)
	{
		$parts = array();
		foreach ($condition as $column => $value) {
			if (is_array($value)) { // IN condition
				$parts[] = $this->buildInCondition('in', array($column, $value));
			} else {
				if (strpos($column, '(') === false) {
Qiang Xue committed
533
					$column = $this->db->quoteColumnName($column);
Qiang Xue committed
534 535 536 537
				}
				if ($value === null) {
					$parts[] = "$column IS NULL";
				} elseif (is_string($value)) {
Qiang Xue committed
538
					$parts[] = "$column=" . $this->db->quoteValue($value);
Qiang Xue committed
539 540
				} else {
					$parts[] = "$column=$value";
Qiang Xue committed
541 542 543
				}
			}
		}
Qiang Xue committed
544
		return count($parts) === 1 ? $parts[0] : '(' . implode(') AND (', $parts) . ')';
Qiang Xue committed
545
	}
Qiang Xue committed
546

Qiang Xue committed
547 548 549 550 551 552 553 554 555 556
	private function buildAndCondition($operator, $operands)
	{
		$parts = array();
		foreach ($operands as $operand) {
			if (is_array($operand)) {
				$operand = $this->buildCondition($operand);
			}
			if ($operand !== '') {
				$parts[] = $operand;
			}
Qiang Xue committed
557
		}
Qiang Xue committed
558 559 560 561 562 563 564 565 566 567 568 569 570 571
		if ($parts !== array()) {
			return '(' . implode(") $operator (", $parts) . ')';
		} else {
			return '';
		}
	}

	private function buildBetweenCondition($operator, $operands)
	{
		if (!isset($operands[0], $operands[1], $operands[2])) {
			throw new Exception("Operator '$operator' requires three operands.");
		}

		list($column, $value1, $value2) = $operands;
Qiang Xue committed
572 573

		if (strpos($column, '(') === false) {
Qiang Xue committed
574
			$column = $this->db->quoteColumnName($column);
Qiang Xue committed
575
		}
Qiang Xue committed
576 577
		$value1 = is_string($value1) ? $this->db->quoteValue($value1) : (string)$value1;
		$value2 = is_string($value2) ? $this->db->quoteValue($value2) : (string)$value2;
Qiang Xue committed
578

Qiang Xue committed
579 580 581 582 583 584 585
		return "$column $operator $value1 AND $value2";
	}

	private function buildInCondition($operator, $operands)
	{
		if (!isset($operands[0], $operands[1])) {
			throw new Exception("Operator '$operator' requires two operands.");
Qiang Xue committed
586 587
		}

Qiang Xue committed
588 589
		list($column, $values) = $operands;

590
		$values = (array)$values;
Qiang Xue committed
591

Qiang Xue committed
592
		if ($values === array() || $column === array()) {
Qiang Xue committed
593
			return $operator === 'IN' ? '0=1' : '';
Qiang Xue committed
594 595
		}

Qiang Xue committed
596 597 598 599 600 601 602
		if (is_array($column)) {
			if (count($column) > 1) {
				return $this->buildCompositeInCondition($operator, $column, $values);
			} else {
				$column = reset($column);
				foreach ($values as $i => $value) {
					if (is_array($value)) {
Qiang Xue committed
603 604 605 606
						$value = isset($value[$column]) ? $value[$column] : null;
					}
					if ($value === null) {
						$values[$i] = 'NULL';
Qiang Xue committed
607
					} else {
Qiang Xue committed
608
						$values[$i] = is_string($value) ? $this->db->quoteValue($value) : (string)$value;
Qiang Xue committed
609 610 611 612
					}
				}
			}
		}
Qiang Xue committed
613
		if (strpos($column, '(') === false) {
Qiang Xue committed
614
			$column = $this->db->quoteColumnName($column);
Qiang Xue committed
615 616
		}

Qiang Xue committed
617 618 619 620 621 622
		if (count($values) > 1) {
			return "$column $operator (" . implode(', ', $values) . ')';
		} else {
			$operator = $operator === 'IN' ? '=' : '<>';
			return "$column$operator{$values[0]}";
		}
Qiang Xue committed
623 624
	}

Qiang Xue committed
625 626 627 628
	protected function buildCompositeInCondition($operator, $columns, $values)
	{
		foreach ($columns as $i => $column) {
			if (strpos($column, '(') === false) {
Qiang Xue committed
629
				$columns[$i] = $this->db->quoteColumnName($column);
Qiang Xue committed
630 631 632 633 634 635 636
			}
		}
		$vss = array();
		foreach ($values as $value) {
			$vs = array();
			foreach ($columns as $column) {
				if (isset($value[$column])) {
Qiang Xue committed
637
					$vs[] = is_string($value[$column]) ? $this->db->quoteValue($value[$column]) : (string)$value[$column];
Qiang Xue committed
638 639 640 641 642 643 644 645 646
				} else {
					$vs[] = 'NULL';
				}
			}
			$vss[] = '(' . implode(', ', $vs) . ')';
		}
		return '(' . implode(', ', $columns) . ") $operator (" . implode(', ', $vss) . ')';
	}

Qiang Xue committed
647 648 649 650 651 652 653 654
	private function buildLikeCondition($operator, $operands)
	{
		if (!isset($operands[0], $operands[1])) {
			throw new Exception("Operator '$operator' requires two operands.");
		}

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

655
		$values = (array)$values;
Qiang Xue committed
656 657

		if ($values === array()) {
Qiang Xue committed
658
			return $operator === 'LIKE' || $operator === 'OR LIKE' ? '0=1' : '';
Qiang Xue committed
659 660
		}

Qiang Xue committed
661
		if ($operator === 'LIKE' || $operator === 'NOT LIKE') {
Qiang Xue committed
662
			$andor = ' AND ';
Qiang Xue committed
663
		} else {
Qiang Xue committed
664
			$andor = ' OR ';
Qiang Xue committed
665
			$operator = $operator === 'OR LIKE' ? 'LIKE' : 'NOT LIKE';
Qiang Xue committed
666 667 668
		}

		if (strpos($column, '(') === false) {
Qiang Xue committed
669
			$column = $this->db->quoteColumnName($column);
Qiang Xue committed
670 671 672 673
		}

		$parts = array();
		foreach ($values as $value) {
Qiang Xue committed
674
			$parts[] = "$column $operator " . $this->db->quoteValue($value);
w  
Qiang Xue committed
675
		}
Qiang Xue committed
676

Qiang Xue committed
677
		return implode($andor, $parts);
w  
Qiang Xue committed
678 679
	}

Qiang Xue committed
680
	/**
Qiang Xue committed
681 682 683
	 * @param string|array $columns
	 * @param boolean $distinct
	 * @param string $selectOption
Qiang Xue committed
684 685
	 * @return string the SELECT clause built from [[query]].
	 */
Qiang Xue committed
686
	public function buildSelect($columns, $distinct = false, $selectOption = null)
w  
Qiang Xue committed
687
	{
Qiang Xue committed
688 689 690
		$select = $distinct ? 'SELECT DISTINCT' : 'SELECT';
		if ($selectOption !== null) {
			$select .= ' ' . $selectOption;
w  
Qiang Xue committed
691
		}
w  
Qiang Xue committed
692

w  
Qiang Xue committed
693 694 695 696
		if (empty($columns)) {
			return $select . ' *';
		}

697 698 699 700 701
		if (!is_array($columns)) {
			if (strpos($columns, '(') !== false) {
				return $select . ' ' . $columns;
			} else {
				$columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
Qiang Xue committed
702
			}
703 704 705 706 707 708
		}
		foreach ($columns as $i => $column) {
			if (is_object($column)) {
				$columns[$i] = (string)$column;
			} elseif (strpos($column, '(') === false) {
				if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $column, $matches)) {
Qiang Xue committed
709
					$columns[$i] = $this->db->quoteColumnName($matches[1]) . ' AS ' . $this->db->quoteColumnName($matches[2]);
710
				} else {
Qiang Xue committed
711
					$columns[$i] = $this->db->quoteColumnName($column);
w  
Qiang Xue committed
712 713 714 715
				}
			}
		}

Qiang Xue committed
716 717 718 719 720
		if (is_array($columns)) {
			$columns = implode(', ', $columns);
		}

		return $select . ' ' . $columns;
w  
Qiang Xue committed
721 722
	}

Qiang Xue committed
723
	/**
Qiang Xue committed
724
	 * @param string|array $tables
Qiang Xue committed
725 726
	 * @return string the FROM clause built from [[query]].
	 */
Qiang Xue committed
727
	public function buildFrom($tables)
w  
Qiang Xue committed
728
	{
Qiang Xue committed
729
		if (empty($tables)) {
Qiang Xue committed
730 731 732
			return '';
		}

733 734 735 736 737
		if (!is_array($tables)) {
			if (strpos($tables, '(') !== false) {
				return 'FROM ' . $tables;
			} else {
				$tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
w  
Qiang Xue committed
738
			}
739 740 741 742
		}
		foreach ($tables as $i => $table) {
			if (strpos($table, '(') === false) {
				if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/i', $table, $matches)) { // with alias
Qiang Xue committed
743
					$tables[$i] = $this->db->quoteTableName($matches[1]) . ' ' . $this->db->quoteTableName($matches[2]);
744
				} else {
Qiang Xue committed
745
					$tables[$i] = $this->db->quoteTableName($table);
Qiang Xue committed
746 747 748 749 750 751
				}
			}
		}

		if (is_array($tables)) {
			$tables = implode(', ', $tables);
w  
Qiang Xue committed
752 753
		}

Qiang Xue committed
754
		return 'FROM ' . $tables;
w  
Qiang Xue committed
755
	}
w  
Qiang Xue committed
756

Qiang Xue committed
757
	/**
Qiang Xue committed
758
	 * @param string|array $joins
Qiang Xue committed
759 760
	 * @return string the JOIN clause built from [[query]].
	 */
Qiang Xue committed
761
	public function buildJoin($joins)
w  
Qiang Xue committed
762 763 764 765 766 767 768
	{
		if (empty($joins)) {
			return '';
		}
		if (is_string($joins)) {
			return $joins;
		}
w  
Qiang Xue committed
769

w  
Qiang Xue committed
770
		foreach ($joins as $i => $join) {
Qiang Xue committed
771
			if (is_array($join)) { // 0:join type, 1:table name, 2:on-condition
w  
Qiang Xue committed
772 773
				if (isset($join[0], $join[1])) {
					$table = $join[1];
774
					if (strpos($table, '(') === false) {
Qiang Xue committed
775
						if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/', $table, $matches)) { // with alias
Qiang Xue committed
776
							$table = $this->db->quoteTableName($matches[1]) . ' ' . $this->db->quoteTableName($matches[2]);
Qiang Xue committed
777
						} else {
Qiang Xue committed
778
							$table = $this->db->quoteTableName($table);
w  
Qiang Xue committed
779 780
						}
					}
Qiang Xue committed
781
					$joins[$i] = $join[0] . ' ' . $table;
Qiang Xue committed
782 783 784 785 786
					if (isset($join[2])) {
						$condition = $this->buildCondition($join[2]);
						if ($condition !== '') {
							$joins[$i] .= ' ON ' . $this->buildCondition($join[2]);
						}
w  
Qiang Xue committed
787
					}
Qiang Xue committed
788
				} else {
Qiang Xue committed
789
					throw new Exception('A join clause must be specified as an array of at least two elements.');
w  
Qiang Xue committed
790 791 792
				}
			}
		}
w  
Qiang Xue committed
793

Qiang Xue committed
794
		return implode($this->separator, $joins);
w  
Qiang Xue committed
795 796
	}

Qiang Xue committed
797
	/**
Qiang Xue committed
798
	 * @param string|array $condition
Qiang Xue committed
799 800
	 * @return string the WHERE clause built from [[query]].
	 */
Qiang Xue committed
801
	public function buildWhere($condition)
w  
Qiang Xue committed
802
	{
Qiang Xue committed
803 804
		$where = $this->buildCondition($condition);
		return $where === '' ? '' : 'WHERE ' . $where;
w  
Qiang Xue committed
805 806
	}

Qiang Xue committed
807
	/**
Qiang Xue committed
808 809
	 * @param string|array $columns
	 * @return string the GROUP BY clause
Qiang Xue committed
810
	 */
811
	public function buildGroup($columns)
w  
Qiang Xue committed
812
	{
Qiang Xue committed
813
		if (empty($columns)) {
w  
Qiang Xue committed
814
			return '';
Qiang Xue committed
815
		} else {
Qiang Xue committed
816
			return 'GROUP BY ' . $this->buildColumns($columns);
w  
Qiang Xue committed
817
		}
w  
Qiang Xue committed
818 819
	}

Qiang Xue committed
820
	/**
Qiang Xue committed
821
	 * @param string|array $condition
Qiang Xue committed
822 823
	 * @return string the HAVING clause built from [[query]].
	 */
Qiang Xue committed
824
	public function buildHaving($condition)
w  
Qiang Xue committed
825
	{
Qiang Xue committed
826 827
		$having = $this->buildCondition($condition);
		return $having === '' ? '' : 'HAVING ' . $having;
w  
Qiang Xue committed
828 829
	}

Qiang Xue committed
830
	/**
Qiang Xue committed
831
	 * @param string|array $columns
Qiang Xue committed
832 833
	 * @return string the ORDER BY clause built from [[query]].
	 */
834
	public function buildOrder($columns)
w  
Qiang Xue committed
835
	{
Qiang Xue committed
836
		if (empty($columns)) {
w  
Qiang Xue committed
837 838
			return '';
		}
839 840 841 842 843
		if (!is_array($columns)) {
			if (strpos($columns, '(') !== false) {
				return 'ORDER BY ' . $columns;
			} else {
				$columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
w  
Qiang Xue committed
844
			}
845 846 847 848 849 850
		}
		foreach ($columns as $i => $column) {
			if (is_object($column)) {
				$columns[$i] = (string)$column;
			} elseif (strpos($column, '(') === false) {
				if (preg_match('/^(.*?)\s+(asc|desc)$/i', $column, $matches)) {
Qiang Xue committed
851
					$columns[$i] = $this->db->quoteColumnName($matches[1]) . ' ' . $matches[2];
852
				} else {
Qiang Xue committed
853
					$columns[$i] = $this->db->quoteColumnName($column);
Qiang Xue committed
854 855 856 857 858
				}
			}
		}
		if (is_array($columns)) {
			$columns = implode(', ', $columns);
w  
Qiang Xue committed
859
		}
Qiang Xue committed
860
		return 'ORDER BY ' . $columns;
w  
Qiang Xue committed
861 862
	}

Qiang Xue committed
863
	/**
Qiang Xue committed
864 865
	 * @param integer $limit
	 * @param integer $offset
Qiang Xue committed
866 867
	 * @return string the LIMIT and OFFSET clauses built from [[query]].
	 */
Qiang Xue committed
868
	public function buildLimit($limit, $offset)
w  
Qiang Xue committed
869
	{
w  
Qiang Xue committed
870
		$sql = '';
Qiang Xue committed
871 872
		if ($limit !== null && $limit >= 0) {
			$sql = 'LIMIT ' . (int)$limit;
w  
Qiang Xue committed
873
		}
Qiang Xue committed
874 875
		if ($offset > 0) {
			$sql .= ' OFFSET ' . (int)$offset;
w  
Qiang Xue committed
876 877
		}
		return ltrim($sql);
w  
Qiang Xue committed
878 879
	}

Qiang Xue committed
880
	/**
Qiang Xue committed
881
	 * @param string|array $unions
Qiang Xue committed
882 883
	 * @return string the UNION clause built from [[query]].
	 */
Qiang Xue committed
884
	public function buildUnion($unions)
w  
Qiang Xue committed
885
	{
w  
Qiang Xue committed
886 887 888 889 890 891 892
		if (empty($unions)) {
			return '';
		}
		if (!is_array($unions)) {
			$unions = array($unions);
		}
		foreach ($unions as $i => $union) {
Qiang Xue committed
893
			if ($union instanceof Query) {
Qiang Xue committed
894
				$unions[$i] = $this->build($union);
w  
Qiang Xue committed
895 896 897
			}
		}
		return "UNION (\n" . implode("\n) UNION (\n", $unions) . "\n)";
w  
Qiang Xue committed
898
	}
Qiang Xue committed
899 900 901 902 903 904 905 906 907

	/**
	 * 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
	 */
	protected function buildColumns($columns)
	{
908 909 910 911 912
		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
913
			}
914 915 916 917 918
		}
		foreach ($columns as $i => $column) {
			if (is_object($column)) {
				$columns[$i] = (string)$column;
			} elseif (strpos($column, '(') === false) {
Qiang Xue committed
919
				$columns[$i] = $this->db->quoteColumnName($column);
Qiang Xue committed
920 921 922 923
			}
		}
		return is_array($columns) ? implode(', ', $columns) : $columns;
	}
w  
Qiang Xue committed
924
}