Commit f9aa9a18 by Qiang Xue

code refactoring.

parent fb982c4f
......@@ -381,7 +381,7 @@ class YiiBase
* @param string $message the message to be logged.
* @param string $category the category of the message.
*/
public function error($message, $category = 'application')
public static function error($message, $category = 'application')
{
self::getLogger()->error($message, $category);
}
......@@ -393,7 +393,7 @@ class YiiBase
* @param string $message the message to be logged.
* @param string $category the category of the message.
*/
public function warning($message, $category = 'application')
public static function warning($message, $category = 'application')
{
self::getLogger()->warning($message, $category);
}
......@@ -405,7 +405,7 @@ class YiiBase
* @param string $message the message to be logged.
* @param string $category the category of the message.
*/
public function info($message, $category = 'application')
public static function info($message, $category = 'application')
{
self::getLogger()->info($message, $category);
}
......
......@@ -114,8 +114,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
{
if ($key === null) {
$this->_d[] = $value;
}
else {
} else {
$this->_d[$key] = $value;
}
}
......@@ -132,8 +131,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
$value = $this->_d[$key];
unset($this->_d[$key]);
return $value;
}
else { // the value is null
} else { // the value is null
unset($this->_d[$key]);
return null;
}
......@@ -194,8 +192,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
foreach ($data as $key => $value) {
$this->add($key, $value);
}
}
else {
} else {
throw new Exception('Data must be either an array or an object implementing Traversable.');
}
}
......@@ -230,18 +227,15 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
$d[$key] = $value;
}
$this->_d = self::mergeArray($this->_d, $d);
}
else {
} else {
$this->_d = self::mergeArray($this->_d, $data);
}
}
else {
} else {
foreach($data as $key => $value) {
$this->add($key, $value);
}
}
}
else {
} else {
throw new Exception('Dictionary data must be an array or an object implementing Traversable.');
}
}
......@@ -317,12 +311,11 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
foreach($b as $k=>$v) {
if(is_integer($k)) {
isset($a[$k]) ? $a[] = $v : $a[$k] = $v;
}
elseif(is_array($v) && isset($a[$k]) && is_array($a[$k])) {
} elseif(is_array($v) && isset($a[$k]) && is_array($a[$k])) {
$a[$k] = self::mergeArray($a[$k], $v);
}
else
} else {
$a[$k] = $v;
}
}
return $a;
}
......
......@@ -367,8 +367,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc
if (isset($rule[0], $rule[1])) { // attributes, validator type
$validator = \yii\validators\Validator::createValidator($rule[1], $this, $rule[0], array_slice($rule, 2));
$validators->add($validator);
}
else {
} else {
throw new Exception('Invalid validation rule: a rule must specify both attribute names and validator type.');
}
}
......@@ -456,8 +455,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc
{
if ($attribute === null) {
return $this->_errors === null ? array() : $this->_errors;
}
else {
} else {
return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
}
}
......@@ -496,8 +494,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc
foreach ($error as $e) {
$this->_errors[$attribute][] = $e;
}
}
else {
} else {
$this->_errors[$attribute][] = $error;
}
}
......@@ -511,8 +508,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc
{
if ($attribute === null) {
$this->_errors = array();
}
else {
} else {
unset($this->_errors[$attribute]);
}
}
......@@ -547,8 +543,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc
$values[$name] = $this->$name;
}
}
}
else {
} else {
foreach ($this->attributeNames() as $name) {
$values[$name] = $this->$name;
}
......@@ -572,8 +567,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc
foreach ($values as $name => $value) {
if (isset($attributes[$name])) {
$this->$name = $value;
}
elseif ($safeOnly) {
} elseif ($safeOnly) {
$this->onUnsafeAttribute($name, $value);
}
}
......@@ -639,8 +633,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc
foreach ($validator->attributes as $name) {
$unsafe[] = $name;
}
}
else {
} else {
foreach ($validator->attributes as $name) {
$attributes[$name] = true;
}
......
......@@ -103,11 +103,9 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
{
if (isset($this->_d[$index])) {
return $this->_d[$index];
}
elseif ($index >= 0 && $index < $this->_c) { // in case the value is null
} elseif ($index >= 0 && $index < $this->_c) { // in case the value is null
return $this->_d[$index];
}
else {
} else {
throw new Exception('Index out of range: ' . $index);
}
}
......@@ -136,12 +134,10 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
{
if ($index === $this->_c) {
$this->_d[$this->_c++] = $item;
}
elseif ($index >= 0 && $index < $this->_c) {
} elseif ($index >= 0 && $index < $this->_c) {
array_splice($this->_d, $index, 0, array($item));
$this->_c++;
}
else {
} else {
throw new Exception('Index out of range: ' . $index);
}
}
......@@ -157,12 +153,10 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
*/
public function remove($item)
{
if (($index = $this->indexOf($item)) >= 0)
{
if (($index = $this->indexOf($item)) >= 0) {
$this->removeAt($index);
return $index;
}
else {
} else {
return false;
}
}
......@@ -179,14 +173,12 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
$this->_c--;
if ($index === $this->_c) {
return array_pop($this->_d);
}
else {
} else {
$item = $this->_d[$index];
array_splice($this->_d, $index, 1);
return $item;
}
}
else {
} else {
throw new Exception('Index out of range: ' . $index);
}
}
......@@ -260,8 +252,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
foreach ($data as $item) {
$this->add($item);
}
}
else {
} else {
throw new Exception('Data must be either an array or an object implementing Traversable.');
}
}
......@@ -281,8 +272,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
foreach ($data as $item) {
$this->add($item);
}
}
else {
} else {
throw new Exception('Data must be either an array or an object implementing Traversable.');
}
}
......@@ -328,8 +318,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
{
if ($offset === null || $offset === $this->_c) {
$this->insertAt($this->_c, $item);
}
else {
} else {
$this->removeAt($offset);
$this->insertAt($offset, $item);
}
......
......@@ -11,7 +11,7 @@
namespace yii\db;
/**
* CDbException represents an exception that is caused by some DB-related operations.
* Exception represents an exception that is caused by some DB-related operations.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
......@@ -20,8 +20,7 @@ class Exception extends \yii\base\Exception
{
/**
* @var mixed the error info provided by a PDO exception. This is the same as returned
* by {@link http://www.php.net/manual/en/pdo.errorinfo.php PDO::errorInfo}.
* @since 1.1.4
* by [PDO::errorInfo](http://www.php.net/manual/en/pdo.errorinfo.php).
*/
public $errorInfo;
......
......@@ -46,14 +46,13 @@ abstract class CDbMigration extends CComponent
$transaction = $this->getDbConnection()->beginTransaction();
try
{
if ($this->safeUp() === false)
{
if ($this->safeUp() === false) {
$transaction->rollBack();
return false;
}
$transaction->commit();
}
catch(Exception $e)
catch (Exception $e)
{
echo "Exception: " . $e->getMessage() . ' (' . $e->getFile() . ':' . $e->getLine() . ")\n";
echo $e->getTraceAsString() . "\n";
......@@ -73,14 +72,13 @@ abstract class CDbMigration extends CComponent
$transaction = $this->getDbConnection()->beginTransaction();
try
{
if ($this->safeDown() === false)
{
if ($this->safeDown() === false) {
$transaction->rollBack();
return false;
}
$transaction->commit();
}
catch(Exception $e)
catch (Exception $e)
{
echo "Exception: " . $e->getMessage() . ' (' . $e->getFile() . ':' . $e->getLine() . ")\n";
echo $e->getTraceAsString() . "\n";
......@@ -125,8 +123,7 @@ abstract class CDbMigration extends CComponent
*/
public function getDbConnection()
{
if ($this->_db === null)
{
if ($this->_db === null) {
$this->_db = Yii::app()->getComponent('db');
if (!$this->_db instanceof CDbConnection)
throw new CException(Yii::t('yii', 'The "db" application component must be configured to be a CDbConnection object.'));
......
<?php
/**
* This file contains the Command class.
* Command class file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
......@@ -16,30 +16,28 @@ use yii\db\Exception;
* Command represents a SQL statement to be executed against a database.
*
* A command object is usually created by calling [[Connection::createCommand]].
* The SQL statement it represents can be set via the [[text]] property.
* The SQL statement it represents can be set via the [[sql]] property.
*
* To execute a non-query SQL (such as insert, delete, update), call [[execute]].
* To execute an SQL statement that returns result data set (such as SELECT),
* To execute a non-query SQL (such as INSERT, DELETE, UPDATE), call [[execute]].
* To execute a SQL statement that returns result data set (such as SELECT),
* use [[query]], [[queryRow]], [[queryColumn]], or [[queryScalar]].
*
* If an SQL statement returns results (such as a SELECT SQL), the results
* can be accessed via the returned {@link CDbDataReader}.
*
* Command supports SQL statment preparation and parameter binding.
* Call {@link bindParam} to bind a PHP variable to a parameter in SQL.
* Call {@link bindValue} to bind a value to an SQL parameter.
* Command supports SQL statement preparation and parameter binding.
* Call [[bindValue]] to bind a value to a SQL parameter;
* Call [[bindParam]] to bind a PHP variable to a SQL parameter.
* 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 [[prepare]] to explicitly prepare a SQL statement.
*
* Command can also be used as a query builder that builds and executes a SQL statement
* from code fragments. For example,
*
* 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,
* <pre>
* ~~~
* $user = \Yii::app()->db->createCommand()
* ->select('username, password')
* ->from('tbl_user')
* ->where('id=:id', array(':id'=>1))
* ->queryRow();
* </pre>
* ~~~
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
......@@ -50,24 +48,36 @@ class Command extends \yii\base\Component
* @var array the parameters (name=>value) to be bound to the current query.
*/
public $params = array();
/**
* @var Connection the DB connection that this command is associated with
*/
public $connection;
/**
* @var Query the database query that this command is currently representing
*/
public $query;
/**
* @var \PDOStatement the PDOStatement object that this command contains
*/
public $pdoStatement;
private $_sql;
private $_paramLog = array();
/**
* Set the default fetch mode for this statement
* @param mixed $mode fetch mode
* @return Command
* @var mixed the default fetch mode for this command.
* @see http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php
*/
public $fetchMode = \PDO::FETCH_ASSOC;
/**
* @var string the SQL statement that this command represents
*/
private $_sql;
/**
* @var array the parameter log information
*/
private $_paramLog = array();
/**
* Constructor.
* @param CDbConnection $connection the database connection
* @param Connection $connection the database connection
* @param mixed $query the DB query to be executed. This can be either
* a string representing a SQL statement, or an array whose name-value pairs
* will be used to set the corresponding properties of the created command object.
......@@ -91,13 +101,11 @@ class Command extends \yii\base\Component
$this->connection = $connection;
if (is_object($query)) {
$this->query = $query;
}
else {
} else {
$this->query = new Query;
if (is_array($query)) {
$this->query->fromArray($query);
}
else {
} else {
$this->_sql = $query;
}
}
......@@ -109,15 +117,14 @@ class Command extends \yii\base\Component
* multiple times for building different queries.
* Calling this method will clean up all internal states of the command object.
* @return Command this command instance
* @since 1.1.6
*/
public function reset()
{
$this->_sql = null;
$this->query = new Query;
$this->pdoStatement = null;
$this->_paramLog = array();
$this->params = array();
$this->_paramLog = array();
$this->_sql = null;
return $this;
}
......@@ -135,15 +142,14 @@ class Command extends \yii\base\Component
/**
* Specifies the SQL statement to be executed.
* 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 set.
* @return Command this command instance
*/
public function setSql($value)
{
if ($this->connection->tablePrefix !== null && strpos($value, '{') !== false) {
if ($this->connection->tablePrefix !== null && strpos($value, '{{') !== false) {
$this->_sql = preg_replace('/{{(.*?)}}/', $this->connection->tablePrefix . '\1', $value);
}
else {
} else {
$this->_sql = $value;
}
$this->cancel();
......@@ -160,15 +166,16 @@ class Command extends \yii\base\Component
public function prepare()
{
if ($this->pdoStatement == null) {
$sql = $this->getSql();
try {
$this->pdoStatement = $this->connection->pdo->prepare($this->getSql());
$this->pdoStatement = $this->connection->pdo->prepare($sql);
$this->_paramLog = array();
}
catch(\Exception $e) {
\Yii::log('Error in preparing SQL: ' . $this->getSql(), CLogger::LEVEL_ERROR, 'system.db.Command');
\Yii::error("Failed to prepare SQL ($sql): " . $e->getMessage(), __CLASS__);
$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
throw new Exception('Unable to prepare the SQL statement: {error}',
array('{error}' => $e->getMessage()), (int)$e->getCode(), $errorInfo);
$message = YII_DEBUG ? 'Failed to prepare SQL: ' . $e->getMessage() : 'Failed to prepare SQL.';
throw new Exception($message, (int)$e->getCode(), $errorInfo);
}
}
}
......@@ -197,14 +204,15 @@ class Command extends \yii\base\Component
public function bindParam($name, &$value, $dataType = null, $length = null, $driverOptions = null)
{
$this->prepare();
if ($dataType === null)
if ($dataType === null) {
$this->pdoStatement->bindParam($name, $value, $this->connection->getPdoType(gettype($value)));
elseif ($length === null)
} elseif ($length === null) {
$this->pdoStatement->bindParam($name, $value, $dataType);
elseif ($driverOptions === null)
} elseif ($driverOptions === null) {
$this->pdoStatement->bindParam($name, $value, $dataType, $length);
else
} else {
$this->pdoStatement->bindParam($name, $value, $dataType, $length, $driverOptions);
}
$this->_paramLog[$name] =& $value;
return $this;
}
......@@ -223,10 +231,11 @@ class Command extends \yii\base\Component
public function bindValue($name, $value, $dataType = null)
{
$this->prepare();
if ($dataType === null)
if ($dataType === null) {
$this->pdoStatement->bindValue($name, $value, $this->connection->getPdoType(gettype($value)));
else
} else {
$this->pdoStatement->bindValue($name, $value, $dataType);
}
$this->_paramLog[$name] = $value;
return $this;
}
......@@ -244,8 +253,7 @@ class Command extends \yii\base\Component
public function bindValues($values)
{
$this->prepare();
foreach ($values as $name => $value)
{
foreach ($values as $name => $value) {
$this->pdoStatement->bindValue($name, $value, $this->connection->getPdoType(gettype($value)));
$this->_paramLog[$name] = $value;
}
......@@ -311,7 +319,7 @@ class Command extends \yii\base\Component
/**
* Executes the SQL statement and returns query result.
* This method is for executing an SQL query that returns result set.
* This method is for executing a SQL query that returns result set.
* @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
* to {@link bindParam} and {@link bindValue}. If you have multiple input parameters, passing
* them in this way can improve the performance. Note that if you pass parameters in this way,
......
......@@ -246,7 +246,13 @@ class Connection extends \yii\base\ApplicationComponent
'oci' => '\yii\db\dao\oci\Schema', // Oracle driver
);
/**
* @var Transaction the currently active transaction
*/
private $_transaction;
/**
* @var Schema the database schema
*/
private $_schema;
/**
......@@ -344,13 +350,9 @@ class Connection extends \yii\base\ApplicationComponent
$this->initConnection($this->pdo);
}
catch (\PDOException $e) {
if (YII_DEBUG) {
throw new Exception('Failed to open DB connection: ' . $e->getMessage(), (int)$e->getCode(), $e->errorInfo);
}
else {
\Yii::error($e->getMessage(), __CLASS__);
throw new Exception('Failed to open DB connection.', (int)$e->getCode(), $e->errorInfo);
}
\Yii::error("Failed to open DB connection ({$this->dsn}): " . $e->getMessage(), __CLASS__);
$message = YII_DEBUG ? 'Failed to open DB connection: ' . $e->getMessage() : 'Failed to open DB connection.';
throw new Exception($message, (int)$e->getCode(), $e->errorInfo);
}
}
}
......@@ -400,10 +402,8 @@ class Connection extends \yii\base\ApplicationComponent
if ($this->emulatePrepare !== null && constant('\PDO::ATTR_EMULATE_PREPARES')) {
$this->pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
}
if ($this->charset !== null) {
if (in_array($this->getDriverName(), array('pgsql', 'mysql', 'mysqli'))) {
$this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
}
if ($this->charset !== null && in_array($this->getDriverName(), array('pgsql', 'mysql', 'mysqli'))) {
$this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
}
if (!empty($this->initSQLs)) {
foreach ($this->initSQLs as $sql) {
......@@ -434,7 +434,7 @@ class Connection extends \yii\base\ApplicationComponent
*/
public function getCurrentTransaction()
{
if ($this->_transaction !== null && $this->_transaction->getActive()) {
if ($this->_transaction !== null && $this->_transaction->active) {
return $this->_transaction;
}
}
......@@ -459,23 +459,16 @@ class Connection extends \yii\base\ApplicationComponent
{
if ($this->_schema !== null) {
return $this->_schema;
}
else {
} else {
$driver = $this->getDriverName();
if (isset($this->schemaMap[$driver])) {
return $this->_schema = \Yii::create($this->schemaMap[$driver], $this);
}
else {
} else {
throw new Exception("Connection does not support reading schema for '$driver' database.");
}
}
}
public function getQueryBuilder()
{
return $this->getSchema()->getQueryBuilder();
}
/**
* Returns the query builder for the current DB connection.
* @return QueryBuilder the query builder for the current DB connection.
......@@ -513,8 +506,7 @@ class Connection extends \yii\base\ApplicationComponent
$this->open();
if (($value = $this->pdo->quote($str)) !== false) {
return $value;
}
else { // the driver doesn't support quote (e.g. oci)
} else { // the driver doesn't support quote (e.g. oci)
return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
}
}
......@@ -568,8 +560,7 @@ class Connection extends \yii\base\ApplicationComponent
{
if (($pos = strpos($this->dsn, ':')) !== false) {
return strtolower(substr($this->dsn, 0, $pos));
}
else {
} else {
return strtolower($this->getAttribute(\PDO::ATTR_DRIVER_NAME));
}
}
......
......@@ -35,7 +35,7 @@ use yii\db\Exception;
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class DataReader extends \yii\base\Component implements \Iterator, \Countable
class DataReader extends \yii\base\Object implements \Iterator, \Countable
{
private $_statement;
private $_closed = false;
......
......@@ -26,7 +26,7 @@ namespace yii\db\dao;
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Expression
class Expression extends \yii\base\Object
{
/**
* @var string the DB expression
......
......@@ -16,7 +16,7 @@ namespace yii\db\dao;
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Query extends \yii\base\Component
class Query extends \yii\base\Object
{
/**
* @var mixed the columns being selected. This refers to the SELECT clause in an SQL
......
......@@ -18,7 +18,7 @@ use yii\db\Exception;
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class QueryBuilder extends \yii\base\Component
class QueryBuilder extends \yii\base\Object
{
/**
* @var array the abstract column types mapped to physical column types.
......
......@@ -18,7 +18,7 @@ use yii\db\Exception;
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
abstract class Schema extends \yii\base\Component
abstract class Schema extends \yii\base\Object
{
public $connection;
......
......@@ -28,7 +28,7 @@ namespace yii\db\dao;
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class TableSchema extends \yii\base\Component
class TableSchema extends \yii\base\Object
{
/**
* @var string name of the schema that this table belongs to.
......
......@@ -36,7 +36,7 @@ use yii\db\Exception;
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Transaction extends \yii\base\Component
class Transaction extends \yii\base\Object
{
/**
* @var boolean whether this transaction is active. Only an active transaction
......@@ -67,7 +67,7 @@ class Transaction extends \yii\base\Component
public function commit()
{
if ($this->active && $this->connection->getActive()) {
Yii::trace('Committing transaction', __CLASS__);
\Yii::trace('Committing transaction', __CLASS__);
$this->connection->pdo->commit();
$this->active = false;
}
......@@ -83,7 +83,7 @@ class Transaction extends \yii\base\Component
public function rollback()
{
if ($this->active && $this->connection->getActive()) {
Yii::trace('Rolling back transaction', __CLASS__);
\Yii::trace('Rolling back transaction', __CLASS__);
$this->connection->pdo->rollBack();
$this->active = false;
}
......
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