QueryBuilder.php 29.7 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 13
use yii\db\Exception;

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

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

Qiang Xue committed
52
	/**
Qiang Xue committed
53 54
	 * 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
55
	 * @return string the generated SQL statement
Qiang Xue committed
56
	 */
w  
Qiang Xue committed
57 58
	public function build($query)
	{
Qiang Xue committed
59
		$clauses = array(
Qiang Xue committed
60 61 62 63
			$this->buildSelect($query->select, $query->distinct, $query->selectOption),
			$this->buildFrom($query->from),
			$this->buildJoin($query->join),
			$this->buildWhere($query->where),
64
			$this->buildGroup($query->groupBy),
Qiang Xue committed
65 66
			$this->buildHaving($query->having),
			$this->buildUnion($query->union),
67
			$this->buildOrder($query->orderBy),
Qiang Xue committed
68
			$this->buildLimit($query->limit, $query->offset),
Qiang Xue committed
69 70
		);
		return implode($this->separator, array_filter($clauses));
w  
Qiang Xue committed
71 72 73
	}

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

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

	/**
Qiang Xue committed
117
	 * Creates an UPDATE SQL statement.
Qiang Xue committed
118 119 120 121 122
	 * For example,
	 *
	 * ~~~
	 * $params = array();
	 * $sql = $queryBuilder->update('tbl_user', array(
Qiang Xue committed
123
	 *	 'status' => 1,
Qiang Xue committed
124 125 126
	 * ), 'age > 30', $params);
	 * ~~~
	 *
Qiang Xue committed
127 128
	 * The method will properly escape the table and column names.
	 *
w  
Qiang Xue committed
129 130
	 * @param string $table the table to be updated.
	 * @param array $columns the column data (name=>value) to be updated.
Qiang Xue committed
131 132
	 * @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
133 134
	 * @param array $params the binding parameters that will be modified by this method
	 * so that they can be bound to the DB command later.
135
	 * @return string the UPDATE SQL
w  
Qiang Xue committed
136
	 */
Qiang Xue committed
137
	public function update($table, $columns, $condition = '', &$params)
w  
Qiang Xue committed
138 139 140 141 142
	{
		$lines = array();
		$count = 0;
		foreach ($columns as $name => $value) {
			if ($value instanceof Expression) {
143
				$lines[] = $this->connection->quoteColumnName($name) . '=' . $value->expression;
w  
Qiang Xue committed
144 145 146
				foreach ($value->params as $n => $v) {
					$params[$n] = $v;
				}
Qiang Xue committed
147
			} else {
148
				$lines[] = $this->connection->quoteColumnName($name) . '=:p' . $count;
w  
Qiang Xue committed
149 150 151 152
				$params[':p' . $count] = $value;
				$count++;
			}
		}
153
		$sql = 'UPDATE ' . $this->connection->quoteTableName($table) . ' SET ' . implode(', ', $lines);
Qiang Xue committed
154
		if (($where = $this->buildCondition($condition)) !== '') {
w  
Qiang Xue committed
155 156
			$sql .= ' WHERE ' . $where;
		}
w  
Qiang Xue committed
157

w  
Qiang Xue committed
158 159 160 161
		return $sql;
	}

	/**
Qiang Xue committed
162
	 * Creates a DELETE SQL statement.
Qiang Xue committed
163 164 165 166 167 168
	 * For example,
	 *
	 * ~~~
	 * $sql = $queryBuilder->delete('tbl_user', 'status = 0');
	 * ~~~
	 *
Qiang Xue committed
169 170
	 * The method will properly escape the table and column names.
	 *
w  
Qiang Xue committed
171
	 * @param string $table the table where the data will be deleted from.
Qiang Xue committed
172 173
	 * @param mixed $condition the condition that will be put in the WHERE part. Please
	 * refer to [[Query::where()]] on how to specify condition.
174
	 * @return string the DELETE SQL
w  
Qiang Xue committed
175
	 */
Qiang Xue committed
176
	public function delete($table, $condition = '')
w  
Qiang Xue committed
177
	{
178
		$sql = 'DELETE FROM ' . $this->connection->quoteTableName($table);
Qiang Xue committed
179
		if (($where = $this->buildCondition($condition)) !== '') {
w  
Qiang Xue committed
180 181 182
			$sql .= ' WHERE ' . $where;
		}
		return $sql;
w  
Qiang Xue committed
183 184
	}

w  
Qiang Xue committed
185 186 187 188 189 190
	/**
	 * 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
191
	 * The [[getColumnType()]] method will be invoked to convert any abstract type into a physical one.
w  
Qiang Xue committed
192 193 194 195
	 *
	 * 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
196 197 198 199
	 * For example,
	 *
	 * ~~~
	 * $sql = $queryBuilder->createTable('tbl_user', array(
Qiang Xue committed
200 201 202
	 *	 'id' => 'pk',
	 *	 'name' => 'string',
	 *	 'age' => 'integer',
Qiang Xue committed
203 204 205
	 * ));
	 * ~~~
	 *
w  
Qiang Xue committed
206 207 208 209 210 211 212 213
	 * @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
214 215
		foreach ($columns as $name => $type) {
			if (is_string($name)) {
216
				$cols[] = "\t" . $this->connection->quoteColumnName($name) . ' ' . $this->getColumnType($type);
Qiang Xue committed
217
			} else {
w  
Qiang Xue committed
218
				$cols[] = "\t" . $type;
Qiang Xue committed
219
			}
w  
Qiang Xue committed
220
		}
221
		$sql = "CREATE TABLE " . $this->connection->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)";
w  
Qiang Xue committed
222 223 224 225 226
		return $options === null ? $sql : $sql . ' ' . $options;
	}

	/**
	 * Builds a SQL statement for renaming a DB table.
Qiang Xue committed
227
	 * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
w  
Qiang Xue committed
228 229 230
	 * @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
231
	public function renameTable($oldName, $newName)
w  
Qiang Xue committed
232
	{
233
		return 'RENAME TABLE ' . $this->connection->quoteTableName($oldName) . ' TO ' . $this->connection->quoteTableName($newName);
w  
Qiang Xue committed
234 235 236 237 238 239 240 241 242
	}

	/**
	 * 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)
	{
243
		return "DROP TABLE " . $this->connection->quoteTableName($table);
w  
Qiang Xue committed
244 245 246 247 248 249 250 251
	}

	/**
	 * 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
252
	{
253
		return "TRUNCATE TABLE " . $this->connection->quoteTableName($table);
w  
Qiang Xue committed
254 255 256 257 258 259
	}

	/**
	 * 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
260
	 * @param string $type the column type. The [[getColumnType()]] method will be invoked to convert abstract column type (if any)
w  
Qiang Xue committed
261 262 263 264 265 266
	 * 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)
	{
267 268
		return 'ALTER TABLE ' . $this->connection->quoteTableName($table)
			. ' ADD ' . $this->connection->quoteColumnName($column) . ' '
w  
Qiang Xue committed
269 270
			. $this->getColumnType($type);
	}
w  
Qiang Xue committed
271

w  
Qiang Xue committed
272 273 274 275 276 277 278 279
	/**
	 * 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)
	{
280 281
		return "ALTER TABLE " . $this->connection->quoteTableName($table)
			. " DROP COLUMN " . $this->connection->quoteColumnName($column);
w  
Qiang Xue committed
282 283 284 285 286
	}

	/**
	 * 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
287
	 * @param string $oldName the old name of the column. The name will be properly quoted by the method.
w  
Qiang Xue committed
288 289 290
	 * @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
291
	public function renameColumn($table, $oldName, $newName)
w  
Qiang Xue committed
292
	{
293 294 295
		return "ALTER TABLE " . $this->connection->quoteTableName($table)
			. " RENAME COLUMN " . $this->connection->quoteColumnName($oldName)
			. " TO " . $this->connection->quoteColumnName($newName);
w  
Qiang Xue committed
296 297 298 299 300 301
	}

	/**
	 * 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
302 303 304 305
	 * @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
306 307 308 309
	 * @return string the SQL statement for changing the definition of a column.
	 */
	public function alterColumn($table, $column, $type)
	{
310 311 312
		return 'ALTER TABLE ' . $this->connection->quoteTableName($table) . ' CHANGE '
			. $this->connection->quoteColumnName($column) . ' '
			. $this->connection->quoteColumnName($column) . ' '
w  
Qiang Xue committed
313 314 315 316 317 318 319 320
			. $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
321 322
	 * @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
323
	 * @param string $refTable the table that the foreign key references to.
Qiang Xue committed
324 325
	 * @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
326 327 328 329 330 331
	 * @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)
	{
332 333
		$sql = 'ALTER TABLE ' . $this->connection->quoteTableName($table)
			. ' ADD CONSTRAINT ' . $this->connection->quoteColumnName($name)
Qiang Xue committed
334
			. ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
335
			. ' REFERENCES ' . $this->connection->quoteTableName($refTable)
Qiang Xue committed
336
			. ' (' . $this->buildColumns($refColumns) . ')';
Qiang Xue committed
337
		if ($delete !== null) {
w  
Qiang Xue committed
338
			$sql .= ' ON DELETE ' . $delete;
Qiang Xue committed
339 340
		}
		if ($update !== null) {
w  
Qiang Xue committed
341
			$sql .= ' ON UPDATE ' . $update;
Qiang Xue committed
342
		}
w  
Qiang Xue committed
343 344 345 346 347 348 349 350 351 352 353
		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)
	{
354 355
		return 'ALTER TABLE ' . $this->connection->quoteTableName($table)
			. ' DROP CONSTRAINT ' . $this->connection->quoteColumnName($name);
w  
Qiang Xue committed
356 357 358 359 360 361
	}

	/**
	 * 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
362 363 364
	 * @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
365 366 367
	 * @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
368
	public function createIndex($name, $table, $columns, $unique = false)
w  
Qiang Xue committed
369 370
	{
		return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
371 372
			. $this->connection->quoteTableName($name) . ' ON '
			. $this->connection->quoteTableName($table)
Qiang Xue committed
373
			. ' (' . $this->buildColumns($columns) . ')';
w  
Qiang Xue committed
374 375 376 377 378 379 380 381 382 383
	}

	/**
	 * 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)
	{
384
		return 'DROP INDEX ' . $this->connection->quoteTableName($name) . ' ON ' . $this->connection->quoteTableName($table);
w  
Qiang Xue committed
385 386
	}

w  
Qiang Xue committed
387 388 389 390
	/**
	 * Resets the sequence value of a table's primary key.
	 * 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
391
	 * @param string $table the table schema whose primary key sequence will be reset
w  
Qiang Xue committed
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
	 * @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.
	 */
	public function resetSequence($table, $value = null)
	{
	}

	/**
	 * Enables or disables integrity check.
	 * @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.
	 */
	public function checkIntegrity($check = true, $schema = '')
	{
	}

	/**
	 * Converts an abstract column type into a physical column type.
Qiang Xue committed
410
	 * The conversion is done using the type map specified in [[typeMap]].
Qiang Xue committed
411
	 * The following abstract column types are supported (using MySQL as an example to explain the corresponding
w  
Qiang Xue committed
412
	 * physical types):
Qiang Xue committed
413
	 *
Qiang Xue committed
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
	 * - `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
429 430
	 *
	 * If the abstract type contains two or more parts separated by spaces (e.g. "string NOT NULL"), then only
Qiang Xue committed
431
	 * the first part will be converted, and the rest of the parts will be appended to the converted result.
w  
Qiang Xue committed
432
	 * For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'.
Qiang Xue committed
433 434
	 *
	 * If a type cannot be found in [[typeMap]], it will be returned without any change.
w  
Qiang Xue committed
435 436 437
	 * @param string $type abstract column type
	 * @return string physical column type.
	 */
Qiang Xue committed
438 439
	public function getColumnType($type)
	{
w  
Qiang Xue committed
440 441
		if (isset($this->typeMap[$type])) {
			return $this->typeMap[$type];
Qiang Xue committed
442 443 444 445 446 447 448 449 450
		} 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
451
	 * Parses the condition specification and generates the corresponding SQL expression.
Qiang Xue committed
452
	 * @param string|array $condition the condition specification. Please refer to [[Query::where()]]
Qiang Xue committed
453 454 455
	 * 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
456 457 458
	 */
	public function buildCondition($condition)
	{
Qiang Xue committed
459
		static $builders = array(
Qiang Xue committed
460 461 462 463 464 465 466 467 468 469
			'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
470 471
		);

Qiang Xue committed
472
		if (!is_array($condition)) {
Qiang Xue committed
473
			return (string)$condition;
Qiang Xue committed
474 475 476
		} elseif ($condition === array()) {
			return '';
		}
Qiang Xue committed
477
		if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
Qiang Xue committed
478
			$operator = strtoupper($condition[0]);
Qiang Xue committed
479 480 481 482 483 484 485 486 487 488 489
			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
490

Qiang Xue committed
491 492 493 494 495 496 497 498
	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) {
499
					$column = $this->connection->quoteColumnName($column);
Qiang Xue committed
500 501 502 503 504 505 506
				}
				if ($value === null) {
					$parts[] = "$column IS NULL";
				} elseif (is_string($value)) {
					$parts[] = "$column=" . $this->connection->quoteValue($value);
				} else {
					$parts[] = "$column=$value";
Qiang Xue committed
507 508 509
				}
			}
		}
Qiang Xue committed
510
		return count($parts) === 1 ? $parts[0] : '(' . implode(') AND (', $parts) . ')';
Qiang Xue committed
511
	}
Qiang Xue committed
512

Qiang Xue committed
513 514 515 516 517 518 519 520 521 522
	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
523
		}
Qiang Xue committed
524 525 526 527 528 529 530 531 532 533 534 535 536 537
		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
538 539

		if (strpos($column, '(') === false) {
540
			$column = $this->connection->quoteColumnName($column);
Qiang Xue committed
541
		}
Qiang Xue committed
542 543
		$value1 = is_string($value1) ? $this->connection->quoteValue($value1) : (string)$value1;
		$value2 = is_string($value2) ? $this->connection->quoteValue($value2) : (string)$value2;
Qiang Xue committed
544

Qiang Xue committed
545 546 547 548 549 550 551
		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
552 553
		}

Qiang Xue committed
554 555
		list($column, $values) = $operands;

556
		$values = (array)$values;
Qiang Xue committed
557

Qiang Xue committed
558
		if ($values === array() || $column === array()) {
Qiang Xue committed
559
			return $operator === 'IN' ? '0=1' : '';
Qiang Xue committed
560 561
		}

Qiang Xue committed
562 563 564 565 566 567 568
		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
569 570 571 572
						$value = isset($value[$column]) ? $value[$column] : null;
					}
					if ($value === null) {
						$values[$i] = 'NULL';
Qiang Xue committed
573
					} else {
Qiang Xue committed
574
						$values[$i] = is_string($value) ? $this->connection->quoteValue($value) : (string)$value;
Qiang Xue committed
575 576 577 578
					}
				}
			}
		}
Qiang Xue committed
579
		if (strpos($column, '(') === false) {
580
			$column = $this->connection->quoteColumnName($column);
Qiang Xue committed
581 582
		}

Qiang Xue committed
583 584 585 586 587 588
		if (count($values) > 1) {
			return "$column $operator (" . implode(', ', $values) . ')';
		} else {
			$operator = $operator === 'IN' ? '=' : '<>';
			return "$column$operator{$values[0]}";
		}
Qiang Xue committed
589 590
	}

Qiang Xue committed
591 592 593 594
	protected function buildCompositeInCondition($operator, $columns, $values)
	{
		foreach ($columns as $i => $column) {
			if (strpos($column, '(') === false) {
595
				$columns[$i] = $this->connection->quoteColumnName($column);
Qiang Xue committed
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
			}
		}
		$vss = array();
		foreach ($values as $value) {
			$vs = array();
			foreach ($columns as $column) {
				if (isset($value[$column])) {
					$vs[] = is_string($value[$column]) ? $this->connection->quoteValue($value[$column]) : (string)$value[$column];
				} else {
					$vs[] = 'NULL';
				}
			}
			$vss[] = '(' . implode(', ', $vs) . ')';
		}
		return '(' . implode(', ', $columns) . ") $operator (" . implode(', ', $vss) . ')';
	}

Qiang Xue committed
613 614 615 616 617 618 619 620
	private function buildLikeCondition($operator, $operands)
	{
		if (!isset($operands[0], $operands[1])) {
			throw new Exception("Operator '$operator' requires two operands.");
		}

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

621
		$values = (array)$values;
Qiang Xue committed
622 623

		if ($values === array()) {
Qiang Xue committed
624
			return $operator === 'LIKE' || $operator === 'OR LIKE' ? '0=1' : '';
Qiang Xue committed
625 626
		}

Qiang Xue committed
627
		if ($operator === 'LIKE' || $operator === 'NOT LIKE') {
Qiang Xue committed
628
			$andor = ' AND ';
Qiang Xue committed
629
		} else {
Qiang Xue committed
630
			$andor = ' OR ';
Qiang Xue committed
631
			$operator = $operator === 'OR LIKE' ? 'LIKE' : 'NOT LIKE';
Qiang Xue committed
632 633 634
		}

		if (strpos($column, '(') === false) {
635
			$column = $this->connection->quoteColumnName($column);
Qiang Xue committed
636 637 638 639 640
		}

		$parts = array();
		foreach ($values as $value) {
			$parts[] = "$column $operator " . $this->connection->quoteValue($value);
w  
Qiang Xue committed
641
		}
Qiang Xue committed
642

Qiang Xue committed
643
		return implode($andor, $parts);
w  
Qiang Xue committed
644 645
	}

Qiang Xue committed
646
	/**
Qiang Xue committed
647 648 649
	 * @param string|array $columns
	 * @param boolean $distinct
	 * @param string $selectOption
Qiang Xue committed
650 651
	 * @return string the SELECT clause built from [[query]].
	 */
Qiang Xue committed
652
	public function buildSelect($columns, $distinct = false, $selectOption = null)
w  
Qiang Xue committed
653
	{
Qiang Xue committed
654 655 656
		$select = $distinct ? 'SELECT DISTINCT' : 'SELECT';
		if ($selectOption !== null) {
			$select .= ' ' . $selectOption;
w  
Qiang Xue committed
657
		}
w  
Qiang Xue committed
658

w  
Qiang Xue committed
659 660 661 662
		if (empty($columns)) {
			return $select . ' *';
		}

663 664 665 666 667
		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
668
			}
669 670 671 672 673 674 675 676 677
		}
		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)) {
					$columns[$i] = $this->connection->quoteColumnName($matches[1]) . ' AS ' . $this->connection->quoteColumnName($matches[2]);
				} else {
					$columns[$i] = $this->connection->quoteColumnName($column);
w  
Qiang Xue committed
678 679 680 681
				}
			}
		}

Qiang Xue committed
682 683 684 685 686
		if (is_array($columns)) {
			$columns = implode(', ', $columns);
		}

		return $select . ' ' . $columns;
w  
Qiang Xue committed
687 688
	}

Qiang Xue committed
689
	/**
Qiang Xue committed
690
	 * @param string|array $tables
Qiang Xue committed
691 692
	 * @return string the FROM clause built from [[query]].
	 */
Qiang Xue committed
693
	public function buildFrom($tables)
w  
Qiang Xue committed
694
	{
Qiang Xue committed
695
		if (empty($tables)) {
Qiang Xue committed
696 697 698
			return '';
		}

699 700 701 702 703
		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
704
			}
705 706 707 708 709 710 711
		}
		foreach ($tables as $i => $table) {
			if (strpos($table, '(') === false) {
				if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/i', $table, $matches)) { // with alias
					$tables[$i] = $this->connection->quoteTableName($matches[1]) . ' ' . $this->connection->quoteTableName($matches[2]);
				} else {
					$tables[$i] = $this->connection->quoteTableName($table);
Qiang Xue committed
712 713 714 715 716 717
				}
			}
		}

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

Qiang Xue committed
720
		return 'FROM ' . $tables;
w  
Qiang Xue committed
721
	}
w  
Qiang Xue committed
722

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

w  
Qiang Xue committed
736
		foreach ($joins as $i => $join) {
Qiang Xue committed
737
			if (is_array($join)) { // 0:join type, 1:table name, 2:on-condition
w  
Qiang Xue committed
738 739
				if (isset($join[0], $join[1])) {
					$table = $join[1];
740
					if (strpos($table, '(') === false) {
Qiang Xue committed
741
						if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/', $table, $matches)) { // with alias
742
							$table = $this->connection->quoteTableName($matches[1]) . ' ' . $this->connection->quoteTableName($matches[2]);
Qiang Xue committed
743
						} else {
744
							$table = $this->connection->quoteTableName($table);
w  
Qiang Xue committed
745 746
						}
					}
Qiang Xue committed
747
					$joins[$i] = $join[0] . ' ' . $table;
Qiang Xue committed
748 749 750 751 752
					if (isset($join[2])) {
						$condition = $this->buildCondition($join[2]);
						if ($condition !== '') {
							$joins[$i] .= ' ON ' . $this->buildCondition($join[2]);
						}
w  
Qiang Xue committed
753
					}
Qiang Xue committed
754
				} else {
Qiang Xue committed
755
					throw new Exception('A join clause must be specified as an array of at least two elements.');
w  
Qiang Xue committed
756 757 758
				}
			}
		}
w  
Qiang Xue committed
759

Qiang Xue committed
760
		return implode($this->separator, $joins);
w  
Qiang Xue committed
761 762
	}

Qiang Xue committed
763
	/**
Qiang Xue committed
764
	 * @param string|array $condition
Qiang Xue committed
765 766
	 * @return string the WHERE clause built from [[query]].
	 */
Qiang Xue committed
767
	public function buildWhere($condition)
w  
Qiang Xue committed
768
	{
Qiang Xue committed
769 770
		$where = $this->buildCondition($condition);
		return $where === '' ? '' : 'WHERE ' . $where;
w  
Qiang Xue committed
771 772
	}

Qiang Xue committed
773
	/**
Qiang Xue committed
774 775
	 * @param string|array $columns
	 * @return string the GROUP BY clause
Qiang Xue committed
776
	 */
777
	public function buildGroup($columns)
w  
Qiang Xue committed
778
	{
Qiang Xue committed
779
		if (empty($columns)) {
w  
Qiang Xue committed
780
			return '';
Qiang Xue committed
781
		} else {
Qiang Xue committed
782
			return 'GROUP BY ' . $this->buildColumns($columns);
w  
Qiang Xue committed
783
		}
w  
Qiang Xue committed
784 785
	}

Qiang Xue committed
786
	/**
Qiang Xue committed
787
	 * @param string|array $condition
Qiang Xue committed
788 789
	 * @return string the HAVING clause built from [[query]].
	 */
Qiang Xue committed
790
	public function buildHaving($condition)
w  
Qiang Xue committed
791
	{
Qiang Xue committed
792 793
		$having = $this->buildCondition($condition);
		return $having === '' ? '' : 'HAVING ' . $having;
w  
Qiang Xue committed
794 795
	}

Qiang Xue committed
796
	/**
Qiang Xue committed
797
	 * @param string|array $columns
Qiang Xue committed
798 799
	 * @return string the ORDER BY clause built from [[query]].
	 */
800
	public function buildOrder($columns)
w  
Qiang Xue committed
801
	{
Qiang Xue committed
802
		if (empty($columns)) {
w  
Qiang Xue committed
803 804
			return '';
		}
805 806 807 808 809
		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
810
			}
811 812 813 814 815 816 817 818 819
		}
		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)) {
					$columns[$i] = $this->connection->quoteColumnName($matches[1]) . ' ' . $matches[2];
				} else {
					$columns[$i] = $this->connection->quoteColumnName($column);
Qiang Xue committed
820 821 822 823 824
				}
			}
		}
		if (is_array($columns)) {
			$columns = implode(', ', $columns);
w  
Qiang Xue committed
825
		}
Qiang Xue committed
826
		return 'ORDER BY ' . $columns;
w  
Qiang Xue committed
827 828
	}

Qiang Xue committed
829
	/**
Qiang Xue committed
830 831
	 * @param integer $limit
	 * @param integer $offset
Qiang Xue committed
832 833
	 * @return string the LIMIT and OFFSET clauses built from [[query]].
	 */
Qiang Xue committed
834
	public function buildLimit($limit, $offset)
w  
Qiang Xue committed
835
	{
w  
Qiang Xue committed
836
		$sql = '';
Qiang Xue committed
837 838
		if ($limit !== null && $limit >= 0) {
			$sql = 'LIMIT ' . (int)$limit;
w  
Qiang Xue committed
839
		}
Qiang Xue committed
840 841
		if ($offset > 0) {
			$sql .= ' OFFSET ' . (int)$offset;
w  
Qiang Xue committed
842 843
		}
		return ltrim($sql);
w  
Qiang Xue committed
844 845
	}

Qiang Xue committed
846
	/**
Qiang Xue committed
847
	 * @param string|array $unions
Qiang Xue committed
848 849
	 * @return string the UNION clause built from [[query]].
	 */
Qiang Xue committed
850
	public function buildUnion($unions)
w  
Qiang Xue committed
851
	{
w  
Qiang Xue committed
852 853 854 855 856 857 858
		if (empty($unions)) {
			return '';
		}
		if (!is_array($unions)) {
			$unions = array($unions);
		}
		foreach ($unions as $i => $union) {
Qiang Xue committed
859
			if ($union instanceof Query) {
Qiang Xue committed
860
				$unions[$i] = $this->build($union);
w  
Qiang Xue committed
861 862 863
			}
		}
		return "UNION (\n" . implode("\n) UNION (\n", $unions) . "\n)";
w  
Qiang Xue committed
864
	}
Qiang Xue committed
865 866 867 868 869 870 871 872 873

	/**
	 * 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)
	{
874 875 876 877 878
		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
879
			}
880 881 882 883 884 885
		}
		foreach ($columns as $i => $column) {
			if (is_object($column)) {
				$columns[$i] = (string)$column;
			} elseif (strpos($column, '(') === false) {
				$columns[$i] = $this->connection->quoteColumnName($column);
Qiang Xue committed
886 887 888 889
			}
		}
		return is_array($columns) ? implode(', ', $columns) : $columns;
	}
w  
Qiang Xue committed
890
}