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

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

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

w  
Qiang Xue committed
15
/**
w  
Qiang Xue committed
16
 * Command represents a SQL statement to be executed against a database.
w  
Qiang Xue committed
17
 *
Qiang Xue committed
18
 * A command object is usually created by calling [[Connection::createCommand()]].
Qiang Xue committed
19
 * The SQL statement it represents can be set via the [[sql]] property.
w  
Qiang Xue committed
20
 *
Qiang Xue committed
21
 * To execute a non-query SQL (such as INSERT, DELETE, UPDATE), call [[execute()]].
Qiang Xue committed
22
 * To execute a SQL statement that returns result data set (such as SELECT),
Qiang Xue committed
23
 * use [[queryAll()]], [[queryRow()]], [[queryColumn()]], [[queryScalar()]], or [[query()]].
Qiang Xue committed
24 25 26
 * For example,
 *
 * ~~~
Qiang Xue committed
27
 * $users = \Yii::$application->db->createCommand('SELECT * FROM tbl_user')->queryAll();
Qiang Xue committed
28
 * ~~~
w  
Qiang Xue committed
29
 *
Qiang Xue committed
30
 * Command supports SQL statement preparation and parameter binding.
Qiang Xue committed
31 32
 * 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
33
 * When binding a parameter, the SQL statement is automatically prepared.
Qiang Xue committed
34
 * You may also call [[prepare()]] explicitly to prepare a SQL statement.
w  
Qiang Xue committed
35
 *
Qiang Xue committed
36 37
 * @property string $sql the SQL statement to be executed
 *
w  
Qiang Xue committed
38
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
39
 * @since 2.0
w  
Qiang Xue committed
40
 */
w  
Qiang Xue committed
41
class Command extends \yii\base\Component
w  
Qiang Xue committed
42
{
Qiang Xue committed
43 44 45
	/**
	 * @var Connection the DB connection that this command is associated with
	 */
w  
Qiang Xue committed
46
	public $connection;
Qiang Xue committed
47 48 49
	/**
	 * @var \PDOStatement the PDOStatement object that this command contains
	 */
w  
Qiang Xue committed
50 51
	public $pdoStatement;
	/**
Qiang Xue committed
52
	 * @var mixed the default fetch mode for this command.
w  
Qiang Xue committed
53 54 55
	 * @see http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php
	 */
	public $fetchMode = \PDO::FETCH_ASSOC;
Qiang Xue committed
56 57 58 59 60
	/**
	 * @var string the SQL statement that this command represents
	 */
	private $_sql;
	/**
Qiang Xue committed
61
	 * @var array the parameter log information (name=>value)
Qiang Xue committed
62
	 */
Qiang Xue committed
63
	private $_params = array();
Qiang Xue committed
64

w  
Qiang Xue committed
65 66
	/**
	 * Constructor.
Qiang Xue committed
67
	 * @param Connection $connection the database connection
Qiang Xue committed
68 69
	 * @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
70
	 */
Qiang Xue committed
71
	public function __construct($connection, $sql = null, $params = array())
w  
Qiang Xue committed
72
	{
w  
Qiang Xue committed
73
		$this->connection = $connection;
Qiang Xue committed
74 75
		$this->_sql = $sql;
		$this->bindValues($params);
w  
Qiang Xue committed
76 77 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.
Qiang Xue committed
89
	 * Any previous execution will be terminated or cancelled.
Qiang Xue committed
90
	 * @param string $value the SQL statement to be set.
w  
Qiang Xue committed
91
	 * @return Command this command instance
w  
Qiang Xue committed
92
	 */
w  
Qiang Xue committed
93
	public function setSql($value)
w  
Qiang Xue committed
94
	{
Qiang Xue committed
95
		$this->_sql = $value;
Qiang Xue committed
96
		$this->_params = array();
w  
Qiang Xue committed
97 98 99 100 101 102 103 104 105 106 107 108 109
		$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.
	 */
	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 189
	 * array with array keys being the parameter names, and array values the corresponding parameter values,
	 * e.g. `array(':name'=>'John', ':age'=>25)`.
w  
Qiang Xue committed
190
	 * @return Command the current command being executed
w  
Qiang Xue committed
191 192 193
	 */
	public function bindValues($values)
	{
Qiang Xue committed
194
		if (!empty($values)) {
Qiang Xue committed
195 196 197 198 199 200
			$this->prepare();
			foreach ($values as $name => $value) {
				$this->pdoStatement->bindValue($name, $value, $this->connection->getPdoType(gettype($value)));
				$this->_params[$name] = $value;
			}
		}
w  
Qiang Xue committed
201 202 203 204 205
		return $this;
	}

	/**
	 * Executes the SQL statement.
Qiang Xue committed
206
	 * This method should only be used for executing non-query SQL statement, such as `INSERT`, `DELETE`, `UPDATE` SQLs.
w  
Qiang Xue committed
207 208
	 * No result set will be returned.
	 * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
Qiang Xue committed
209 210
	 * 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
211
	 * @return integer number of rows affected by the execution.
Qiang Xue committed
212
	 * @throws Exception execution failed
w  
Qiang Xue committed
213 214 215
	 */
	public function execute($params = array())
	{
Qiang Xue committed
216
		$sql = $this->connection->expandTablePrefix($this->getSql());
Qiang Xue committed
217 218 219
		$this->_params = array_merge($this->_params, $params);
		if ($this->_params === array()) {
			$paramLog = '';
Qiang Xue committed
220
		} else {
Qiang Xue committed
221
			$paramLog = "\nParameters: " . var_export($this->_params, true);
w  
Qiang Xue committed
222
		}
Qiang Xue committed
223 224

		\Yii::trace("Executing SQL: {$sql}{$paramLog}", __CLASS__);
Qiang Xue committed
225
echo $sql . "\n\n";
Qiang Xue committed
226 227 228 229
		try {
			if ($this->connection->enableProfiling) {
				\Yii::beginProfile(__METHOD__ . "($sql)", __CLASS__);
			}
w  
Qiang Xue committed
230 231

			$this->prepare();
Qiang Xue committed
232
			if ($params === array()) {
w  
Qiang Xue committed
233
				$this->pdoStatement->execute();
Qiang Xue committed
234
			} else {
w  
Qiang Xue committed
235
				$this->pdoStatement->execute($params);
Qiang Xue committed
236
			}
w  
Qiang Xue committed
237
			$n = $this->pdoStatement->rowCount();
w  
Qiang Xue committed
238

Qiang Xue committed
239 240 241
			if ($this->connection->enableProfiling) {
				\Yii::endProfile(__METHOD__ . "($sql)", __CLASS__);
			}
w  
Qiang Xue committed
242
			return $n;
Qiang Xue committed
243
		} catch (\Exception $e) {
Qiang Xue committed
244 245 246 247 248 249 250
			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
251 252 253 254 255
		}
	}

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

	/**
Qiang Xue committed
269
	 * Executes the SQL statement and returns ALL rows at once.
Qiang Xue committed
270
	 * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
Qiang Xue committed
271 272
	 * to [[bindValues()]]. Note that if you pass parameters in this way, any previous call to [[bindParam()]]
	 * or [[bindValue()]] will be ignored.
Qiang Xue committed
273 274 275
	 * @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
276
	 * An empty array is returned if the query results in nothing.
Qiang Xue committed
277
	 * @throws Exception execution failed
w  
Qiang Xue committed
278
	 */
w  
Qiang Xue committed
279
	public function queryAll($params = array(), $fetchMode = null)
w  
Qiang Xue committed
280
	{
w  
Qiang Xue committed
281
		return $this->queryInternal('fetchAll', $params, $fetchMode);
w  
Qiang Xue committed
282 283 284 285
	}

	/**
	 * Executes the SQL statement and returns the first row of the result.
Qiang Xue committed
286
	 * This method is best used when only the first row of result is needed for a query.
Qiang Xue committed
287
	 * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
Qiang Xue committed
288 289
	 * to [[bindValues()]]. Note that if you pass parameters in this way, any previous call to [[bindParam()]]
	 * or [[bindValue()]] will be ignored.
Qiang Xue committed
290 291 292 293
	 * @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
294
	 * @throws Exception execution failed
w  
Qiang Xue committed
295
	 */
w  
Qiang Xue committed
296
	public function queryRow($params = array(), $fetchMode = null)
w  
Qiang Xue committed
297
	{
w  
Qiang Xue committed
298
		return $this->queryInternal('fetch', $params, $fetchMode);
w  
Qiang Xue committed
299 300 301 302
	}

	/**
	 * Executes the SQL statement and returns the value of the first column in the first row of data.
Qiang Xue committed
303
	 * This method is best used when only a single value is needed for a query.
w  
Qiang Xue committed
304
	 * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
Qiang Xue committed
305 306 307
	 * 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
308
	 * False is returned if there is no value.
Qiang Xue committed
309
	 * @throws Exception execution failed
w  
Qiang Xue committed
310 311 312
	 */
	public function queryScalar($params = array())
	{
Qiang Xue committed
313
		$result = $this->queryInternal('fetchColumn', $params, 0);
w  
Qiang Xue committed
314
		if (is_resource($result) && get_resource_type($result) === 'stream') {
w  
Qiang Xue committed
315
			return stream_get_contents($result);
Qiang Xue committed
316
		} else {
w  
Qiang Xue committed
317
			return $result;
w  
Qiang Xue committed
318
		}
w  
Qiang Xue committed
319 320 321 322
	}

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

	/**
Qiang Xue committed
337
	 * Performs the actual DB query of a SQL statement.
w  
Qiang Xue committed
338 339
	 * @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
340 341
	 * to [[bindValues()]]. Note that if you pass parameters in this way, any previous call to [[bindParam()]]
	 * or [[bindValue()]] will be ignored.
Qiang Xue committed
342 343
	 * @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
344 345
	 * @return mixed the method execution result
	 */
w  
Qiang Xue committed
346
	private function queryInternal($method, $params, $fetchMode = null)
w  
Qiang Xue committed
347
	{
Qiang Xue committed
348
		$db = $this->connection;
Qiang Xue committed
349
		$sql = $db->expandTablePrefix($this->getSql());
Qiang Xue committed
350 351 352
		$this->_params = array_merge($this->_params, $params);
		if ($this->_params === array()) {
			$paramLog = '';
Qiang Xue committed
353
		} else {
Qiang Xue committed
354
			$paramLog = "\nParameters: " . var_export($this->_params, true);
w  
Qiang Xue committed
355
		}
Qiang Xue committed
356 357

		\Yii::trace("Querying SQL: {$sql}{$paramLog}", __CLASS__);
Qiang Xue committed
358
echo $sql . "\n\n";
Qiang Xue committed
359
		if ($db->queryCachingCount > 0 && $db->queryCachingDuration >= 0 && $method !== '') {
Qiang Xue committed
360
			$cache = \Yii::$application->getComponent($db->queryCacheID);
Qiang Xue committed
361 362 363
		}

		if (isset($cache)) {
Qiang Xue committed
364
			$db->queryCachingCount--;
Qiang Xue committed
365
			$cacheKey = __CLASS__ . "/{$db->dsn}/{$db->username}/$sql/$paramLog";
Qiang Xue committed
366
			if (($result = $cache->get($cacheKey)) !== false) {
Qiang Xue committed
367
				\Yii::trace('Query result found in cache', __CLASS__);
w  
Qiang Xue committed
368 369 370 371
				return $result;
			}
		}

Qiang Xue committed
372 373 374 375
		try {
			if ($db->enableProfiling) {
				\Yii::beginProfile(__METHOD__ . "($sql)", __CLASS__);
			}
w  
Qiang Xue committed
376 377

			$this->prepare();
Qiang Xue committed
378
			if ($params === array()) {
w  
Qiang Xue committed
379
				$this->pdoStatement->execute();
Qiang Xue committed
380
			} else {
w  
Qiang Xue committed
381
				$this->pdoStatement->execute($params);
Qiang Xue committed
382
			}
w  
Qiang Xue committed
383

Qiang Xue committed
384
			if ($method === '') {
w  
Qiang Xue committed
385
				$result = new DataReader($this);
Qiang Xue committed
386
			} else {
Qiang Xue committed
387 388 389
				if ($fetchMode === null) {
					$fetchMode = $this->fetchMode;
				}
w  
Qiang Xue committed
390 391
				$result = call_user_func_array(array($this->pdoStatement, $method), (array)$fetchMode);
				$this->pdoStatement->closeCursor();
w  
Qiang Xue committed
392 393
			}

Qiang Xue committed
394 395 396
			if ($db->enableProfiling) {
				\Yii::endProfile(__METHOD__ . "($sql)", __CLASS__);
			}
w  
Qiang Xue committed
397

Qiang Xue committed
398
			if (isset($cache)) {
Qiang Xue committed
399
				$cache->set($cacheKey, $result, $db->queryCachingDuration, $db->queryCachingDependency);
Qiang Xue committed
400
				\Yii::trace('Saved query result in cache', __CLASS__);
Qiang Xue committed
401
			}
w  
Qiang Xue committed
402 403

			return $result;
Qiang Xue committed
404
		} catch (\Exception $e) {
Qiang Xue committed
405 406 407 408
			if ($db->enableProfiling) {
				\Yii::endProfile(__METHOD__ . "($sql)", __CLASS__);
			}
			$message = $e->getMessage();
Qiang Xue committed
409 410 411
			\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
412 413 414
		}
	}
}