You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
425 lines
16 KiB
425 lines
16 KiB
14 years ago
|
<?php
|
||
|
/**
|
||
13 years ago
|
* Command class file.
|
||
14 years ago
|
*
|
||
|
* @link http://www.yiiframework.com/
|
||
14 years ago
|
* @copyright Copyright © 2008-2012 Yii Software LLC
|
||
14 years ago
|
* @license http://www.yiiframework.com/license/
|
||
|
*/
|
||
|
|
||
12 years ago
|
namespace yii\db;
|
||
14 years ago
|
|
||
14 years ago
|
use yii\db\Exception;
|
||
|
|
||
14 years ago
|
/**
|
||
14 years ago
|
* Command represents a SQL statement to be executed against a database.
|
||
14 years ago
|
*
|
||
13 years ago
|
* A command object is usually created by calling [[Connection::createCommand()]].
|
||
13 years ago
|
* The SQL statement it represents can be set via the [[sql]] property.
|
||
14 years ago
|
*
|
||
13 years ago
|
* To execute a non-query SQL (such as INSERT, DELETE, UPDATE), call [[execute()]].
|
||
13 years ago
|
* To execute a SQL statement that returns result data set (such as SELECT),
|
||
13 years ago
|
* use [[queryAll()]], [[queryRow()]], [[queryColumn()]], [[queryScalar()]], or [[query()]].
|
||
13 years ago
|
* For example,
|
||
|
*
|
||
|
* ~~~
|
||
13 years ago
|
* $users = \Yii::$application->db->createCommand('SELECT * FROM tbl_user')->queryAll();
|
||
13 years ago
|
* ~~~
|
||
14 years ago
|
*
|
||
13 years ago
|
* Command supports SQL statement preparation and parameter binding.
|
||
13 years ago
|
* Call [[bindValue()]] to bind a value to a SQL parameter;
|
||
|
* Call [[bindParam()]] to bind a PHP variable to a SQL parameter.
|
||
14 years ago
|
* When binding a parameter, the SQL statement is automatically prepared.
|
||
13 years ago
|
* You may also call [[prepare()]] explicitly to prepare a SQL statement.
|
||
14 years ago
|
*
|
||
13 years ago
|
* @property string $sql the SQL statement to be executed
|
||
|
*
|
||
14 years ago
|
* @author Qiang Xue <qiang.xue@gmail.com>
|
||
14 years ago
|
* @since 2.0
|
||
14 years ago
|
*/
|
||
14 years ago
|
class Command extends \yii\base\Component
|
||
14 years ago
|
{
|
||
|
/**
|
||
13 years ago
|
* @var Connection the DB connection that this command is associated with
|
||
|
*/
|
||
14 years ago
|
public $connection;
|
||
13 years ago
|
/**
|
||
|
* @var \PDOStatement the PDOStatement object that this command contains
|
||
|
*/
|
||
14 years ago
|
public $pdoStatement;
|
||
|
/**
|
||
13 years ago
|
* @var mixed the default fetch mode for this command.
|
||
14 years ago
|
* @see http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php
|
||
|
*/
|
||
|
public $fetchMode = \PDO::FETCH_ASSOC;
|
||
14 years ago
|
/**
|
||
13 years ago
|
* @var string the SQL statement that this command represents
|
||
|
*/
|
||
|
private $_sql;
|
||
|
/**
|
||
13 years ago
|
* @var array the parameter log information (name=>value)
|
||
13 years ago
|
*/
|
||
13 years ago
|
private $_params = array();
|
||
13 years ago
|
|
||
|
/**
|
||
14 years ago
|
* Constructor.
|
||
13 years ago
|
* @param Connection $connection the database connection
|
||
13 years ago
|
* @param string $sql the SQL statement to be executed
|
||
|
* @param array $params the parameters to be bound to the SQL statement
|
||
12 years ago
|
* @param array $config name-value pairs that will be used to initialize the object properties
|
||
14 years ago
|
*/
|
||
12 years ago
|
public function __construct($connection, $sql = null, $params = array(), $config = array())
|
||
14 years ago
|
{
|
||
14 years ago
|
$this->connection = $connection;
|
||
13 years ago
|
$this->_sql = $sql;
|
||
|
$this->bindValues($params);
|
||
12 years ago
|
parent::__construct($config);
|
||
14 years ago
|
}
|
||
|
|
||
|
/**
|
||
13 years ago
|
* Returns the SQL statement for this command.
|
||
14 years ago
|
* @return string the SQL statement to be executed
|
||
|
*/
|
||
13 years ago
|
public function getSql()
|
||
14 years ago
|
{
|
||
14 years ago
|
return $this->_sql;
|
||
14 years ago
|
}
|
||
|
|
||
|
/**
|
||
|
* Specifies the SQL statement to be executed.
|
||
13 years ago
|
* Any previous execution will be terminated or cancelled.
|
||
13 years ago
|
* @param string $value the SQL statement to be set.
|
||
14 years ago
|
* @return Command this command instance
|
||
14 years ago
|
*/
|
||
14 years ago
|
public function setSql($value)
|
||
14 years ago
|
{
|
||
13 years ago
|
$this->_sql = $value;
|
||
13 years ago
|
$this->_params = array();
|
||
14 years ago
|
$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.
|
||
13 years ago
|
* @throws Exception if there is any DB error
|
||
14 years ago
|
*/
|
||
|
public function prepare()
|
||
|
{
|
||
14 years ago
|
if ($this->pdoStatement == null) {
|
||
13 years ago
|
$sql = $this->connection->expandTablePrefix($this->getSql());
|
||
14 years ago
|
try {
|
||
13 years ago
|
$this->pdoStatement = $this->connection->pdo->prepare($sql);
|
||
13 years ago
|
} catch (\Exception $e) {
|
||
13 years ago
|
\Yii::error($e->getMessage() . "\nFailed to prepare SQL: $sql", __CLASS__);
|
||
13 years ago
|
$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
|
||
13 years ago
|
throw new Exception($e->getMessage(), (int)$e->getCode(), $errorInfo);
|
||
14 years ago
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Cancels the execution of the SQL statement.
|
||
13 years ago
|
* This method mainly sets [[pdoStatement]] to be null.
|
||
14 years ago
|
*/
|
||
|
public function cancel()
|
||
|
{
|
||
14 years ago
|
$this->pdoStatement = null;
|
||
14 years ago
|
}
|
||
|
|
||
|
/**
|
||
|
* Binds a parameter to the SQL statement to be executed.
|
||
13 years ago
|
* @param string|integer $name parameter identifier. For a prepared statement
|
||
14 years ago
|
* using named placeholders, this will be a parameter name of
|
||
13 years ago
|
* the form `:name`. For a prepared statement using question mark
|
||
14 years ago
|
* 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
|
||
13 years ago
|
* @param mixed $driverOptions the driver-specific options
|
||
|
* @return Command the current command being executed
|
||
14 years ago
|
* @see http://www.php.net/manual/en/function.PDOStatement-bindParam.php
|
||
|
*/
|
||
|
public function bindParam($name, &$value, $dataType = null, $length = null, $driverOptions = null)
|
||
|
{
|
||
|
$this->prepare();
|
||
13 years ago
|
if ($dataType === null) {
|
||
14 years ago
|
$this->pdoStatement->bindParam($name, $value, $this->connection->getPdoType(gettype($value)));
|
||
13 years ago
|
} elseif ($length === null) {
|
||
14 years ago
|
$this->pdoStatement->bindParam($name, $value, $dataType);
|
||
13 years ago
|
} elseif ($driverOptions === null) {
|
||
14 years ago
|
$this->pdoStatement->bindParam($name, $value, $dataType, $length);
|
||
13 years ago
|
} else {
|
||
14 years ago
|
$this->pdoStatement->bindParam($name, $value, $dataType, $length, $driverOptions);
|
||
13 years ago
|
}
|
||
13 years ago
|
$this->_params[$name] =& $value;
|
||
14 years ago
|
return $this;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Binds a value to a parameter.
|
||
13 years ago
|
* @param string|integer $name Parameter identifier. For a prepared statement
|
||
14 years ago
|
* using named placeholders, this will be a parameter name of
|
||
13 years ago
|
* the form `:name`. For a prepared statement using question mark
|
||
14 years ago
|
* 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.
|
||
13 years ago
|
* @return Command the current command being executed
|
||
14 years ago
|
* @see http://www.php.net/manual/en/function.PDOStatement-bindValue.php
|
||
|
*/
|
||
|
public function bindValue($name, $value, $dataType = null)
|
||
|
{
|
||
|
$this->prepare();
|
||
13 years ago
|
if ($dataType === null) {
|
||
14 years ago
|
$this->pdoStatement->bindValue($name, $value, $this->connection->getPdoType(gettype($value)));
|
||
13 years ago
|
} else {
|
||
14 years ago
|
$this->pdoStatement->bindValue($name, $value, $dataType);
|
||
13 years ago
|
}
|
||
13 years ago
|
$this->_params[$name] = $value;
|
||
14 years ago
|
return $this;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Binds a list of values to the corresponding parameters.
|
||
13 years ago
|
* This is similar to [[bindValue()]] except that it binds multiple values at a time.
|
||
14 years ago
|
* 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
|
||
13 years ago
|
* array with array keys being the parameter names, and array values the corresponding parameter values,
|
||
13 years ago
|
* 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))`.
|
||
14 years ago
|
* @return Command the current command being executed
|
||
14 years ago
|
*/
|
||
|
public function bindValues($values)
|
||
|
{
|
||
13 years ago
|
if (!empty($values)) {
|
||
13 years ago
|
$this->prepare();
|
||
|
foreach ($values as $name => $value) {
|
||
13 years ago
|
if (is_array($value)) {
|
||
|
$type = $value[1];
|
||
|
$value = $value[0];
|
||
|
} else {
|
||
|
$type = $this->connection->getPdoType(gettype($value));
|
||
|
}
|
||
|
$this->pdoStatement->bindValue($name, $value, $type);
|
||
13 years ago
|
$this->_params[$name] = $value;
|
||
|
}
|
||
|
}
|
||
14 years ago
|
return $this;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Executes the SQL statement.
|
||
13 years ago
|
* This method should only be used for executing non-query SQL statement, such as `INSERT`, `DELETE`, `UPDATE` SQLs.
|
||
14 years ago
|
* No result set will be returned.
|
||
|
* @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
|
||
13 years ago
|
* to [[bindValues()]]. Note that if you pass parameters in this way, any previous call to [[bindParam()]]
|
||
|
* or [[bindValue()]] will be ignored.
|
||
14 years ago
|
* @return integer number of rows affected by the execution.
|
||
13 years ago
|
* @throws Exception execution failed
|
||
14 years ago
|
*/
|
||
|
public function execute($params = array())
|
||
|
{
|
||
13 years ago
|
$sql = $this->connection->expandTablePrefix($this->getSql());
|
||
13 years ago
|
$this->_params = array_merge($this->_params, $params);
|
||
|
if ($this->_params === array()) {
|
||
|
$paramLog = '';
|
||
13 years ago
|
} else {
|
||
13 years ago
|
$paramLog = "\nParameters: " . var_export($this->_params, true);
|
||
14 years ago
|
}
|
||
13 years ago
|
|
||
|
\Yii::trace("Executing SQL: {$sql}{$paramLog}", __CLASS__);
|
||
13 years ago
|
|
||
13 years ago
|
try {
|
||
|
if ($this->connection->enableProfiling) {
|
||
|
\Yii::beginProfile(__METHOD__ . "($sql)", __CLASS__);
|
||
|
}
|
||
14 years ago
|
|
||
|
$this->prepare();
|
||
13 years ago
|
if ($params === array()) {
|
||
14 years ago
|
$this->pdoStatement->execute();
|
||
13 years ago
|
} else {
|
||
14 years ago
|
$this->pdoStatement->execute($params);
|
||
13 years ago
|
}
|
||
14 years ago
|
$n = $this->pdoStatement->rowCount();
|
||
14 years ago
|
|
||
13 years ago
|
if ($this->connection->enableProfiling) {
|
||
|
\Yii::endProfile(__METHOD__ . "($sql)", __CLASS__);
|
||
|
}
|
||
14 years ago
|
return $n;
|
||
13 years ago
|
} catch (\Exception $e) {
|
||
13 years ago
|
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);
|
||
14 years ago
|
}
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Executes the SQL statement and returns query result.
|
||
13 years ago
|
* This method is for executing a SQL query that returns result set, such as `SELECT`.
|
||
14 years ago
|
* @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
|
||
13 years ago
|
* to [[bindValues()]]. Note that if you pass parameters in this way, any previous call to [[bindParam()]]
|
||
|
* or [[bindValue()]] will be ignored.
|
||
13 years ago
|
* @return DataReader the reader object for fetching the query result
|
||
|
* @throws Exception execution failed
|
||
14 years ago
|
*/
|
||
|
public function query($params = array())
|
||
|
{
|
||
14 years ago
|
return $this->queryInternal('', $params);
|
||
14 years ago
|
}
|
||
|
|
||
|
/**
|
||
13 years ago
|
* Executes the SQL statement and returns ALL rows at once.
|
||
13 years ago
|
* @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
|
||
13 years ago
|
* to [[bindValues()]]. Note that if you pass parameters in this way, any previous call to [[bindParam()]]
|
||
|
* or [[bindValue()]] will be ignored.
|
||
13 years ago
|
* @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.
|
||
14 years ago
|
* An empty array is returned if the query results in nothing.
|
||
13 years ago
|
* @throws Exception execution failed
|
||
14 years ago
|
*/
|
||
14 years ago
|
public function queryAll($params = array(), $fetchMode = null)
|
||
14 years ago
|
{
|
||
14 years ago
|
return $this->queryInternal('fetchAll', $params, $fetchMode);
|
||
14 years ago
|
}
|
||
|
|
||
|
/**
|
||
|
* Executes the SQL statement and returns the first row of the result.
|
||
13 years ago
|
* This method is best used when only the first row of result is needed for a query.
|
||
13 years ago
|
* @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
|
||
13 years ago
|
* to [[bindValues()]]. Note that if you pass parameters in this way, any previous call to [[bindParam()]]
|
||
|
* or [[bindValue()]] will be ignored.
|
||
13 years ago
|
* @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.
|
||
13 years ago
|
* @throws Exception execution failed
|
||
14 years ago
|
*/
|
||
14 years ago
|
public function queryRow($params = array(), $fetchMode = null)
|
||
14 years ago
|
{
|
||
14 years ago
|
return $this->queryInternal('fetch', $params, $fetchMode);
|
||
14 years ago
|
}
|
||
|
|
||
|
/**
|
||
|
* Executes the SQL statement and returns the value of the first column in the first row of data.
|
||
13 years ago
|
* This method is best used when only a single value is needed for a query.
|
||
14 years ago
|
* @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
|
||
13 years ago
|
* 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.
|
||
13 years ago
|
* False is returned if there is no value.
|
||
13 years ago
|
* @throws Exception execution failed
|
||
14 years ago
|
*/
|
||
|
public function queryScalar($params = array())
|
||
|
{
|
||
13 years ago
|
$result = $this->queryInternal('fetchColumn', $params, 0);
|
||
14 years ago
|
if (is_resource($result) && get_resource_type($result) === 'stream') {
|
||
14 years ago
|
return stream_get_contents($result);
|
||
13 years ago
|
} else {
|
||
14 years ago
|
return $result;
|
||
14 years ago
|
}
|
||
14 years ago
|
}
|
||
|
|
||
|
/**
|
||
|
* Executes the SQL statement and returns the first column of the result.
|
||
13 years ago
|
* 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.
|
||
14 years ago
|
* @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
|
||
13 years ago
|
* to [[bindValues()]]. Note that if you pass parameters in this way, any previous call to [[bindParam()]]
|
||
|
* or [[bindValue()]] will be ignored.
|
||
13 years ago
|
* @return array the first column of the query result. Empty array is returned if the query results in nothing.
|
||
13 years ago
|
* @throws Exception execution failed
|
||
14 years ago
|
*/
|
||
|
public function queryColumn($params = array())
|
||
|
{
|
||
14 years ago
|
return $this->queryInternal('fetchAll', $params, \PDO::FETCH_COLUMN);
|
||
14 years ago
|
}
|
||
|
|
||
|
/**
|
||
13 years ago
|
* Performs the actual DB query of a SQL statement.
|
||
14 years ago
|
* @param string $method method of PDOStatement to be called
|
||
|
* @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
|
||
13 years ago
|
* to [[bindValues()]]. Note that if you pass parameters in this way, any previous call to [[bindParam()]]
|
||
|
* or [[bindValue()]] will be ignored.
|
||
13 years ago
|
* @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.
|
||
14 years ago
|
* @return mixed the method execution result
|
||
|
*/
|
||
14 years ago
|
private function queryInternal($method, $params, $fetchMode = null)
|
||
14 years ago
|
{
|
||
13 years ago
|
$db = $this->connection;
|
||
13 years ago
|
$sql = $db->expandTablePrefix($this->getSql());
|
||
13 years ago
|
$this->_params = array_merge($this->_params, $params);
|
||
|
if ($this->_params === array()) {
|
||
|
$paramLog = '';
|
||
13 years ago
|
} else {
|
||
13 years ago
|
$paramLog = "\nParameters: " . var_export($this->_params, true);
|
||
14 years ago
|
}
|
||
13 years ago
|
|
||
|
\Yii::trace("Querying SQL: {$sql}{$paramLog}", __CLASS__);
|
||
12 years ago
|
echo $sql."\n\n";
|
||
13 years ago
|
if ($db->queryCachingCount > 0 && $db->queryCachingDuration >= 0 && $method !== '') {
|
||
13 years ago
|
$cache = \Yii::$application->getComponent($db->queryCacheID);
|
||
13 years ago
|
}
|
||
|
|
||
|
if (isset($cache)) {
|
||
13 years ago
|
$db->queryCachingCount--;
|
||
13 years ago
|
$cacheKey = __CLASS__ . "/{$db->dsn}/{$db->username}/$sql/$paramLog";
|
||
13 years ago
|
if (($result = $cache->get($cacheKey)) !== false) {
|
||
13 years ago
|
\Yii::trace('Query result found in cache', __CLASS__);
|
||
14 years ago
|
return $result;
|
||
|
}
|
||
|
}
|
||
|
|
||
13 years ago
|
try {
|
||
|
if ($db->enableProfiling) {
|
||
|
\Yii::beginProfile(__METHOD__ . "($sql)", __CLASS__);
|
||
|
}
|
||
14 years ago
|
|
||
|
$this->prepare();
|
||
13 years ago
|
if ($params === array()) {
|
||
14 years ago
|
$this->pdoStatement->execute();
|
||
13 years ago
|
} else {
|
||
14 years ago
|
$this->pdoStatement->execute($params);
|
||
13 years ago
|
}
|
||
14 years ago
|
|
||
13 years ago
|
if ($method === '') {
|
||
14 years ago
|
$result = new DataReader($this);
|
||
13 years ago
|
} else {
|
||
13 years ago
|
if ($fetchMode === null) {
|
||
|
$fetchMode = $this->fetchMode;
|
||
|
}
|
||
14 years ago
|
$result = call_user_func_array(array($this->pdoStatement, $method), (array)$fetchMode);
|
||
|
$this->pdoStatement->closeCursor();
|
||
14 years ago
|
}
|
||
|
|
||
13 years ago
|
if ($db->enableProfiling) {
|
||
|
\Yii::endProfile(__METHOD__ . "($sql)", __CLASS__);
|
||
|
}
|
||
14 years ago
|
|
||
13 years ago
|
if (isset($cache)) {
|
||
13 years ago
|
$cache->set($cacheKey, $result, $db->queryCachingDuration, $db->queryCachingDependency);
|
||
13 years ago
|
\Yii::trace('Saved query result in cache', __CLASS__);
|
||
13 years ago
|
}
|
||
14 years ago
|
|
||
|
return $result;
|
||
13 years ago
|
} catch (\Exception $e) {
|
||
13 years ago
|
if ($db->enableProfiling) {
|
||
|
\Yii::endProfile(__METHOD__ . "($sql)", __CLASS__);
|
||
|
}
|
||
|
$message = $e->getMessage();
|
||
13 years ago
|
\Yii::error("$message\nCommand::$method() failed: {$sql}{$paramLog}", __CLASS__);
|
||
|
$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
|
||
|
throw new Exception($message, (int)$e->getCode(), $errorInfo);
|
||
14 years ago
|
}
|
||
|
}
|
||
|
}
|