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

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

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

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),
Qiang Xue committed
22
 * use [[queryAll()]], [[queryRow()]], [[queryColumn()]], [[queryScalar()]], or [[query()]].
Qiang Xue committed
23 24 25
 * For example,
 *
 * ~~~
Qiang Xue committed
26
 * $users = \Yii::$application->db->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
 * @property string $sql the SQL statement to be executed
 *
w  
Qiang Xue committed
37
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
38
 * @since 2.0
w  
Qiang Xue committed
39
 */
w  
Qiang Xue committed
40
class Command extends \yii\base\Component
w  
Qiang Xue committed
41
{
Qiang Xue committed
42 43 44
	/**
	 * @var Connection the DB connection that this command is associated with
	 */
w  
Qiang Xue committed
45
	public $connection;
Qiang Xue committed
46 47 48
	/**
	 * @var \PDOStatement the PDOStatement object that this command contains
	 */
w  
Qiang Xue committed
49 50
	public $pdoStatement;
	/**
Qiang Xue committed
51
	 * @var mixed the default fetch mode for this command.
w  
Qiang Xue committed
52 53 54
	 * @see http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php
	 */
	public $fetchMode = \PDO::FETCH_ASSOC;
Qiang Xue committed
55 56 57 58 59
	/**
	 * @var string the SQL statement that this command represents
	 */
	private $_sql;
	/**
Qiang Xue committed
60
	 * @var array the parameter log information (name=>value)
Qiang Xue committed
61
	 */
Qiang Xue committed
62
	private $_params = array();
Qiang Xue committed
63

w  
Qiang Xue committed
64 65
	/**
	 * Constructor.
Qiang Xue committed
66
	 * @param Connection $connection the database connection
Qiang Xue committed
67 68
	 * @param string $sql the SQL statement to be executed
	 * @param array $params the parameters to be bound to the SQL statement
w  
Qiang Xue committed
69
	 */
Qiang Xue committed
70
	public function __construct($connection, $sql = null, $params = array())
w  
Qiang Xue committed
71
	{
w  
Qiang Xue committed
72
		$this->connection = $connection;
Qiang Xue committed
73 74
		$this->_sql = $sql;
		$this->bindValues($params);
w  
Qiang Xue committed
75 76 77
	}

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

	/**
	 * Specifies the SQL statement to be executed.
Qiang Xue committed
88
	 * Any previous execution will be terminated or cancelled.
Qiang Xue committed
89
	 * @param string $value the SQL statement to be set.
w  
Qiang Xue committed
90
	 * @return Command this command instance
w  
Qiang Xue committed
91
	 */
w  
Qiang Xue committed
92
	public function setSql($value)
w  
Qiang Xue committed
93
	{
Qiang Xue committed
94
		$this->_sql = $value;
Qiang Xue committed
95
		$this->_params = array();
w  
Qiang Xue committed
96 97 98 99 100 101 102 103 104 105
		$this->cancel();
		return $this;
	}

	/**
	 * 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
106
	 * @throws Exception if there is any DB error
w  
Qiang Xue committed
107 108 109
	 */
	public function prepare()
	{
w  
Qiang Xue committed
110
		if ($this->pdoStatement == null) {
Qiang Xue committed
111
			$sql = $this->connection->expandTablePrefix($this->getSql());
w  
Qiang Xue committed
112
			try {
Qiang Xue committed
113
				$this->pdoStatement = $this->connection->pdo->prepare($sql);
Qiang Xue committed
114
			} catch (\Exception $e) {
Qiang Xue committed
115
				\Yii::error($e->getMessage() . "\nFailed to prepare SQL: $sql", __CLASS__);
Qiang Xue committed
116
				$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
Qiang Xue committed
117
				throw new Exception($e->getMessage(), (int)$e->getCode(), $errorInfo);
w  
Qiang Xue committed
118 119 120 121 122 123
			}
		}
	}

	/**
	 * Cancels the execution of the SQL statement.
Qiang Xue committed
124
	 * This method mainly sets [[pdoStatement]] to be null.
w  
Qiang Xue committed
125 126 127
	 */
	public function cancel()
	{
w  
Qiang Xue committed
128
		$this->pdoStatement = null;
w  
Qiang Xue committed
129 130 131 132
	}

	/**
	 * Binds a parameter to the SQL statement to be executed.
Qiang Xue committed
133
	 * @param string|integer $name parameter identifier. For a prepared statement
w  
Qiang Xue committed
134
	 * using named placeholders, this will be a parameter name of
Qiang Xue committed
135
	 * the form `:name`. For a prepared statement using question mark
w  
Qiang Xue committed
136 137 138 139
	 * 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
140 141
	 * @param mixed $driverOptions the driver-specific options
	 * @return Command the current command being executed
w  
Qiang Xue committed
142 143 144 145 146
	 * @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
147
		if ($dataType === null) {
w  
Qiang Xue committed
148
			$this->pdoStatement->bindParam($name, $value, $this->connection->getPdoType(gettype($value)));
Qiang Xue committed
149
		} elseif ($length === null) {
w  
Qiang Xue committed
150
			$this->pdoStatement->bindParam($name, $value, $dataType);
Qiang Xue committed
151
		} elseif ($driverOptions === null) {
w  
Qiang Xue committed
152
			$this->pdoStatement->bindParam($name, $value, $dataType, $length);
Qiang Xue committed
153
		} else {
w  
Qiang Xue committed
154
			$this->pdoStatement->bindParam($name, $value, $dataType, $length, $driverOptions);
Qiang Xue committed
155
		}
Qiang Xue committed
156
		$this->_params[$name] =& $value;
w  
Qiang Xue committed
157 158 159 160 161
		return $this;
	}

	/**
	 * Binds a value to a parameter.
Qiang Xue committed
162
	 * @param string|integer $name Parameter identifier. For a prepared statement
w  
Qiang Xue committed
163
	 * using named placeholders, this will be a parameter name of
Qiang Xue committed
164
	 * the form `:name`. For a prepared statement using question mark
w  
Qiang Xue committed
165 166 167
	 * 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
168
	 * @return Command the current command being executed
w  
Qiang Xue committed
169 170 171 172 173
	 * @see http://www.php.net/manual/en/function.PDOStatement-bindValue.php
	 */
	public function bindValue($name, $value, $dataType = null)
	{
		$this->prepare();
Qiang Xue committed
174
		if ($dataType === null) {
w  
Qiang Xue committed
175
			$this->pdoStatement->bindValue($name, $value, $this->connection->getPdoType(gettype($value)));
Qiang Xue committed
176
		} else {
w  
Qiang Xue committed
177
			$this->pdoStatement->bindValue($name, $value, $dataType);
Qiang Xue committed
178
		}
Qiang Xue committed
179
		$this->_params[$name] = $value;
w  
Qiang Xue committed
180 181 182 183 184
		return $this;
	}

	/**
	 * Binds a list of values to the corresponding parameters.
Qiang Xue committed
185
	 * This is similar to [[bindValue()]] except that it binds multiple values at a time.
w  
Qiang Xue committed
186 187
	 * 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
188
	 * array with array keys being the parameter names, and array values the corresponding parameter values,
189 190 191
	 * e.g. `array(':name'=>'John', ':age'=>25)`. By default, the PDO type of each value is determined
	 * by its PHP type. You may explicitly specify the PDO type by using an array: `array(value, type)`,
	 * e.g. `array(':name'=>'John', ':profile'=>array($profile, \PDO::PARAM_LOB))`.
w  
Qiang Xue committed
192
	 * @return Command the current command being executed
w  
Qiang Xue committed
193 194 195
	 */
	public function bindValues($values)
	{
Qiang Xue committed
196
		if (!empty($values)) {
Qiang Xue committed
197 198
			$this->prepare();
			foreach ($values as $name => $value) {
199 200 201 202 203 204 205
				if (is_array($value)) {
					$type = $value[1];
					$value = $value[0];
				} else {
					$type = $this->connection->getPdoType(gettype($value));
				}
				$this->pdoStatement->bindValue($name, $value, $type);
Qiang Xue committed
206 207 208
				$this->_params[$name] = $value;
			}
		}
w  
Qiang Xue committed
209 210 211 212 213
		return $this;
	}

	/**
	 * Executes the SQL statement.
Qiang Xue committed
214
	 * This method should only be used for executing non-query SQL statement, such as `INSERT`, `DELETE`, `UPDATE` SQLs.
w  
Qiang Xue committed
215 216
	 * No result set will be returned.
	 * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
Qiang Xue committed
217 218
	 * to [[bindValues()]]. Note that if you pass parameters in this way, any previous call to [[bindParam()]]
	 * or [[bindValue()]] will be ignored.
w  
Qiang Xue committed
219
	 * @return integer number of rows affected by the execution.
Qiang Xue committed
220
	 * @throws Exception execution failed
w  
Qiang Xue committed
221 222 223
	 */
	public function execute($params = array())
	{
Qiang Xue committed
224
		$sql = $this->connection->expandTablePrefix($this->getSql());
Qiang Xue committed
225 226 227
		$this->_params = array_merge($this->_params, $params);
		if ($this->_params === array()) {
			$paramLog = '';
Qiang Xue committed
228
		} else {
Qiang Xue committed
229
			$paramLog = "\nParameters: " . var_export($this->_params, true);
w  
Qiang Xue committed
230
		}
Qiang Xue committed
231 232

		\Yii::trace("Executing SQL: {$sql}{$paramLog}", __CLASS__);
Qiang Xue committed
233

Qiang Xue committed
234 235 236 237
		try {
			if ($this->connection->enableProfiling) {
				\Yii::beginProfile(__METHOD__ . "($sql)", __CLASS__);
			}
w  
Qiang Xue committed
238 239

			$this->prepare();
Qiang Xue committed
240
			if ($params === array()) {
w  
Qiang Xue committed
241
				$this->pdoStatement->execute();
Qiang Xue committed
242
			} else {
w  
Qiang Xue committed
243
				$this->pdoStatement->execute($params);
Qiang Xue committed
244
			}
w  
Qiang Xue committed
245
			$n = $this->pdoStatement->rowCount();
w  
Qiang Xue committed
246

Qiang Xue committed
247 248 249
			if ($this->connection->enableProfiling) {
				\Yii::endProfile(__METHOD__ . "($sql)", __CLASS__);
			}
w  
Qiang Xue committed
250
			return $n;
Qiang Xue committed
251
		} catch (\Exception $e) {
Qiang Xue committed
252 253 254 255 256 257 258
			if ($this->connection->enableProfiling) {
				\Yii::endProfile(__METHOD__ . "($sql)", __CLASS__);
			}
			$message = $e->getMessage();
			\Yii::error("$message\nFailed to execute SQL: {$sql}{$paramLog}", __CLASS__);
			$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
			throw new Exception($message, (int)$e->getCode(), $errorInfo);
w  
Qiang Xue committed
259 260 261 262 263
		}
	}

	/**
	 * Executes the SQL statement and returns query result.
Qiang Xue committed
264
	 * This method is for executing a SQL query that returns result set, such as `SELECT`.
w  
Qiang Xue committed
265
	 * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
Qiang Xue committed
266 267
	 * to [[bindValues()]]. Note that if you pass parameters in this way, any previous call to [[bindParam()]]
	 * or [[bindValue()]] will be ignored.
Qiang Xue committed
268 269
	 * @return DataReader the reader object for fetching the query result
	 * @throws Exception execution failed
w  
Qiang Xue committed
270 271 272
	 */
	public function query($params = array())
	{
w  
Qiang Xue committed
273
		return $this->queryInternal('', $params);
w  
Qiang Xue committed
274 275 276
	}

	/**
Qiang Xue committed
277
	 * Executes the SQL statement and returns ALL rows at once.
Qiang Xue committed
278
	 * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
Qiang Xue committed
279 280
	 * to [[bindValues()]]. Note that if you pass parameters in this way, any previous call to [[bindParam()]]
	 * or [[bindValue()]] will be ignored.
Qiang Xue committed
281 282 283
	 * @param mixed $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
	 * 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
284
	 * An empty array is returned if the query results in nothing.
Qiang Xue committed
285
	 * @throws Exception execution failed
w  
Qiang Xue committed
286
	 */
w  
Qiang Xue committed
287
	public function queryAll($params = array(), $fetchMode = null)
w  
Qiang Xue committed
288
	{
w  
Qiang Xue committed
289
		return $this->queryInternal('fetchAll', $params, $fetchMode);
w  
Qiang Xue committed
290 291 292 293
	}

	/**
	 * Executes the SQL statement and returns the first row of the result.
Qiang Xue committed
294
	 * This method is best used when only the first row of result is needed for a query.
Qiang Xue committed
295
	 * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
Qiang Xue committed
296 297
	 * to [[bindValues()]]. Note that if you pass parameters in this way, any previous call to [[bindParam()]]
	 * or [[bindValue()]] will be ignored.
Qiang Xue committed
298 299 300 301
	 * @param mixed $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
	 * 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
302
	 * @throws Exception execution failed
w  
Qiang Xue committed
303
	 */
w  
Qiang Xue committed
304
	public function queryRow($params = array(), $fetchMode = null)
w  
Qiang Xue committed
305
	{
w  
Qiang Xue committed
306
		return $this->queryInternal('fetch', $params, $fetchMode);
w  
Qiang Xue committed
307 308 309 310
	}

	/**
	 * Executes the SQL statement and returns the value of the first column in the first row of data.
Qiang Xue committed
311
	 * This method is best used when only a single value is needed for a query.
w  
Qiang Xue committed
312
	 * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
Qiang Xue committed
313 314 315
	 * to [[bindValues()]]. Note that if you pass parameters in this way, any previous call to [[bindParam()]]
	 * or [[bindValue()]] will be ignored.
	 * @return string|boolean the value of the first column in the first row of the query result.
Qiang Xue committed
316
	 * False is returned if there is no value.
Qiang Xue committed
317
	 * @throws Exception execution failed
w  
Qiang Xue committed
318 319 320
	 */
	public function queryScalar($params = array())
	{
Qiang Xue committed
321
		$result = $this->queryInternal('fetchColumn', $params, 0);
w  
Qiang Xue committed
322
		if (is_resource($result) && get_resource_type($result) === 'stream') {
w  
Qiang Xue committed
323
			return stream_get_contents($result);
Qiang Xue committed
324
		} else {
w  
Qiang Xue committed
325
			return $result;
w  
Qiang Xue committed
326
		}
w  
Qiang Xue committed
327 328 329 330
	}

	/**
	 * Executes the SQL statement and returns the first column of the result.
Qiang Xue committed
331 332
	 * 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.
w  
Qiang Xue committed
333
	 * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
Qiang Xue committed
334 335
	 * to [[bindValues()]]. Note that if you pass parameters in this way, any previous call to [[bindParam()]]
	 * or [[bindValue()]] will be ignored.
Qiang Xue committed
336
	 * @return array the first column of the query result. Empty array is returned if the query results in nothing.
Qiang Xue committed
337
	 * @throws Exception execution failed
w  
Qiang Xue committed
338 339 340
	 */
	public function queryColumn($params = array())
	{
w  
Qiang Xue committed
341
		return $this->queryInternal('fetchAll', $params, \PDO::FETCH_COLUMN);
w  
Qiang Xue committed
342 343 344
	}

	/**
Qiang Xue committed
345
	 * Performs the actual DB query of a SQL statement.
w  
Qiang Xue committed
346 347
	 * @param string $method method of PDOStatement to be called
	 * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
Qiang Xue committed
348 349
	 * to [[bindValues()]]. Note that if you pass parameters in this way, any previous call to [[bindParam()]]
	 * or [[bindValue()]] will be ignored.
Qiang Xue committed
350 351
	 * @param mixed $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
	 * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
w  
Qiang Xue committed
352 353
	 * @return mixed the method execution result
	 */
w  
Qiang Xue committed
354
	private function queryInternal($method, $params, $fetchMode = null)
w  
Qiang Xue committed
355
	{
Qiang Xue committed
356
		$db = $this->connection;
Qiang Xue committed
357
		$sql = $db->expandTablePrefix($this->getSql());
Qiang Xue committed
358 359 360
		$this->_params = array_merge($this->_params, $params);
		if ($this->_params === array()) {
			$paramLog = '';
Qiang Xue committed
361
		} else {
Qiang Xue committed
362
			$paramLog = "\nParameters: " . var_export($this->_params, true);
w  
Qiang Xue committed
363
		}
Qiang Xue committed
364 365

		\Yii::trace("Querying SQL: {$sql}{$paramLog}", __CLASS__);
366

Qiang Xue committed
367
		if ($db->queryCachingCount > 0 && $db->queryCachingDuration >= 0 && $method !== '') {
Qiang Xue committed
368
			$cache = \Yii::$application->getComponent($db->queryCacheID);
Qiang Xue committed
369 370 371
		}

		if (isset($cache)) {
Qiang Xue committed
372
			$db->queryCachingCount--;
Qiang Xue committed
373
			$cacheKey = __CLASS__ . "/{$db->dsn}/{$db->username}/$sql/$paramLog";
Qiang Xue committed
374
			if (($result = $cache->get($cacheKey)) !== false) {
Qiang Xue committed
375
				\Yii::trace('Query result found in cache', __CLASS__);
w  
Qiang Xue committed
376 377 378 379
				return $result;
			}
		}

Qiang Xue committed
380 381 382 383
		try {
			if ($db->enableProfiling) {
				\Yii::beginProfile(__METHOD__ . "($sql)", __CLASS__);
			}
w  
Qiang Xue committed
384 385

			$this->prepare();
Qiang Xue committed
386
			if ($params === array()) {
w  
Qiang Xue committed
387
				$this->pdoStatement->execute();
Qiang Xue committed
388
			} else {
w  
Qiang Xue committed
389
				$this->pdoStatement->execute($params);
Qiang Xue committed
390
			}
w  
Qiang Xue committed
391

Qiang Xue committed
392
			if ($method === '') {
w  
Qiang Xue committed
393
				$result = new DataReader($this);
Qiang Xue committed
394
			} else {
Qiang Xue committed
395 396 397
				if ($fetchMode === null) {
					$fetchMode = $this->fetchMode;
				}
w  
Qiang Xue committed
398 399
				$result = call_user_func_array(array($this->pdoStatement, $method), (array)$fetchMode);
				$this->pdoStatement->closeCursor();
w  
Qiang Xue committed
400 401
			}

Qiang Xue committed
402 403 404
			if ($db->enableProfiling) {
				\Yii::endProfile(__METHOD__ . "($sql)", __CLASS__);
			}
w  
Qiang Xue committed
405

Qiang Xue committed
406
			if (isset($cache)) {
Qiang Xue committed
407
				$cache->set($cacheKey, $result, $db->queryCachingDuration, $db->queryCachingDependency);
Qiang Xue committed
408
				\Yii::trace('Saved query result in cache', __CLASS__);
Qiang Xue committed
409
			}
w  
Qiang Xue committed
410 411

			return $result;
Qiang Xue committed
412
		} catch (\Exception $e) {
Qiang Xue committed
413 414 415 416
			if ($db->enableProfiling) {
				\Yii::endProfile(__METHOD__ . "($sql)", __CLASS__);
			}
			$message = $e->getMessage();
Qiang Xue committed
417 418 419
			\Yii::error("$message\nCommand::$method() failed: {$sql}{$paramLog}", __CLASS__);
			$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
			throw new Exception($message, (int)$e->getCode(), $errorInfo);
w  
Qiang Xue committed
420 421 422
		}
	}
}