Command.php 28.1 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;
Qiang Xue committed
11
use yii\base\NotSupportedException;
12
use yii\caching\Cache;
Qiang Xue committed
13

w  
Qiang Xue committed
14
/**
w  
Qiang Xue committed
15
 * Command represents a SQL statement to be executed against a database.
w  
Qiang Xue committed
16
 *
Qiang Xue committed
17
 * A command object is usually created by calling [[Connection::createCommand()]].
Qiang Xue committed
18
 * The SQL statement it represents can be set via the [[sql]] property.
w  
Qiang Xue committed
19
 *
Qiang Xue committed
20
 * To execute a non-query SQL (such as INSERT, DELETE, UPDATE), call [[execute()]].
Qiang Xue committed
21
 * To execute a SQL statement that returns result data set (such as SELECT),
22
 * use [[queryAll()]], [[queryOne()]], [[queryColumn()]], [[queryScalar()]], or [[query()]].
Qiang Xue committed
23 24 25
 * For example,
 *
 * ~~~
Qiang Xue committed
26
 * $users = $connection->createCommand('SELECT * FROM tbl_user')->queryAll();
Qiang Xue committed
27
 * ~~~
w  
Qiang Xue committed
28
 *
Qiang Xue committed
29
 * Command supports SQL statement preparation and parameter binding.
Qiang Xue committed
30 31
 * Call [[bindValue()]] to bind a value to a SQL parameter;
 * Call [[bindParam()]] to bind a PHP variable to a SQL parameter.
w  
Qiang Xue committed
32
 * When binding a parameter, the SQL statement is automatically prepared.
Qiang Xue committed
33
 * You may also call [[prepare()]] explicitly to prepare a SQL statement.
w  
Qiang Xue committed
34
 *
Qiang Xue committed
35 36 37 38 39 40 41 42 43 44 45 46
 * Command also supports building SQL statements by providing methods such as [[insert()]],
 * [[update()]], etc. For example,
 *
 * ~~~
 * $connection->createCommand()->insert('tbl_user', array(
 *     'name' => 'Sam',
 *     'age' => 30,
 * ))->execute();
 * ~~~
 *
 * To build SELECT SQL statements, please use [[QueryBuilder]] instead.
 *
47 48
 * @property string $rawSql The raw SQL with parameter values inserted into the corresponding placeholders in
 * [[sql]]. This property is read-only.
49
 * @property string $sql The SQL statement to be executed.
Qiang Xue committed
50
 *
w  
Qiang Xue committed
51
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
52
 * @since 2.0
w  
Qiang Xue committed
53
 */
w  
Qiang Xue committed
54
class Command extends \yii\base\Component
w  
Qiang Xue committed
55
{
Qiang Xue committed
56 57 58
	/**
	 * @var Connection the DB connection that this command is associated with
	 */
Qiang Xue committed
59
	public $db;
Qiang Xue committed
60
	/**
Qiang Xue committed
61
	 * @var \PDOStatement the PDOStatement object that this command is associated with
Qiang Xue committed
62
	 */
w  
Qiang Xue committed
63 64
	public $pdoStatement;
	/**
65
	 * @var integer the default fetch mode for this command.
w  
Qiang Xue committed
66 67 68
	 * @see http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php
	 */
	public $fetchMode = \PDO::FETCH_ASSOC;
Qiang Xue committed
69 70 71 72 73
	/**
	 * @var string the SQL statement that this command represents
	 */
	private $_sql;
	/**
resurtm committed
74
	 * @var array the parameter log information (name => value)
Qiang Xue committed
75
	 */
Qiang Xue committed
76
	private $_params = array();
Qiang Xue committed
77

w  
Qiang Xue committed
78
	/**
Qiang Xue committed
79
	 * Returns the SQL statement for this command.
w  
Qiang Xue committed
80 81
	 * @return string the SQL statement to be executed
	 */
Qiang Xue committed
82
	public function getSql()
w  
Qiang Xue committed
83
	{
w  
Qiang Xue committed
84
		return $this->_sql;
w  
Qiang Xue committed
85 86 87 88
	}

	/**
	 * Specifies the SQL statement to be executed.
89
	 * The previous SQL execution (if any) will be cancelled, and [[params]] will be cleared as well.
90
	 * @param string $sql the SQL statement to be set.
w  
Qiang Xue committed
91
	 * @return Command this command instance
w  
Qiang Xue committed
92
	 */
93
	public function setSql($sql)
w  
Qiang Xue committed
94
	{
95
		if ($sql !== $this->_sql) {
Qiang Xue committed
96
			$this->cancel();
97
			$this->_sql = $this->db->quoteSql($sql);
98 99
			$this->_params = array();
		}
w  
Qiang Xue committed
100 101 102
		return $this;
	}

Qiang Xue committed
103 104 105 106
	/**
	 * Returns the raw SQL by inserting parameter values into the corresponding placeholders in [[sql]].
	 * Note that the return value of this method should mainly be used for logging purpose.
	 * It is likely that this method returns an invalid SQL due to improper replacement of parameter placeholders.
107
	 * @return string the raw SQL with parameter values inserted into the corresponding placeholders in [[sql]].
Qiang Xue committed
108 109 110
	 */
	public function getRawSql()
	{
111
		if (empty($this->_params)) {
Qiang Xue committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
			return $this->_sql;
		} else {
			$params = array();
			foreach ($this->_params as $name => $value) {
				if (is_string($value)) {
					$params[$name] = $this->db->quoteValue($value);
				} elseif ($value === null) {
					$params[$name] = 'NULL';
				} else {
					$params[$name] = $value;
				}
			}
			if (isset($params[1])) {
				$sql = '';
				foreach (explode('?', $this->_sql) as $i => $part) {
					$sql .= (isset($params[$i]) ? $params[$i] : '') . $part;
				}
				return $sql;
			} else {
				return strtr($this->_sql, $params);
			}
		}
	}

w  
Qiang Xue committed
136 137 138 139 140 141
	/**
	 * Prepares the SQL statement to be executed.
	 * For complex SQL statement that is to be executed multiple times,
	 * this may improve performance.
	 * For SQL statement with binding parameters, this method is invoked
	 * automatically.
Qiang Xue committed
142
	 * @throws Exception if there is any DB error
w  
Qiang Xue committed
143 144 145
	 */
	public function prepare()
	{
w  
Qiang Xue committed
146
		if ($this->pdoStatement == null) {
147
			$sql = $this->getSql();
w  
Qiang Xue committed
148
			try {
Qiang Xue committed
149
				$this->pdoStatement = $this->db->pdo->prepare($sql);
Qiang Xue committed
150
			} catch (\Exception $e) {
151
				$message = $e->getMessage() . "\nFailed to prepare SQL: $sql";
Qiang Xue committed
152
				$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
153
				throw new Exception($message, $errorInfo, (int)$e->getCode(), $e);
w  
Qiang Xue committed
154 155 156 157 158 159
			}
		}
	}

	/**
	 * Cancels the execution of the SQL statement.
Qiang Xue committed
160
	 * This method mainly sets [[pdoStatement]] to be null.
w  
Qiang Xue committed
161 162 163
	 */
	public function cancel()
	{
w  
Qiang Xue committed
164
		$this->pdoStatement = null;
w  
Qiang Xue committed
165 166 167 168
	}

	/**
	 * Binds a parameter to the SQL statement to be executed.
Qiang Xue committed
169
	 * @param string|integer $name parameter identifier. For a prepared statement
w  
Qiang Xue committed
170
	 * using named placeholders, this will be a parameter name of
Qiang Xue committed
171
	 * the form `:name`. For a prepared statement using question mark
w  
Qiang Xue committed
172 173 174 175
	 * placeholders, this will be the 1-indexed position of the parameter.
	 * @param mixed $value Name of the PHP variable to bind to the SQL statement parameter
	 * @param integer $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
	 * @param integer $length length of the data type
Qiang Xue committed
176 177
	 * @param mixed $driverOptions the driver-specific options
	 * @return Command the current command being executed
w  
Qiang Xue committed
178 179 180 181 182
	 * @see http://www.php.net/manual/en/function.PDOStatement-bindParam.php
	 */
	public function bindParam($name, &$value, $dataType = null, $length = null, $driverOptions = null)
	{
		$this->prepare();
Qiang Xue committed
183
		if ($dataType === null) {
184
			$this->pdoStatement->bindParam($name, $value, $this->getPdoType($value));
Qiang Xue committed
185
		} elseif ($length === null) {
w  
Qiang Xue committed
186
			$this->pdoStatement->bindParam($name, $value, $dataType);
Qiang Xue committed
187
		} elseif ($driverOptions === null) {
w  
Qiang Xue committed
188
			$this->pdoStatement->bindParam($name, $value, $dataType, $length);
Qiang Xue committed
189
		} else {
w  
Qiang Xue committed
190
			$this->pdoStatement->bindParam($name, $value, $dataType, $length, $driverOptions);
Qiang Xue committed
191
		}
Qiang Xue committed
192
		$this->_params[$name] =& $value;
w  
Qiang Xue committed
193 194 195 196 197
		return $this;
	}

	/**
	 * Binds a value to a parameter.
Qiang Xue committed
198
	 * @param string|integer $name Parameter identifier. For a prepared statement
w  
Qiang Xue committed
199
	 * using named placeholders, this will be a parameter name of
Qiang Xue committed
200
	 * the form `:name`. For a prepared statement using question mark
w  
Qiang Xue committed
201 202 203
	 * placeholders, this will be the 1-indexed position of the parameter.
	 * @param mixed $value The value to bind to the parameter
	 * @param integer $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
Qiang Xue committed
204
	 * @return Command the current command being executed
w  
Qiang Xue committed
205 206 207 208 209
	 * @see http://www.php.net/manual/en/function.PDOStatement-bindValue.php
	 */
	public function bindValue($name, $value, $dataType = null)
	{
		$this->prepare();
Qiang Xue committed
210
		if ($dataType === null) {
211
			$this->pdoStatement->bindValue($name, $value, $this->getPdoType($value));
Qiang Xue committed
212
		} else {
w  
Qiang Xue committed
213
			$this->pdoStatement->bindValue($name, $value, $dataType);
Qiang Xue committed
214
		}
Qiang Xue committed
215
		$this->_params[$name] = $value;
w  
Qiang Xue committed
216 217 218 219 220
		return $this;
	}

	/**
	 * Binds a list of values to the corresponding parameters.
Qiang Xue committed
221
	 * This is similar to [[bindValue()]] except that it binds multiple values at a time.
w  
Qiang Xue committed
222 223
	 * Note that the SQL data type of each value is determined by its PHP type.
	 * @param array $values the values to be bound. This must be given in terms of an associative
Qiang Xue committed
224
	 * array with array keys being the parameter names, and array values the corresponding parameter values,
resurtm committed
225
	 * e.g. `array(':name' => 'John', ':age' => 25)`. By default, the PDO type of each value is determined
226
	 * by its PHP type. You may explicitly specify the PDO type by using an array: `array(value, type)`,
resurtm committed
227
	 * e.g. `array(':name' => 'John', ':profile' => array($profile, \PDO::PARAM_LOB))`.
w  
Qiang Xue committed
228
	 * @return Command the current command being executed
w  
Qiang Xue committed
229 230 231
	 */
	public function bindValues($values)
	{
Qiang Xue committed
232
		if (!empty($values)) {
Qiang Xue committed
233 234
			$this->prepare();
			foreach ($values as $name => $value) {
235 236 237 238
				if (is_array($value)) {
					$type = $value[1];
					$value = $value[0];
				} else {
239
					$type = $this->getPdoType($value);
240 241
				}
				$this->pdoStatement->bindValue($name, $value, $type);
Qiang Xue committed
242 243 244
				$this->_params[$name] = $value;
			}
		}
w  
Qiang Xue committed
245 246 247
		return $this;
	}

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
	/**
	 * Determines the PDO type for the given PHP data value.
	 * @param mixed $data the data whose PDO type is to be determined
	 * @return integer the PDO type
	 * @see http://www.php.net/manual/en/pdo.constants.php
	 */
	private function getPdoType($data)
	{
		static $typeMap = array( // php type => PDO type
			'boolean' => \PDO::PARAM_BOOL,
			'integer' => \PDO::PARAM_INT,
			'string' => \PDO::PARAM_STR,
			'resource' => \PDO::PARAM_LOB,
			'NULL' => \PDO::PARAM_NULL,
		);
		$type = gettype($data);
		return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR;
	}

w  
Qiang Xue committed
267 268
	/**
	 * Executes the SQL statement.
Qiang Xue committed
269
	 * This method should only be used for executing non-query SQL statement, such as `INSERT`, `DELETE`, `UPDATE` SQLs.
w  
Qiang Xue committed
270 271
	 * No result set will be returned.
	 * @return integer number of rows affected by the execution.
Qiang Xue committed
272
	 * @throws Exception execution failed
w  
Qiang Xue committed
273
	 */
274
	public function execute()
w  
Qiang Xue committed
275
	{
276
		$sql = $this->getSql();
Qiang Xue committed
277

Qiang Xue committed
278
		$rawSql = $this->getRawSql();
Qiang Xue committed
279

Qiang Xue committed
280
		Yii::trace($rawSql, __METHOD__);
Qiang Xue committed
281

Qiang Xue committed
282 283 284 285
		if ($sql == '') {
			return 0;
		}

Qiang Xue committed
286
		$token = $rawSql;
Qiang Xue committed
287
		try {
288
			Yii::beginProfile($token, __METHOD__);
w  
Qiang Xue committed
289 290

			$this->prepare();
291
			$this->pdoStatement->execute();
w  
Qiang Xue committed
292
			$n = $this->pdoStatement->rowCount();
w  
Qiang Xue committed
293

294
			Yii::endProfile($token, __METHOD__);
w  
Qiang Xue committed
295
			return $n;
Qiang Xue committed
296
		} catch (\Exception $e) {
297
			Yii::endProfile($token, __METHOD__);
298
			$message = $e->getMessage() . "\nThe SQL being executed was: $rawSql";
Qiang Xue committed
299
			$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
300
			throw new Exception($message, $errorInfo, (int)$e->getCode(), $e);
w  
Qiang Xue committed
301 302 303 304 305
		}
	}

	/**
	 * Executes the SQL statement and returns query result.
Qiang Xue committed
306 307 308
	 * This method is for executing a SQL query that returns result set, such as `SELECT`.
	 * @return DataReader the reader object for fetching the query result
	 * @throws Exception execution failed
w  
Qiang Xue committed
309
	 */
310
	public function query()
w  
Qiang Xue committed
311
	{
312
		return $this->queryInternal('');
w  
Qiang Xue committed
313 314 315
	}

	/**
Qiang Xue committed
316
	 * Executes the SQL statement and returns ALL rows at once.
317
	 * @param integer $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
Qiang Xue committed
318 319
	 * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
	 * @return array all rows of the query result. Each array element is an array representing a row of data.
w  
Qiang Xue committed
320
	 * An empty array is returned if the query results in nothing.
Qiang Xue committed
321
	 * @throws Exception execution failed
w  
Qiang Xue committed
322
	 */
323
	public function queryAll($fetchMode = null)
w  
Qiang Xue committed
324
	{
325
		return $this->queryInternal('fetchAll', $fetchMode);
w  
Qiang Xue committed
326 327 328 329
	}

	/**
	 * Executes the SQL statement and returns the first row of the result.
Qiang Xue committed
330
	 * This method is best used when only the first row of result is needed for a query.
331
	 * @param integer $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
Qiang Xue committed
332 333 334
	 * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
	 * @return array|boolean the first row (in terms of an array) of the query result. False is returned if the query
	 * results in nothing.
Qiang Xue committed
335
	 * @throws Exception execution failed
w  
Qiang Xue committed
336
	 */
337
	public function queryOne($fetchMode = null)
w  
Qiang Xue committed
338
	{
339
		return $this->queryInternal('fetch', $fetchMode);
w  
Qiang Xue committed
340 341 342 343
	}

	/**
	 * Executes the SQL statement and returns the value of the first column in the first row of data.
Qiang Xue committed
344
	 * This method is best used when only a single value is needed for a query.
Qiang Xue committed
345
	 * @return string|boolean the value of the first column in the first row of the query result.
Qiang Xue committed
346
	 * False is returned if there is no value.
Qiang Xue committed
347
	 * @throws Exception execution failed
w  
Qiang Xue committed
348
	 */
349
	public function queryScalar()
w  
Qiang Xue committed
350
	{
351
		$result = $this->queryInternal('fetchColumn', 0);
w  
Qiang Xue committed
352
		if (is_resource($result) && get_resource_type($result) === 'stream') {
w  
Qiang Xue committed
353
			return stream_get_contents($result);
Qiang Xue committed
354
		} else {
w  
Qiang Xue committed
355
			return $result;
w  
Qiang Xue committed
356
		}
w  
Qiang Xue committed
357 358 359 360
	}

	/**
	 * Executes the SQL statement and returns the first column of the result.
Qiang Xue committed
361 362 363
	 * This method is best used when only the first column of result (i.e. the first element in each row)
	 * is needed for a query.
	 * @return array the first column of the query result. Empty array is returned if the query results in nothing.
Qiang Xue committed
364
	 * @throws Exception execution failed
w  
Qiang Xue committed
365
	 */
366
	public function queryColumn()
w  
Qiang Xue committed
367
	{
368
		return $this->queryInternal('fetchAll', \PDO::FETCH_COLUMN);
w  
Qiang Xue committed
369 370 371
	}

	/**
Qiang Xue committed
372
	 * Performs the actual DB query of a SQL statement.
w  
Qiang Xue committed
373
	 * @param string $method method of PDOStatement to be called
374
	 * @param integer $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
Qiang Xue committed
375
	 * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
w  
Qiang Xue committed
376
	 * @return mixed the method execution result
Qiang Xue committed
377
	 * @throws Exception if the query causes any problem
w  
Qiang Xue committed
378
	 */
379
	private function queryInternal($method, $fetchMode = null)
w  
Qiang Xue committed
380
	{
Qiang Xue committed
381
		$db = $this->db;
Qiang Xue committed
382
		$rawSql = $this->getRawSql();
Qiang Xue committed
383

Qiang Xue committed
384
		Yii::trace($rawSql, __METHOD__);
385

Qiang Xue committed
386
		/** @var $cache \yii\caching\Cache */
387
		if ($db->enableQueryCache && $method !== '') {
388
			$cache = is_string($db->queryCache) ? Yii::$app->getComponent($db->queryCache) : $db->queryCache;
Qiang Xue committed
389 390
		}

391
		if (isset($cache) && $cache instanceof Cache) {
392
			$cacheKey = array(
Qiang Xue committed
393 394 395
				__CLASS__,
				$db->dsn,
				$db->username,
Qiang Xue committed
396
				$rawSql,
397
			);
Qiang Xue committed
398
			if (($result = $cache->get($cacheKey)) !== false) {
399
				Yii::trace('Query result served from cache', __METHOD__);
w  
Qiang Xue committed
400 401 402 403
				return $result;
			}
		}

Qiang Xue committed
404
		$token = $rawSql;
Qiang Xue committed
405
		try {
406
			Yii::beginProfile($token, __METHOD__);
w  
Qiang Xue committed
407 408

			$this->prepare();
409
			$this->pdoStatement->execute();
w  
Qiang Xue committed
410

Qiang Xue committed
411
			if ($method === '') {
w  
Qiang Xue committed
412
				$result = new DataReader($this);
Qiang Xue committed
413
			} else {
Qiang Xue committed
414 415 416
				if ($fetchMode === null) {
					$fetchMode = $this->fetchMode;
				}
w  
Qiang Xue committed
417 418
				$result = call_user_func_array(array($this->pdoStatement, $method), (array)$fetchMode);
				$this->pdoStatement->closeCursor();
w  
Qiang Xue committed
419 420
			}

421
			Yii::endProfile($token, __METHOD__);
w  
Qiang Xue committed
422

423
			if (isset($cache, $cacheKey) && $cache instanceof Cache) {
424
				$cache->set($cacheKey, $result, $db->queryCacheDuration, $db->queryCacheDependency);
425
				Yii::trace('Saved query result in cache', __METHOD__);
Qiang Xue committed
426
			}
w  
Qiang Xue committed
427 428

			return $result;
Qiang Xue committed
429
		} catch (\Exception $e) {
430
			Yii::endProfile($token, __METHOD__);
431
			$message = $e->getMessage()  . "\nThe SQL being executed was: $rawSql";
Qiang Xue committed
432
			$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
433
			throw new Exception($message, $errorInfo, (int)$e->getCode(), $e);
w  
Qiang Xue committed
434 435
		}
	}
Qiang Xue committed
436 437 438 439 440 441

	/**
	 * Creates an INSERT command.
	 * For example,
	 *
	 * ~~~
Qiang Xue committed
442 443 444
	 * $connection->createCommand()->insert('tbl_user', array(
	 *     'name' => 'Sam',
	 *     'age' => 30,
Qiang Xue committed
445 446 447 448 449 450 451 452
	 * ))->execute();
	 * ~~~
	 *
	 * The method will properly escape the column names, and bind the values to be inserted.
	 *
	 * Note that the created command is not executed until [[execute()]] is called.
	 *
	 * @param string $table the table that new rows will be inserted into.
resurtm committed
453
	 * @param array $columns the column data (name => value) to be inserted into the table.
Qiang Xue committed
454 455
	 * @return Command the command object itself
	 */
Qiang Xue committed
456
	public function insert($table, $columns)
Qiang Xue committed
457
	{
Qiang Xue committed
458
		$params = array();
Qiang Xue committed
459
		$sql = $this->db->getQueryBuilder()->insert($table, $columns, $params);
Qiang Xue committed
460 461 462
		return $this->setSql($sql)->bindValues($params);
	}

Qiang Xue committed
463 464 465 466 467 468 469 470 471 472 473 474
	/**
	 * Creates a batch INSERT command.
	 * For example,
	 *
	 * ~~~
	 * $connection->createCommand()->batchInsert('tbl_user', array('name', 'age'), array(
	 *     array('Tom', 30),
	 *     array('Jane', 20),
	 *     array('Linda', 25),
	 * ))->execute();
	 * ~~~
	 *
475
	 * Note that the values in each row must match the corresponding column names.
Qiang Xue committed
476 477 478 479 480 481 482 483 484 485 486 487
	 *
	 * @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 Command the command object itself
	 */
	public function batchInsert($table, $columns, $rows)
	{
		$sql = $this->db->getQueryBuilder()->batchInsert($table, $columns, $rows);
		return $this->setSql($sql);
	}

Qiang Xue committed
488 489 490 491 492
	/**
	 * Creates an UPDATE command.
	 * For example,
	 *
	 * ~~~
Qiang Xue committed
493 494
	 * $connection->createCommand()->update('tbl_user', array(
	 *     'status' => 1,
Qiang Xue committed
495 496 497 498 499 500 501 502
	 * ), 'age > 30')->execute();
	 * ~~~
	 *
	 * The method will properly escape the column names and bind the values to be updated.
	 *
	 * Note that the created command is not executed until [[execute()]] is called.
	 *
	 * @param string $table the table to be updated.
resurtm committed
503
	 * @param array $columns the column data (name => value) to be updated.
504
	 * @param string|array $condition the condition that will be put in the WHERE part. Please
Qiang Xue committed
505 506 507 508 509 510
	 * refer to [[Query::where()]] on how to specify condition.
	 * @param array $params the parameters to be bound to the command
	 * @return Command the command object itself
	 */
	public function update($table, $columns, $condition = '', $params = array())
	{
Qiang Xue committed
511
		$sql = $this->db->getQueryBuilder()->update($table, $columns, $condition, $params);
Qiang Xue committed
512 513 514 515 516 517 518 519
		return $this->setSql($sql)->bindValues($params);
	}

	/**
	 * Creates a DELETE command.
	 * For example,
	 *
	 * ~~~
Qiang Xue committed
520
	 * $connection->createCommand()->delete('tbl_user', 'status = 0')->execute();
Qiang Xue committed
521 522 523 524 525 526 527
	 * ~~~
	 *
	 * The method will properly escape the table and column names.
	 *
	 * Note that the created command is not executed until [[execute()]] is called.
	 *
	 * @param string $table the table where the data will be deleted from.
528
	 * @param string|array $condition the condition that will be put in the WHERE part. Please
Qiang Xue committed
529 530 531 532 533 534
	 * refer to [[Query::where()]] on how to specify condition.
	 * @param array $params the parameters to be bound to the command
	 * @return Command the command object itself
	 */
	public function delete($table, $condition = '', $params = array())
	{
535
		$sql = $this->db->getQueryBuilder()->delete($table, $condition, $params);
Qiang Xue committed
536 537 538 539 540 541 542
		return $this->setSql($sql)->bindValues($params);
	}


	/**
	 * Creates a SQL command for creating a new DB table.
	 *
resurtm committed
543
	 * The columns in the new table should be specified as name-definition pairs (e.g. 'name' => 'string'),
Qiang Xue committed
544 545
	 * 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
546
	 * The method [[QueryBuilder::getColumnType()]] will be called
Qiang Xue committed
547 548 549 550 551 552 553
	 * to convert the abstract column types to physical ones. For example, `string` will be converted
	 * as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
	 *
	 * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
	 * inserted into the generated SQL.
	 *
	 * @param string $table the name of the table to be created. The name will be properly quoted by the method.
resurtm committed
554
	 * @param array $columns the columns (name => definition) in the new table.
Qiang Xue committed
555 556 557 558 559
	 * @param string $options additional SQL fragment that will be appended to the generated SQL.
	 * @return Command the command object itself
	 */
	public function createTable($table, $columns, $options = null)
	{
Qiang Xue committed
560
		$sql = $this->db->getQueryBuilder()->createTable($table, $columns, $options);
Qiang Xue committed
561 562 563 564 565 566 567 568 569 570 571
		return $this->setSql($sql);
	}

	/**
	 * Creates a SQL command for renaming a DB table.
	 * @param string $table the table to be renamed. The name will be properly quoted by the method.
	 * @param string $newName the new table name. The name will be properly quoted by the method.
	 * @return Command the command object itself
	 */
	public function renameTable($table, $newName)
	{
Qiang Xue committed
572
		$sql = $this->db->getQueryBuilder()->renameTable($table, $newName);
Qiang Xue committed
573 574 575 576 577 578 579 580 581 582
		return $this->setSql($sql);
	}

	/**
	 * Creates a SQL command for dropping a DB table.
	 * @param string $table the table to be dropped. The name will be properly quoted by the method.
	 * @return Command the command object itself
	 */
	public function dropTable($table)
	{
Qiang Xue committed
583
		$sql = $this->db->getQueryBuilder()->dropTable($table);
Qiang Xue committed
584 585 586 587 588 589 590 591 592 593
		return $this->setSql($sql);
	}

	/**
	 * Creates a SQL command for truncating a DB table.
	 * @param string $table the table to be truncated. The name will be properly quoted by the method.
	 * @return Command the command object itself
	 */
	public function truncateTable($table)
	{
Qiang Xue committed
594
		$sql = $this->db->getQueryBuilder()->truncateTable($table);
Qiang Xue committed
595 596 597 598 599 600 601 602 603 604 605 606 607 608
		return $this->setSql($sql);
	}

	/**
	 * Creates a SQL command 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.
	 * @param string $type the column type. [[\yii\db\QueryBuilder::getColumnType()]] will be called
	 * to convert the give column type to the physical one. For example, `string` will be converted
	 * as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
	 * @return Command the command object itself
	 */
	public function addColumn($table, $column, $type)
	{
Qiang Xue committed
609
		$sql = $this->db->getQueryBuilder()->addColumn($table, $column, $type);
Qiang Xue committed
610 611 612 613 614 615 616 617 618 619 620
		return $this->setSql($sql);
	}

	/**
	 * Creates a SQL command 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 Command the command object itself
	 */
	public function dropColumn($table, $column)
	{
Qiang Xue committed
621
		$sql = $this->db->getQueryBuilder()->dropColumn($table, $column);
Qiang Xue committed
622 623 624 625 626 627 628 629 630 631 632 633
		return $this->setSql($sql);
	}

	/**
	 * Creates a SQL command for renaming a column.
	 * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
	 * @param string $oldName the old name of the column. The name will be properly quoted by the method.
	 * @param string $newName the new name of the column. The name will be properly quoted by the method.
	 * @return Command the command object itself
	 */
	public function renameColumn($table, $oldName, $newName)
	{
Qiang Xue committed
634
		$sql = $this->db->getQueryBuilder()->renameColumn($table, $oldName, $newName);
Qiang Xue committed
635 636 637 638 639 640 641 642 643 644 645 646 647 648
		return $this->setSql($sql);
	}

	/**
	 * Creates a SQL command 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.
	 * @param string $type the column type. [[\yii\db\QueryBuilder::getColumnType()]] will be called
	 * to convert the give column type to the physical one. For example, `string` will be converted
	 * as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
	 * @return Command the command object itself
	 */
	public function alterColumn($table, $column, $type)
	{
Qiang Xue committed
649
		$sql = $this->db->getQueryBuilder()->alterColumn($table, $column, $type);
Qiang Xue committed
650 651
		return $this->setSql($sql);
	}
Qiang Xue committed
652

653 654 655 656 657 658 659
	/**
	 * Creates a SQL command for adding a primary key constraint to an existing table.
	 * The method will properly quote the table and column names.
	 * @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 Command the command object itself.
Qiang Xue committed
660
	 */
661
	public function addPrimaryKey($name, $table, $columns)
662 663 664 665
	{
		$sql = $this->db->getQueryBuilder()->addPrimaryKey($name, $table, $columns);
		return $this->setSql($sql);
	}
Qiang Xue committed
666

667 668 669 670 671
	/**
	 * Creates a SQL command 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 Command the command object itself
Qiang Xue committed
672
	 */
673
	public function dropPrimaryKey($name, $table)
674
	{
675
		$sql = $this->db->getQueryBuilder()->dropPrimaryKey($name, $table);
676 677
		return $this->setSql($sql);
	}
Qiang Xue committed
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692

	/**
	 * Creates a SQL command 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.
	 * @param string $columns the name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas.
	 * @param string $refTable the table that the foreign key references to.
	 * @param string $refColumns the name of the column that the foreign key references to. If there are multiple columns, separate them with commas.
	 * @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 Command the command object itself
	 */
	public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
	{
Qiang Xue committed
693
		$sql = $this->db->getQueryBuilder()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update);
Qiang Xue committed
694 695 696 697 698 699 700 701 702 703 704
		return $this->setSql($sql);
	}

	/**
	 * Creates a SQL command 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 Command the command object itself
	 */
	public function dropForeignKey($name, $table)
	{
Qiang Xue committed
705
		$sql = $this->db->getQueryBuilder()->dropForeignKey($name, $table);
Qiang Xue committed
706 707 708 709 710 711 712 713 714 715 716 717 718 719
		return $this->setSql($sql);
	}

	/**
	 * Creates a SQL command 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.
	 * @param string $columns the column(s) that should be included in the index. If there are multiple columns, please separate them
	 * by commas. The column names will be properly quoted by the method.
	 * @param boolean $unique whether to add UNIQUE constraint on the created index.
	 * @return Command the command object itself
	 */
	public function createIndex($name, $table, $columns, $unique = false)
	{
Qiang Xue committed
720
		$sql = $this->db->getQueryBuilder()->createIndex($name, $table, $columns, $unique);
Qiang Xue committed
721 722 723 724 725 726 727 728 729 730 731
		return $this->setSql($sql);
	}

	/**
	 * Creates a SQL command 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 Command the command object itself
	 */
	public function dropIndex($name, $table)
	{
Qiang Xue committed
732
		$sql = $this->db->getQueryBuilder()->dropIndex($name, $table);
Qiang Xue committed
733 734
		return $this->setSql($sql);
	}
Qiang Xue committed
735 736 737 738 739 740 741 742 743 744 745 746 747

	/**
	 * Creates a SQL command for resetting 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.
	 * @param string $table the name of the table whose primary key sequence will be reset
	 * @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.
	 * @return Command the command object itself
	 * @throws NotSupportedException if this is not supported by the underlying DBMS
	 */
	public function resetSequence($table, $value = null)
	{
Qiang Xue committed
748
		$sql = $this->db->getQueryBuilder()->resetSequence($table, $value);
Qiang Xue committed
749 750 751 752 753 754 755 756 757 758 759 760 761
		return $this->setSql($sql);
	}

	/**
	 * Builds a SQL command for enabling or disabling integrity check.
	 * @param boolean $check whether to turn on or off the integrity check.
	 * @param string $schema the schema name of the tables. Defaults to empty string, meaning the current
	 * or default schema.
	 * @return Command the command object itself
	 * @throws NotSupportedException if this is not supported by the underlying DBMS
	 */
	public function checkIntegrity($check = true, $schema = '')
	{
Qiang Xue committed
762
		$sql = $this->db->getQueryBuilder()->checkIntegrity($check, $schema);
Qiang Xue committed
763 764
		return $this->setSql($sql);
	}
w  
Qiang Xue committed
765
}