Commit 8f15fd41 by Qiang Xue

w

parent 760fdf98
<?php <?php
/** /**
* This file contains the CDbCommand class. * This file contains the Command class.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2011 Yii Software LLC * @copyright Copyright &copy; 2008-2012 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
/** /**
* CDbCommand represents an SQL statement to execute against a database. * Command represents a SQL statement to be executed against a database.
* *
* It is usually created by calling {@link CDbConnection::createCommand}. * A command object is usually created by calling [[Connection::createCommand]].
* The SQL statement to be executed may be set via {@link setText Text}. * The SQL statement it represents can be set via the [[text]] property.
* *
* To execute a non-query SQL (such as insert, delete, update), call * To execute a non-query SQL (such as insert, delete, update), call [[execute]].
* {@link execute}. To execute an SQL statement that returns result data set * To execute an SQL statement that returns result data set (such as SELECT),
* (such as SELECT), use {@link query} or its convenient versions {@link queryRow}, * use [[query]], [[queryRow]], [[queryColumn]], or [[queryScalar]].
* {@link queryColumn}, or {@link queryScalar}.
* *
* If an SQL statement returns results (such as a SELECT SQL), the results * If an SQL statement returns results (such as a SELECT SQL), the results
* can be accessed via the returned {@link CDbDataReader}. * can be accessed via the returned {@link CDbDataReader}.
* *
* CDbCommand supports SQL statment preparation and parameter binding. * Command supports SQL statment preparation and parameter binding.
* Call {@link bindParam} to bind a PHP variable to a parameter in SQL. * Call {@link bindParam} to bind a PHP variable to a parameter in SQL.
* Call {@link bindValue} to bind a value to an SQL parameter. * Call {@link bindValue} to bind a value to an SQL parameter.
* When binding a parameter, the SQL statement is automatically prepared. * When binding a parameter, the SQL statement is automatically prepared.
* You may also call {@link prepare} to explicitly prepare an SQL statement. * You may also call {@link prepare} to explicitly prepare an SQL statement.
* *
* Starting from version 1.1.6, CDbCommand can also be used as a query builder * Starting from version 1.1.6, Command can also be used as a query builder
* that builds a SQL statement from code fragments. For example, * that builds a SQL statement from code fragments. For example,
* <pre> * <pre>
* $user = Yii::app()->db->createCommand() * $user = Yii::app()->db->createCommand()
...@@ -39,11 +38,9 @@ ...@@ -39,11 +38,9 @@
* </pre> * </pre>
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @version $Id: CDbCommand.php 3240 2011-05-25 19:22:47Z qiang.xue $ * @since 2.0
* @package system.db
* @since 1.0
*/ */
class CDbCommand extends CComponent class Command extends CComponent
{ {
/** /**
* @var array the parameters (name=>value) to be bound to the current query. * @var array the parameters (name=>value) to be bound to the current query.
...@@ -104,7 +101,7 @@ class CDbCommand extends CComponent ...@@ -104,7 +101,7 @@ class CDbCommand extends CComponent
/** /**
* Set the default fetch mode for this statement * Set the default fetch mode for this statement
* @param mixed $mode fetch mode * @param mixed $mode fetch mode
* @return CDbCommand * @return Command
* @see http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php * @see http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php
* @since 1.1.7 * @since 1.1.7
*/ */
...@@ -120,7 +117,7 @@ class CDbCommand extends CComponent ...@@ -120,7 +117,7 @@ class CDbCommand extends CComponent
* This method is mainly used when a command object is being reused * This method is mainly used when a command object is being reused
* multiple times for building different queries. * multiple times for building different queries.
* Calling this method will clean up all internal states of the command object. * Calling this method will clean up all internal states of the command object.
* @return CDbCommand this command instance * @return Command this command instance
* @since 1.1.6 * @since 1.1.6
*/ */
public function reset() public function reset()
...@@ -147,7 +144,7 @@ class CDbCommand extends CComponent ...@@ -147,7 +144,7 @@ class CDbCommand extends CComponent
* Specifies the SQL statement to be executed. * Specifies the SQL statement to be executed.
* Any previous execution will be terminated or cancel. * Any previous execution will be terminated or cancel.
* @param string $value the SQL statement to be executed * @param string $value the SQL statement to be executed
* @return CDbCommand this command instance * @return Command this command instance
*/ */
public function setText($value) public function setText($value)
{ {
...@@ -194,9 +191,9 @@ class CDbCommand extends CComponent ...@@ -194,9 +191,9 @@ class CDbCommand extends CComponent
} }
catch(Exception $e) catch(Exception $e)
{ {
Yii::log('Error in preparing SQL: ' . $this->getText(), CLogger::LEVEL_ERROR, 'system.db.CDbCommand'); Yii::log('Error in preparing SQL: ' . $this->getText(), CLogger::LEVEL_ERROR, 'system.db.Command');
$errorInfo = $e instanceof PDOException ? $e->errorInfo : null; $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
throw new CDbException(Yii::t('yii', 'CDbCommand failed to prepare the SQL statement: {error}', throw new CDbException(Yii::t('yii', 'Command failed to prepare the SQL statement: {error}',
array('{error}' => $e->getMessage())), (int)$e->getCode(), $errorInfo); array('{error}' => $e->getMessage())), (int)$e->getCode(), $errorInfo);
} }
} }
...@@ -220,7 +217,7 @@ class CDbCommand extends CComponent ...@@ -220,7 +217,7 @@ class CDbCommand extends CComponent
* @param integer $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value. * @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 * @param integer $length length of the data type
* @param mixed $driverOptions the driver-specific options (this is available since version 1.1.6) * @param mixed $driverOptions the driver-specific options (this is available since version 1.1.6)
* @return CDbCommand the current command being executed (this is available since version 1.0.8) * @return Command the current command being executed (this is available since version 1.0.8)
* @see http://www.php.net/manual/en/function.PDOStatement-bindParam.php * @see http://www.php.net/manual/en/function.PDOStatement-bindParam.php
*/ */
public function bindParam($name, &$value, $dataType = null, $length = null, $driverOptions = null) public function bindParam($name, &$value, $dataType = null, $length = null, $driverOptions = null)
...@@ -246,7 +243,7 @@ class CDbCommand extends CComponent ...@@ -246,7 +243,7 @@ class CDbCommand extends CComponent
* placeholders, this will be the 1-indexed position of the parameter. * placeholders, this will be the 1-indexed position of the parameter.
* @param mixed $value The value to bind to 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. * @param integer $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
* @return CDbCommand the current command being executed (this is available since version 1.0.8) * @return Command the current command being executed (this is available since version 1.0.8)
* @see http://www.php.net/manual/en/function.PDOStatement-bindValue.php * @see http://www.php.net/manual/en/function.PDOStatement-bindValue.php
*/ */
public function bindValue($name, $value, $dataType = null) public function bindValue($name, $value, $dataType = null)
...@@ -267,7 +264,7 @@ class CDbCommand extends CComponent ...@@ -267,7 +264,7 @@ class CDbCommand extends CComponent
* @param array $values the values to be bound. This must be given in terms of an associative * @param array $values the values to be bound. This must be given in terms of an associative
* array with array keys being the parameter names, and array values the corresponding parameter values. * array with array keys being the parameter names, and array values the corresponding parameter values.
* For example, <code>array(':name'=>'John', ':age'=>25)</code>. * For example, <code>array(':name'=>'John', ':age'=>25)</code>.
* @return CDbCommand the current command being executed * @return Command the current command being executed
* @since 1.1.5 * @since 1.1.5
*/ */
public function bindValues($values) public function bindValues($values)
...@@ -305,11 +302,11 @@ class CDbCommand extends CComponent ...@@ -305,11 +302,11 @@ class CDbCommand extends CComponent
} }
else else
$par = ''; $par = '';
Yii::trace('Executing SQL: ' . $this->getText() . $par, 'system.db.CDbCommand'); Yii::trace('Executing SQL: ' . $this->getText() . $par, 'system.db.Command');
try try
{ {
if ($this->_connection->enableProfiling) if ($this->_connection->enableProfiling)
Yii::beginProfile('system.db.CDbCommand.execute(' . $this->getText() . ')', 'system.db.CDbCommand.execute'); Yii::beginProfile('system.db.Command.execute(' . $this->getText() . ')', 'system.db.Command.execute');
$this->prepare(); $this->prepare();
if ($params === array()) if ($params === array())
...@@ -319,21 +316,21 @@ class CDbCommand extends CComponent ...@@ -319,21 +316,21 @@ class CDbCommand extends CComponent
$n = $this->_statement->rowCount(); $n = $this->_statement->rowCount();
if ($this->_connection->enableProfiling) if ($this->_connection->enableProfiling)
Yii::endProfile('system.db.CDbCommand.execute(' . $this->getText() . ')', 'system.db.CDbCommand.execute'); Yii::endProfile('system.db.Command.execute(' . $this->getText() . ')', 'system.db.Command.execute');
return $n; return $n;
} }
catch(Exception $e) catch(Exception $e)
{ {
if ($this->_connection->enableProfiling) if ($this->_connection->enableProfiling)
Yii::endProfile('system.db.CDbCommand.execute(' . $this->getText() . ')', 'system.db.CDbCommand.execute'); Yii::endProfile('system.db.Command.execute(' . $this->getText() . ')', 'system.db.Command.execute');
$errorInfo = $e instanceof PDOException ? $e->errorInfo : null; $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
$message = $e->getMessage(); $message = $e->getMessage();
Yii::log(Yii::t('yii', 'CDbCommand::execute() failed: {error}. The SQL statement executed was: {sql}.', Yii::log(Yii::t('yii', 'Command::execute() failed: {error}. The SQL statement executed was: {sql}.',
array('{error}' => $message, '{sql}' => $this->getText() . $par)), CLogger::LEVEL_ERROR, 'system.db.CDbCommand'); array('{error}' => $message, '{sql}' => $this->getText() . $par)), CLogger::LEVEL_ERROR, 'system.db.Command');
if (YII_DEBUG) if (YII_DEBUG)
$message .= '. The SQL statement executed was: ' . $this->getText() . $par; $message .= '. The SQL statement executed was: ' . $this->getText() . $par;
throw new CDbException(Yii::t('yii', 'CDbCommand failed to execute the SQL statement: {error}', throw new CDbException(Yii::t('yii', 'Command failed to execute the SQL statement: {error}',
array('{error}' => $message)), (int)$e->getCode(), $errorInfo); array('{error}' => $message)), (int)$e->getCode(), $errorInfo);
} }
} }
...@@ -458,7 +455,7 @@ class CDbCommand extends CComponent ...@@ -458,7 +455,7 @@ class CDbCommand extends CComponent
else else
$par = ''; $par = '';
Yii::trace('Querying SQL: ' . $this->getText() . $par, 'system.db.CDbCommand'); Yii::trace('Querying SQL: ' . $this->getText() . $par, 'system.db.Command');
if ($this->_connection->queryCachingCount > 0 && $method !== '' if ($this->_connection->queryCachingCount > 0 && $method !== ''
&& $this->_connection->queryCachingDuration > 0 && $this->_connection->queryCachingDuration > 0
...@@ -470,7 +467,7 @@ class CDbCommand extends CComponent ...@@ -470,7 +467,7 @@ class CDbCommand extends CComponent
$cacheKey .= ':' . $this->getText() . ':' . serialize(array_merge($this->_paramLog, $params)); $cacheKey .= ':' . $this->getText() . ':' . serialize(array_merge($this->_paramLog, $params));
if (($result = $cache->get($cacheKey)) !== false) if (($result = $cache->get($cacheKey)) !== false)
{ {
Yii::trace('Query result found in cache', 'system.db.CDbCommand'); Yii::trace('Query result found in cache', 'system.db.Command');
return $result; return $result;
} }
} }
...@@ -478,7 +475,7 @@ class CDbCommand extends CComponent ...@@ -478,7 +475,7 @@ class CDbCommand extends CComponent
try try
{ {
if ($this->_connection->enableProfiling) if ($this->_connection->enableProfiling)
Yii::beginProfile('system.db.CDbCommand.query(' . $this->getText() . $par . ')', 'system.db.CDbCommand.query'); Yii::beginProfile('system.db.Command.query(' . $this->getText() . $par . ')', 'system.db.Command.query');
$this->prepare(); $this->prepare();
if ($params === array()) if ($params === array())
...@@ -496,7 +493,7 @@ class CDbCommand extends CComponent ...@@ -496,7 +493,7 @@ class CDbCommand extends CComponent
} }
if ($this->_connection->enableProfiling) if ($this->_connection->enableProfiling)
Yii::endProfile('system.db.CDbCommand.query(' . $this->getText() . $par . ')', 'system.db.CDbCommand.query'); Yii::endProfile('system.db.Command.query(' . $this->getText() . $par . ')', 'system.db.Command.query');
if (isset($cache, $cacheKey)) if (isset($cache, $cacheKey))
$cache->set($cacheKey, $result, $this->_connection->queryCachingDuration, $this->_connection->queryCachingDependency); $cache->set($cacheKey, $result, $this->_connection->queryCachingDuration, $this->_connection->queryCachingDependency);
...@@ -506,14 +503,14 @@ class CDbCommand extends CComponent ...@@ -506,14 +503,14 @@ class CDbCommand extends CComponent
catch(Exception $e) catch(Exception $e)
{ {
if ($this->_connection->enableProfiling) if ($this->_connection->enableProfiling)
Yii::endProfile('system.db.CDbCommand.query(' . $this->getText() . $par . ')', 'system.db.CDbCommand.query'); Yii::endProfile('system.db.Command.query(' . $this->getText() . $par . ')', 'system.db.Command.query');
$errorInfo = $e instanceof PDOException ? $e->errorInfo : null; $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
$message = $e->getMessage(); $message = $e->getMessage();
Yii::log(Yii::t('yii', 'CDbCommand::{method}() failed: {error}. The SQL statement executed was: {sql}.', Yii::log(Yii::t('yii', 'Command::{method}() failed: {error}. The SQL statement executed was: {sql}.',
array('{method}' => $method, '{error}' => $message, '{sql}' => $this->getText() . $par)), CLogger::LEVEL_ERROR, 'system.db.CDbCommand'); array('{method}' => $method, '{error}' => $message, '{sql}' => $this->getText() . $par)), CLogger::LEVEL_ERROR, 'system.db.Command');
if (YII_DEBUG) if (YII_DEBUG)
$message .= '. The SQL statement executed was: ' . $this->getText() . $par; $message .= '. The SQL statement executed was: ' . $this->getText() . $par;
throw new CDbException(Yii::t('yii', 'CDbCommand failed to execute the SQL statement: {error}', throw new CDbException(Yii::t('yii', 'Command failed to execute the SQL statement: {error}',
array('{error}' => $message)), (int)$e->getCode(), $errorInfo); array('{error}' => $message)), (int)$e->getCode(), $errorInfo);
} }
} }
...@@ -572,7 +569,7 @@ class CDbCommand extends CComponent ...@@ -572,7 +569,7 @@ class CDbCommand extends CComponent
* (which means the column contains a DB expression). * (which means the column contains a DB expression).
* @param string $option additional option that should be appended to the 'SELECT' keyword. For example, * @param string $option additional option that should be appended to the 'SELECT' keyword. For example,
* in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used. This parameter is supported since version 1.1.8. * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used. This parameter is supported since version 1.1.8.
* @return CDbCommand the command object itself * @return Command the command object itself
* @since 1.1.6 * @since 1.1.6
*/ */
public function select($columns = '*', $option = '') public function select($columns = '*', $option = '')
...@@ -628,7 +625,7 @@ class CDbCommand extends CComponent ...@@ -628,7 +625,7 @@ class CDbCommand extends CComponent
* Sets the SELECT part of the query with the DISTINCT flag turned on. * Sets the SELECT part of the query with the DISTINCT flag turned on.
* This is the same as {@link select} except that the DISTINCT flag is turned on. * This is the same as {@link select} except that the DISTINCT flag is turned on.
* @param mixed $columns the columns to be selected. See {@link select} for more details. * @param mixed $columns the columns to be selected. See {@link select} for more details.
* @return CDbCommand the command object itself * @return Command the command object itself
* @since 1.1.6 * @since 1.1.6
*/ */
public function selectDistinct($columns = '*') public function selectDistinct($columns = '*')
...@@ -664,7 +661,7 @@ class CDbCommand extends CComponent ...@@ -664,7 +661,7 @@ class CDbCommand extends CComponent
* Table names can contain schema prefixes (e.g. 'public.tbl_user') and/or table aliases (e.g. 'tbl_user u'). * Table names can contain schema prefixes (e.g. 'public.tbl_user') and/or table aliases (e.g. 'tbl_user u').
* The method will automatically quote the table names unless it contains some parenthesis * The method will automatically quote the table names unless it contains some parenthesis
* (which means the table is given as a sub-query or DB expression). * (which means the table is given as a sub-query or DB expression).
* @return CDbCommand the command object itself * @return Command the command object itself
* @since 1.1.6 * @since 1.1.6
*/ */
public function from($tables) public function from($tables)
...@@ -746,7 +743,7 @@ class CDbCommand extends CComponent ...@@ -746,7 +743,7 @@ class CDbCommand extends CComponent
* </ul> * </ul>
* @param mixed $conditions the conditions that should be put in the WHERE part. * @param mixed $conditions the conditions that should be put in the WHERE part.
* @param array $params the parameters (name=>value) to be bound to the query * @param array $params the parameters (name=>value) to be bound to the query
* @return CDbCommand the command object itself * @return Command the command object itself
* @since 1.1.6 * @since 1.1.6
*/ */
public function where($conditions, $params = array()) public function where($conditions, $params = array())
...@@ -787,7 +784,7 @@ class CDbCommand extends CComponent ...@@ -787,7 +784,7 @@ class CDbCommand extends CComponent
* @param mixed $conditions the join condition that should appear in the ON part. * @param mixed $conditions the join condition that should appear in the ON part.
* Please refer to {@link where} on how to specify conditions. * Please refer to {@link where} on how to specify conditions.
* @param array $params the parameters (name=>value) to be bound to the query * @param array $params the parameters (name=>value) to be bound to the query
* @return CDbCommand the command object itself * @return Command the command object itself
* @since 1.1.6 * @since 1.1.6
*/ */
public function join($table, $conditions, $params = array()) public function join($table, $conditions, $params = array())
...@@ -828,7 +825,7 @@ class CDbCommand extends CComponent ...@@ -828,7 +825,7 @@ class CDbCommand extends CComponent
* @param mixed $conditions the join condition that should appear in the ON part. * @param mixed $conditions the join condition that should appear in the ON part.
* Please refer to {@link where} on how to specify conditions. * Please refer to {@link where} on how to specify conditions.
* @param array $params the parameters (name=>value) to be bound to the query * @param array $params the parameters (name=>value) to be bound to the query
* @return CDbCommand the command object itself * @return Command the command object itself
* @since 1.1.6 * @since 1.1.6
*/ */
public function leftJoin($table, $conditions, $params = array()) public function leftJoin($table, $conditions, $params = array())
...@@ -845,7 +842,7 @@ class CDbCommand extends CComponent ...@@ -845,7 +842,7 @@ class CDbCommand extends CComponent
* @param mixed $conditions the join condition that should appear in the ON part. * @param mixed $conditions the join condition that should appear in the ON part.
* Please refer to {@link where} on how to specify conditions. * Please refer to {@link where} on how to specify conditions.
* @param array $params the parameters (name=>value) to be bound to the query * @param array $params the parameters (name=>value) to be bound to the query
* @return CDbCommand the command object itself * @return Command the command object itself
* @since 1.1.6 * @since 1.1.6
*/ */
public function rightJoin($table, $conditions, $params = array()) public function rightJoin($table, $conditions, $params = array())
...@@ -860,7 +857,7 @@ class CDbCommand extends CComponent ...@@ -860,7 +857,7 @@ class CDbCommand extends CComponent
* Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u'). * Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u').
* The method will automatically quote the table name unless it contains some parenthesis * The method will automatically quote the table name unless it contains some parenthesis
* (which means the table is given as a sub-query or DB expression). * (which means the table is given as a sub-query or DB expression).
* @return CDbCommand the command object itself * @return Command the command object itself
* @since 1.1.6 * @since 1.1.6
*/ */
public function crossJoin($table) public function crossJoin($table)
...@@ -875,7 +872,7 @@ class CDbCommand extends CComponent ...@@ -875,7 +872,7 @@ class CDbCommand extends CComponent
* Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u'). * Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u').
* The method will automatically quote the table name unless it contains some parenthesis * The method will automatically quote the table name unless it contains some parenthesis
* (which means the table is given as a sub-query or DB expression). * (which means the table is given as a sub-query or DB expression).
* @return CDbCommand the command object itself * @return Command the command object itself
* @since 1.1.6 * @since 1.1.6
*/ */
public function naturalJoin($table) public function naturalJoin($table)
...@@ -889,7 +886,7 @@ class CDbCommand extends CComponent ...@@ -889,7 +886,7 @@ class CDbCommand extends CComponent
* Columns can be specified in either a string (e.g. "id, name") or an array (e.g. array('id', 'name')). * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. array('id', 'name')).
* The method will automatically quote the column names unless a column contains some parenthesis * The method will automatically quote the column names unless a column contains some parenthesis
* (which means the column contains a DB expression). * (which means the column contains a DB expression).
* @return CDbCommand the command object itself * @return Command the command object itself
* @since 1.1.6 * @since 1.1.6
*/ */
public function group($columns) public function group($columns)
...@@ -938,7 +935,7 @@ class CDbCommand extends CComponent ...@@ -938,7 +935,7 @@ class CDbCommand extends CComponent
* @param mixed $conditions the conditions to be put after HAVING. * @param mixed $conditions the conditions to be put after HAVING.
* Please refer to {@link where} on how to specify conditions. * Please refer to {@link where} on how to specify conditions.
* @param array $params the parameters (name=>value) to be bound to the query * @param array $params the parameters (name=>value) to be bound to the query
* @return CDbCommand the command object itself * @return Command the command object itself
* @since 1.1.6 * @since 1.1.6
*/ */
public function having($conditions, $params = array()) public function having($conditions, $params = array())
...@@ -976,7 +973,7 @@ class CDbCommand extends CComponent ...@@ -976,7 +973,7 @@ class CDbCommand extends CComponent
* Columns can be specified in either a string (e.g. "id ASC, name DESC") or an array (e.g. array('id ASC', 'name DESC')). * Columns can be specified in either a string (e.g. "id ASC, name DESC") or an array (e.g. array('id ASC', 'name DESC')).
* The method will automatically quote the column names unless a column contains some parenthesis * The method will automatically quote the column names unless a column contains some parenthesis
* (which means the column contains a DB expression). * (which means the column contains a DB expression).
* @return CDbCommand the command object itself * @return Command the command object itself
* @since 1.1.6 * @since 1.1.6
*/ */
public function order($columns) public function order($columns)
...@@ -1029,7 +1026,7 @@ class CDbCommand extends CComponent ...@@ -1029,7 +1026,7 @@ class CDbCommand extends CComponent
* Sets the LIMIT part of the query. * Sets the LIMIT part of the query.
* @param integer $limit the limit * @param integer $limit the limit
* @param integer $offset the offset * @param integer $offset the offset
* @return CDbCommand the command object itself * @return Command the command object itself
* @since 1.1.6 * @since 1.1.6
*/ */
public function limit($limit, $offset = null) public function limit($limit, $offset = null)
...@@ -1064,7 +1061,7 @@ class CDbCommand extends CComponent ...@@ -1064,7 +1061,7 @@ class CDbCommand extends CComponent
/** /**
* Sets the OFFSET part of the query. * Sets the OFFSET part of the query.
* @param integer $offset the offset * @param integer $offset the offset
* @return CDbCommand the command object itself * @return Command the command object itself
* @since 1.1.6 * @since 1.1.6
*/ */
public function offset($offset) public function offset($offset)
...@@ -1097,7 +1094,7 @@ class CDbCommand extends CComponent ...@@ -1097,7 +1094,7 @@ class CDbCommand extends CComponent
/** /**
* Appends a SQL statement using UNION operator. * Appends a SQL statement using UNION operator.
* @param string $sql the SQL statement to be appended using UNION * @param string $sql the SQL statement to be appended using UNION
* @return CDbCommand the command object itself * @return Command the command object itself
* @since 1.1.6 * @since 1.1.6
*/ */
public function union($sql) public function union($sql)
...@@ -1470,7 +1467,7 @@ class CDbCommand extends CComponent ...@@ -1470,7 +1467,7 @@ class CDbCommand extends CComponent
* @param mixed $conditions the join condition that should appear in the ON part. * @param mixed $conditions the join condition that should appear in the ON part.
* Please refer to {@link where} on how to specify conditions. * Please refer to {@link where} on how to specify conditions.
* @param array $params the parameters (name=>value) to be bound to the query * @param array $params the parameters (name=>value) to be bound to the query
* @return CDbCommand the command object itself * @return Command the command object itself
* @since 1.1.6 * @since 1.1.6
*/ */
private function joinInternal($type, $table, $conditions = '', $params = array()) private function joinInternal($type, $table, $conditions = '', $params = array())
......
...@@ -580,12 +580,12 @@ class Connection extends \yii\base\ApplicationComponent ...@@ -580,12 +580,12 @@ class Connection extends \yii\base\ApplicationComponent
public function getStats() public function getStats()
{ {
$logger = \Yii::getLogger(); $logger = \Yii::getLogger();
$timings = $logger->getProfilingResults(null, 'yii\db\dao\Command::query'); $timings = $logger->getProfiling(array('yii\db\dao\Command::query', 'yii\db\dao\Command::execute'));
$count = count($timings); $count = count($timings);
$time = array_sum($timings); $time = 0;
$timings = $logger->getProfilingResults(null, 'yii\db\dao\Command::execute'); foreach ($timings as $timing) {
$count += count($timings); $time += $timing[1];
$time += array_sum($timings); }
return array($count, $time); return array($count, $time);
} }
} }
<?php <?php
/** /**
* CDbDataReader class file * DataReader class file
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2011 Yii Software LLC * @copyright Copyright &copy; 2008-2012 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
/** /**
* CDbDataReader represents a forward-only stream of rows from a query result set. * DataReader represents a forward-only stream of rows from a query result set.
* *
* To read the current row of data, call {@link read}. The method {@link readAll} * To read the current row of data, call [[read]]. The method [[readAll]]
* returns all the rows in a single array. * returns all the rows in a single array.
* *
* One can also retrieve the rows of data in CDbDataReader by using foreach: * One can also retrieve the rows of data in DataReader by using `foreach`:
* <pre> *
* foreach($reader as $row) * ~~~
* foreach($reader as $row) {
* // $row represents a row of data * // $row represents a row of data
* </pre> * }
* Since CDbDataReader is a forward-only stream, you can only traverse it once. * ~~~
*
* Since DataReader is a forward-only stream, you can only traverse it once.
* *
* It is possible to use a specific mode of data fetching by setting * It is possible to use a specific mode of data fetching by setting
* {@link setFetchMode FetchMode}. See {@link http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php} * [[fetchMode]]. See the [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
* for more details. * for more details about possible fetch mode.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @version $Id: CDbDataReader.php 3204 2011-05-05 21:36:32Z alexander.makarow $ * @since 2.0
* @package system.db
* @since 1.0
*/ */
class CDbDataReader extends CComponent implements Iterator, Countable class DataReader extends \yii\base\Component implements \Iterator, \Countable
{ {
private $_statement; private $_statement;
private $_closed = false; private $_closed = false;
...@@ -39,12 +40,12 @@ class CDbDataReader extends CComponent implements Iterator, Countable ...@@ -39,12 +40,12 @@ class CDbDataReader extends CComponent implements Iterator, Countable
/** /**
* Constructor. * Constructor.
* @param CDbCommand $command the command generating the query result * @param Command $command the command generating the query result
*/ */
public function __construct(CDbCommand $command) public function __construct(Command $command)
{ {
$this->_statement = $command->getPdoStatement(); $this->_statement = $command->getPdoStatement();
$this->_statement->setFetchMode(PDO::FETCH_ASSOC); $this->_statement->setFetchMode(\PDO::FETCH_ASSOC);
} }
/** /**
...@@ -60,11 +61,13 @@ class CDbDataReader extends CComponent implements Iterator, Countable ...@@ -60,11 +61,13 @@ class CDbDataReader extends CComponent implements Iterator, Countable
*/ */
public function bindColumn($column, &$value, $dataType = null) public function bindColumn($column, &$value, $dataType = null)
{ {
if ($dataType === null) if ($dataType === null) {
$this->_statement->bindColumn($column, $value); $this->_statement->bindColumn($column, $value);
else }
else {
$this->_statement->bindColumn($column, $value, $dataType); $this->_statement->bindColumn($column, $value, $dataType);
} }
}
/** /**
* Set the default fetch mode for this statement * Set the default fetch mode for this statement
...@@ -125,8 +128,9 @@ class CDbDataReader extends CComponent implements Iterator, Countable ...@@ -125,8 +128,9 @@ class CDbDataReader extends CComponent implements Iterator, Countable
*/ */
public function nextResult() public function nextResult()
{ {
if (($result = $this->_statement->nextRowset()) !== false) if (($result = $this->_statement->nextRowset()) !== false) {
$this->_index = -1; $this->_index = -1;
}
return $result; return $result;
} }
...@@ -186,17 +190,17 @@ class CDbDataReader extends CComponent implements Iterator, Countable ...@@ -186,17 +190,17 @@ class CDbDataReader extends CComponent implements Iterator, Countable
/** /**
* Resets the iterator to the initial state. * Resets the iterator to the initial state.
* This method is required by the interface Iterator. * This method is required by the interface Iterator.
* @throws CException if this method is invoked twice * @throws Exception if this method is invoked twice
*/ */
public function rewind() public function rewind()
{ {
if ($this->_index < 0) if ($this->_index < 0) {
{
$this->_row = $this->_statement->fetch(); $this->_row = $this->_statement->fetch();
$this->_index = 0; $this->_index = 0;
} }
else else {
throw new CDbException(Yii::t('yii', 'CDbDataReader cannot rewind. It is a forward-only reader.')); throw new Exception('DataReader cannot rewind. It is a forward-only reader.');
}
} }
/** /**
......
<?php <?php
/** /**
* CDbTransaction class file * Transaction class file.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2011 Yii Software LLC * @copyright Copyright &copy; 2008-2012 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
namespace yii\db\dao;
/** /**
* CDbTransaction represents a DB transaction. * Transaction represents a DB transaction.
*
* It is usually created by calling [[Connection::beginTransaction]].
* *
* It is usually created by calling {@link CDbConnection::beginTransaction}. * The following code is a typical example of using transactions (note that some
* DBMS may not support transactions):
* *
* The following code is a common scenario of using transactions: * ~~~
* <pre> * $transaction = $connection->beginTransaction();
* $transaction=$connection->beginTransaction(); * try {
* try
* {
* $connection->createCommand($sql1)->execute(); * $connection->createCommand($sql1)->execute();
* $connection->createCommand($sql2)->execute(); * $connection->createCommand($sql2)->execute();
* //.... other SQL executions * //.... other SQL executions
* $transaction->commit(); * $transaction->commit();
* } * }
* catch(Exception $e) * catch(Exception $e) {
* {
* $transaction->rollBack(); * $transaction->rollBack();
* } * }
* </pre> * ~~~
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @version $Id: CDbTransaction.php 3069 2011-03-14 00:28:38Z qiang.xue $ * @since 2.0
* @package system.db
* @since 1.0
*/ */
class CDbTransaction extends CComponent class Transaction extends \yii\base\Component
{ {
private $_connection = null; /**
private $_active; * @var boolean whether this transaction is active. Only an active transaction
* can [[commit]] or [[rollBack]]. This property is set true when the transaction is started.
*/
public $active;
/**
* @var Connection the database connection that this transaction is associated with.
* This property is set true when the transaction is started.
*/
public $connection;
/** /**
* Constructor. * Constructor.
* @param CDbConnection $connection the connection associated with this transaction * @param Connection $connection the connection associated with this transaction
* @see CDbConnection::beginTransaction * @see Connection::beginTransaction
*/ */
public function __construct(CDbConnection $connection) public function __construct($connection)
{ {
$this->_connection = $connection; $this->active = true;
$this->_active = true; $this->connection = $connection;
} }
/** /**
* Commits a transaction. * Commits a transaction.
* @throws CException if the transaction or the DB connection is not active. * @throws Exception if the transaction or the DB connection is not active.
*/ */
public function commit() public function commit()
{ {
if ($this->_active && $this->_connection->getActive()) if ($this->active && $this->connection->getActive()) {
{ Yii::trace('Committing transaction', __CLASS__);
Yii::trace('Committing transaction', 'system.db.CDbTransaction'); $this->connection->pdo->commit();
$this->_connection->getPdoInstance()->commit(); $this->active = false;
$this->_active = false; }
else {
throw new Exception('Transaction is inactive and cannot perform commit operation.');
} }
else
throw new CDbException(Yii::t('yii', 'CDbTransaction is inactive and cannot perform commit or roll back operations.'));
} }
/** /**
* Rolls back a transaction. * Rolls back a transaction.
* @throws CException if the transaction or the DB connection is not active. * @throws Exception if the transaction or the DB connection is not active.
*/ */
public function rollback() public function rollback()
{ {
if ($this->_active && $this->_connection->getActive()) if ($this->active && $this->connection->getActive()) {
{ Yii::trace('Rolling back transaction', __CLASS__);
Yii::trace('Rolling back transaction', 'system.db.CDbTransaction'); $this->connection->pdo->rollBack();
$this->_connection->getPdoInstance()->rollBack(); $this->active = false;
$this->_active = false;
} }
else else {
throw new CDbException(Yii::t('yii', 'CDbTransaction is inactive and cannot perform commit or roll back operations.')); throw new Exception('Transaction is inactive and cannot perform roll back operation.');
} }
/**
* @return CDbConnection the DB connection for this transaction
*/
public function getConnection()
{
return $this->_connection;
}
/**
* @return boolean whether this transaction is active
*/
public function getActive()
{
return $this->_active;
}
/**
* @param boolean $value whether this transaction is active
*/
protected function setActive($value)
{
$this->_active = $value;
} }
} }
...@@ -95,9 +95,9 @@ abstract class Validator extends \yii\base\Component ...@@ -95,9 +95,9 @@ abstract class Validator extends \yii\base\Component
public $on; public $on;
/** /**
* @var boolean whether this validation rule should be skipped if the attribute being validated * @var boolean whether this validation rule should be skipped if the attribute being validated
* already has some validation error according to the previous rules. Defaults to false. * already has some validation error according to the previous rules. Defaults to true.
*/ */
public $skipOnError = false; public $skipOnError = true;
/** /**
* @var boolean whether attributes listed with this validator should be considered safe for * @var boolean whether attributes listed with this validator should be considered safe for
* massive assignment. Defaults to true. * massive assignment. Defaults to true.
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment