Browse Source

code refactoring.

tags/2.0.0-beta
Qiang Xue 13 years ago
parent
commit
f9aa9a181f
  1. 6
      framework/YiiBase.php
  2. 25
      framework/base/Dictionary.php
  3. 21
      framework/base/Model.php
  4. 33
      framework/base/Vector.php
  5. 5
      framework/db/Exception.php
  6. 9
      framework/db/Migration.php
  7. 102
      framework/db/dao/Command.php
  8. 39
      framework/db/dao/Connection.php
  9. 2
      framework/db/dao/DataReader.php
  10. 2
      framework/db/dao/Expression.php
  11. 2
      framework/db/dao/Query.php
  12. 2
      framework/db/dao/QueryBuilder.php
  13. 2
      framework/db/dao/Schema.php
  14. 2
      framework/db/dao/TableSchema.php
  15. 6
      framework/db/dao/Transaction.php

6
framework/YiiBase.php

@ -381,7 +381,7 @@ class YiiBase
* @param string $message the message to be logged. * @param string $message the message to be logged.
* @param string $category the category of the message. * @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); self::getLogger()->error($message, $category);
} }
@ -393,7 +393,7 @@ class YiiBase
* @param string $message the message to be logged. * @param string $message the message to be logged.
* @param string $category the category of the message. * @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); self::getLogger()->warning($message, $category);
} }
@ -405,7 +405,7 @@ class YiiBase
* @param string $message the message to be logged. * @param string $message the message to be logged.
* @param string $category the category of the message. * @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); self::getLogger()->info($message, $category);
} }

25
framework/base/Dictionary.php

@ -114,8 +114,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
{ {
if ($key === null) { if ($key === null) {
$this->_d[] = $value; $this->_d[] = $value;
} } else {
else {
$this->_d[$key] = $value; $this->_d[$key] = $value;
} }
} }
@ -132,8 +131,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
$value = $this->_d[$key]; $value = $this->_d[$key];
unset($this->_d[$key]); unset($this->_d[$key]);
return $value; return $value;
} } else { // the value is null
else { // the value is null
unset($this->_d[$key]); unset($this->_d[$key]);
return null; return null;
} }
@ -194,8 +192,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
$this->add($key, $value); $this->add($key, $value);
} }
} } else {
else {
throw new Exception('Data must be either an array or an object implementing Traversable.'); 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; $d[$key] = $value;
} }
$this->_d = self::mergeArray($this->_d, $d); $this->_d = self::mergeArray($this->_d, $d);
} } else {
else {
$this->_d = self::mergeArray($this->_d, $data); $this->_d = self::mergeArray($this->_d, $data);
} }
} } else {
else {
foreach($data as $key => $value) { foreach($data as $key => $value) {
$this->add($key, $value); $this->add($key, $value);
} }
} }
} } else {
else {
throw new Exception('Dictionary data must be an array or an object implementing Traversable.'); throw new Exception('Dictionary data must be an array or an object implementing Traversable.');
} }
} }
@ -317,13 +311,12 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
foreach($b as $k=>$v) { foreach($b as $k=>$v) {
if(is_integer($k)) { if(is_integer($k)) {
isset($a[$k]) ? $a[] = $v : $a[$k] = $v; 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); $a[$k] = self::mergeArray($a[$k], $v);
} } else {
else
$a[$k] = $v; $a[$k] = $v;
} }
}
return $a; return $a;
} }
} }

21
framework/base/Model.php

@ -367,8 +367,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc
if (isset($rule[0], $rule[1])) { // attributes, validator type if (isset($rule[0], $rule[1])) { // attributes, validator type
$validator = \yii\validators\Validator::createValidator($rule[1], $this, $rule[0], array_slice($rule, 2)); $validator = \yii\validators\Validator::createValidator($rule[1], $this, $rule[0], array_slice($rule, 2));
$validators->add($validator); $validators->add($validator);
} } else {
else {
throw new Exception('Invalid validation rule: a rule must specify both attribute names and validator type.'); 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) { if ($attribute === null) {
return $this->_errors === null ? array() : $this->_errors; return $this->_errors === null ? array() : $this->_errors;
} } else {
else {
return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array(); 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) { foreach ($error as $e) {
$this->_errors[$attribute][] = $e; $this->_errors[$attribute][] = $e;
} }
} } else {
else {
$this->_errors[$attribute][] = $error; $this->_errors[$attribute][] = $error;
} }
} }
@ -511,8 +508,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc
{ {
if ($attribute === null) { if ($attribute === null) {
$this->_errors = array(); $this->_errors = array();
} } else {
else {
unset($this->_errors[$attribute]); unset($this->_errors[$attribute]);
} }
} }
@ -547,8 +543,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc
$values[$name] = $this->$name; $values[$name] = $this->$name;
} }
} }
} } else {
else {
foreach ($this->attributeNames() as $name) { foreach ($this->attributeNames() as $name) {
$values[$name] = $this->$name; $values[$name] = $this->$name;
} }
@ -572,8 +567,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc
foreach ($values as $name => $value) { foreach ($values as $name => $value) {
if (isset($attributes[$name])) { if (isset($attributes[$name])) {
$this->$name = $value; $this->$name = $value;
} } elseif ($safeOnly) {
elseif ($safeOnly) {
$this->onUnsafeAttribute($name, $value); $this->onUnsafeAttribute($name, $value);
} }
} }
@ -639,8 +633,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc
foreach ($validator->attributes as $name) { foreach ($validator->attributes as $name) {
$unsafe[] = $name; $unsafe[] = $name;
} }
} } else {
else {
foreach ($validator->attributes as $name) { foreach ($validator->attributes as $name) {
$attributes[$name] = true; $attributes[$name] = true;
} }

33
framework/base/Vector.php

@ -103,11 +103,9 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
{ {
if (isset($this->_d[$index])) { if (isset($this->_d[$index])) {
return $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]; return $this->_d[$index];
} } else {
else {
throw new Exception('Index out of range: ' . $index); throw new Exception('Index out of range: ' . $index);
} }
} }
@ -136,12 +134,10 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
{ {
if ($index === $this->_c) { if ($index === $this->_c) {
$this->_d[$this->_c++] = $item; $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)); array_splice($this->_d, $index, 0, array($item));
$this->_c++; $this->_c++;
} } else {
else {
throw new Exception('Index out of range: ' . $index); throw new Exception('Index out of range: ' . $index);
} }
} }
@ -157,12 +153,10 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
*/ */
public function remove($item) public function remove($item)
{ {
if (($index = $this->indexOf($item)) >= 0) if (($index = $this->indexOf($item)) >= 0) {
{
$this->removeAt($index); $this->removeAt($index);
return $index; return $index;
} } else {
else {
return false; return false;
} }
} }
@ -179,14 +173,12 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
$this->_c--; $this->_c--;
if ($index === $this->_c) { if ($index === $this->_c) {
return array_pop($this->_d); return array_pop($this->_d);
} } else {
else {
$item = $this->_d[$index]; $item = $this->_d[$index];
array_splice($this->_d, $index, 1); array_splice($this->_d, $index, 1);
return $item; return $item;
} }
} } else {
else {
throw new Exception('Index out of range: ' . $index); throw new Exception('Index out of range: ' . $index);
} }
} }
@ -260,8 +252,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
foreach ($data as $item) { foreach ($data as $item) {
$this->add($item); $this->add($item);
} }
} } else {
else {
throw new Exception('Data must be either an array or an object implementing Traversable.'); 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) { foreach ($data as $item) {
$this->add($item); $this->add($item);
} }
} } else {
else {
throw new Exception('Data must be either an array or an object implementing Traversable.'); 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) { if ($offset === null || $offset === $this->_c) {
$this->insertAt($this->_c, $item); $this->insertAt($this->_c, $item);
} } else {
else {
$this->removeAt($offset); $this->removeAt($offset);
$this->insertAt($offset, $item); $this->insertAt($offset, $item);
} }

5
framework/db/Exception.php

@ -11,7 +11,7 @@
namespace yii\db; 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> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @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 * @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}. * by [PDO::errorInfo](http://www.php.net/manual/en/pdo.errorinfo.php).
* @since 1.1.4
*/ */
public $errorInfo; public $errorInfo;

9
framework/db/Migration.php

@ -46,8 +46,7 @@ abstract class CDbMigration extends CComponent
$transaction = $this->getDbConnection()->beginTransaction(); $transaction = $this->getDbConnection()->beginTransaction();
try try
{ {
if ($this->safeUp() === false) if ($this->safeUp() === false) {
{
$transaction->rollBack(); $transaction->rollBack();
return false; return false;
} }
@ -73,8 +72,7 @@ abstract class CDbMigration extends CComponent
$transaction = $this->getDbConnection()->beginTransaction(); $transaction = $this->getDbConnection()->beginTransaction();
try try
{ {
if ($this->safeDown() === false) if ($this->safeDown() === false) {
{
$transaction->rollBack(); $transaction->rollBack();
return false; return false;
} }
@ -125,8 +123,7 @@ abstract class CDbMigration extends CComponent
*/ */
public function getDbConnection() public function getDbConnection()
{ {
if ($this->_db === null) if ($this->_db === null) {
{
$this->_db = Yii::app()->getComponent('db'); $this->_db = Yii::app()->getComponent('db');
if (!$this->_db instanceof CDbConnection) if (!$this->_db instanceof CDbConnection)
throw new CException(Yii::t('yii', 'The "db" application component must be configured to be a CDbConnection object.')); throw new CException(Yii::t('yii', 'The "db" application component must be configured to be a CDbConnection object.'));

102
framework/db/dao/Command.php

@ -1,6 +1,6 @@
<?php <?php
/** /**
* This file contains the Command class. * Command 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/
@ -16,30 +16,28 @@ use yii\db\Exception;
* Command represents a SQL statement to be executed against a database. * Command represents a SQL statement to be executed against a database.
* *
* A command object is usually created by calling [[Connection::createCommand]]. * 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 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 SQL statement that returns result data set (such as SELECT),
* use [[query]], [[queryRow]], [[queryColumn]], or [[queryScalar]]. * use [[query]], [[queryRow]], [[queryColumn]], or [[queryScalar]].
* *
* If an SQL statement returns results (such as a SELECT SQL), the results * Command supports SQL statement preparation and parameter binding.
* can be accessed via the returned {@link CDbDataReader}. * Call [[bindValue]] to bind a value to a SQL parameter;
* * Call [[bindParam]] to bind a PHP variable to a SQL parameter.
* 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.
* 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 [[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() * $user = \Yii::app()->db->createCommand()
* ->select('username, password') * ->select('username, password')
* ->from('tbl_user') * ->from('tbl_user')
* ->where('id=:id', array(':id'=>1)) * ->where('id=:id', array(':id'=>1))
* ->queryRow(); * ->queryRow();
* </pre> * ~~~
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @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. * @var array the parameters (name=>value) to be bound to the current query.
*/ */
public $params = array(); public $params = array();
/**
* @var Connection the DB connection that this command is associated with
*/
public $connection; public $connection;
/**
* @var Query the database query that this command is currently representing
*/
public $query; public $query;
/**
* @var \PDOStatement the PDOStatement object that this command contains
*/
public $pdoStatement; public $pdoStatement;
private $_sql;
private $_paramLog = array();
/** /**
* Set the default fetch mode for this statement * @var mixed the default fetch mode for this command.
* @param mixed $mode fetch mode
* @return Command
* @see http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php * @see http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php
*/ */
public $fetchMode = \PDO::FETCH_ASSOC; 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. * 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 * @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 * 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. * 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; $this->connection = $connection;
if (is_object($query)) { if (is_object($query)) {
$this->query = $query; $this->query = $query;
} } else {
else {
$this->query = new Query; $this->query = new Query;
if (is_array($query)) { if (is_array($query)) {
$this->query->fromArray($query); $this->query->fromArray($query);
} } else {
else {
$this->_sql = $query; $this->_sql = $query;
} }
} }
@ -109,15 +117,14 @@ class Command extends \yii\base\Component
* 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 Command this command instance * @return Command this command instance
* @since 1.1.6
*/ */
public function reset() public function reset()
{ {
$this->_sql = null;
$this->query = new Query; $this->query = new Query;
$this->pdoStatement = null; $this->pdoStatement = null;
$this->_paramLog = array();
$this->params = array(); $this->params = array();
$this->_paramLog = array();
$this->_sql = null;
return $this; return $this;
} }
@ -135,15 +142,14 @@ class Command extends \yii\base\Component
/** /**
* 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 set.
* @return Command this command instance * @return Command this command instance
*/ */
public function setSql($value) 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); $this->_sql = preg_replace('/{{(.*?)}}/', $this->connection->tablePrefix . '\1', $value);
} } else {
else {
$this->_sql = $value; $this->_sql = $value;
} }
$this->cancel(); $this->cancel();
@ -160,15 +166,16 @@ class Command extends \yii\base\Component
public function prepare() public function prepare()
{ {
if ($this->pdoStatement == null) { if ($this->pdoStatement == null) {
$sql = $this->getSql();
try { try {
$this->pdoStatement = $this->connection->pdo->prepare($this->getSql()); $this->pdoStatement = $this->connection->pdo->prepare($sql);
$this->_paramLog = array(); $this->_paramLog = array();
} }
catch(\Exception $e) { 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; $errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
throw new Exception('Unable to prepare the SQL statement: {error}', $message = YII_DEBUG ? 'Failed to prepare SQL: ' . $e->getMessage() : 'Failed to prepare SQL.';
array('{error}' => $e->getMessage()), (int)$e->getCode(), $errorInfo); 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) public function bindParam($name, &$value, $dataType = null, $length = null, $driverOptions = null)
{ {
$this->prepare(); $this->prepare();
if ($dataType === null) if ($dataType === null) {
$this->pdoStatement->bindParam($name, $value, $this->connection->getPdoType(gettype($value))); $this->pdoStatement->bindParam($name, $value, $this->connection->getPdoType(gettype($value)));
elseif ($length === null) } elseif ($length === null) {
$this->pdoStatement->bindParam($name, $value, $dataType); $this->pdoStatement->bindParam($name, $value, $dataType);
elseif ($driverOptions === null) } elseif ($driverOptions === null) {
$this->pdoStatement->bindParam($name, $value, $dataType, $length); $this->pdoStatement->bindParam($name, $value, $dataType, $length);
else } else {
$this->pdoStatement->bindParam($name, $value, $dataType, $length, $driverOptions); $this->pdoStatement->bindParam($name, $value, $dataType, $length, $driverOptions);
}
$this->_paramLog[$name] =& $value; $this->_paramLog[$name] =& $value;
return $this; return $this;
} }
@ -223,10 +231,11 @@ class Command extends \yii\base\Component
public function bindValue($name, $value, $dataType = null) public function bindValue($name, $value, $dataType = null)
{ {
$this->prepare(); $this->prepare();
if ($dataType === null) if ($dataType === null) {
$this->pdoStatement->bindValue($name, $value, $this->connection->getPdoType(gettype($value))); $this->pdoStatement->bindValue($name, $value, $this->connection->getPdoType(gettype($value)));
else } else {
$this->pdoStatement->bindValue($name, $value, $dataType); $this->pdoStatement->bindValue($name, $value, $dataType);
}
$this->_paramLog[$name] = $value; $this->_paramLog[$name] = $value;
return $this; return $this;
} }
@ -244,8 +253,7 @@ class Command extends \yii\base\Component
public function bindValues($values) public function bindValues($values)
{ {
$this->prepare(); $this->prepare();
foreach ($values as $name => $value) foreach ($values as $name => $value) {
{
$this->pdoStatement->bindValue($name, $value, $this->connection->getPdoType(gettype($value))); $this->pdoStatement->bindValue($name, $value, $this->connection->getPdoType(gettype($value)));
$this->_paramLog[$name] = $value; $this->_paramLog[$name] = $value;
} }
@ -311,7 +319,7 @@ class Command extends \yii\base\Component
/** /**
* Executes the SQL statement and returns query result. * 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 * @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 * 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, * them in this way can improve the performance. Note that if you pass parameters in this way,

39
framework/db/dao/Connection.php

@ -246,7 +246,13 @@ class Connection extends \yii\base\ApplicationComponent
'oci' => '\yii\db\dao\oci\Schema', // Oracle driver 'oci' => '\yii\db\dao\oci\Schema', // Oracle driver
); );
/**
* @var Transaction the currently active transaction
*/
private $_transaction; private $_transaction;
/**
* @var Schema the database schema
*/
private $_schema; private $_schema;
/** /**
@ -344,13 +350,9 @@ class Connection extends \yii\base\ApplicationComponent
$this->initConnection($this->pdo); $this->initConnection($this->pdo);
} }
catch (\PDOException $e) { catch (\PDOException $e) {
if (YII_DEBUG) { \Yii::error("Failed to open DB connection ({$this->dsn}): " . $e->getMessage(), __CLASS__);
throw new Exception('Failed to open DB connection: ' . $e->getMessage(), (int)$e->getCode(), $e->errorInfo); $message = YII_DEBUG ? 'Failed to open DB connection: ' . $e->getMessage() : 'Failed to open DB connection.';
} throw new Exception($message, (int)$e->getCode(), $e->errorInfo);
else {
\Yii::error($e->getMessage(), __CLASS__);
throw new Exception('Failed to open DB connection.', (int)$e->getCode(), $e->errorInfo);
}
} }
} }
} }
@ -400,11 +402,9 @@ class Connection extends \yii\base\ApplicationComponent
if ($this->emulatePrepare !== null && constant('\PDO::ATTR_EMULATE_PREPARES')) { if ($this->emulatePrepare !== null && constant('\PDO::ATTR_EMULATE_PREPARES')) {
$this->pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare); $this->pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
} }
if ($this->charset !== null) { if ($this->charset !== null && in_array($this->getDriverName(), array('pgsql', 'mysql', 'mysqli'))) {
if (in_array($this->getDriverName(), array('pgsql', 'mysql', 'mysqli'))) {
$this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset)); $this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
} }
}
if (!empty($this->initSQLs)) { if (!empty($this->initSQLs)) {
foreach ($this->initSQLs as $sql) { foreach ($this->initSQLs as $sql) {
$this->pdo->exec($sql); $this->pdo->exec($sql);
@ -434,7 +434,7 @@ class Connection extends \yii\base\ApplicationComponent
*/ */
public function getCurrentTransaction() public function getCurrentTransaction()
{ {
if ($this->_transaction !== null && $this->_transaction->getActive()) { if ($this->_transaction !== null && $this->_transaction->active) {
return $this->_transaction; return $this->_transaction;
} }
} }
@ -459,23 +459,16 @@ class Connection extends \yii\base\ApplicationComponent
{ {
if ($this->_schema !== null) { if ($this->_schema !== null) {
return $this->_schema; return $this->_schema;
} } else {
else {
$driver = $this->getDriverName(); $driver = $this->getDriverName();
if (isset($this->schemaMap[$driver])) { if (isset($this->schemaMap[$driver])) {
return $this->_schema = \Yii::create($this->schemaMap[$driver], $this); return $this->_schema = \Yii::create($this->schemaMap[$driver], $this);
} } else {
else {
throw new Exception("Connection does not support reading schema for '$driver' database."); 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. * Returns the query builder for the current DB connection.
* @return QueryBuilder 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(); $this->open();
if (($value = $this->pdo->quote($str)) !== false) { if (($value = $this->pdo->quote($str)) !== false) {
return $value; 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") . "'"; 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) { if (($pos = strpos($this->dsn, ':')) !== false) {
return strtolower(substr($this->dsn, 0, $pos)); return strtolower(substr($this->dsn, 0, $pos));
} } else {
else {
return strtolower($this->getAttribute(\PDO::ATTR_DRIVER_NAME)); return strtolower($this->getAttribute(\PDO::ATTR_DRIVER_NAME));
} }
} }

2
framework/db/dao/DataReader.php

@ -35,7 +35,7 @@ use yii\db\Exception;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class DataReader extends \yii\base\Component implements \Iterator, \Countable class DataReader extends \yii\base\Object implements \Iterator, \Countable
{ {
private $_statement; private $_statement;
private $_closed = false; private $_closed = false;

2
framework/db/dao/Expression.php

@ -26,7 +26,7 @@ namespace yii\db\dao;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class Expression class Expression extends \yii\base\Object
{ {
/** /**
* @var string the DB expression * @var string the DB expression

2
framework/db/dao/Query.php

@ -16,7 +16,7 @@ namespace yii\db\dao;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @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 * @var mixed the columns being selected. This refers to the SELECT clause in an SQL

2
framework/db/dao/QueryBuilder.php

@ -18,7 +18,7 @@ use yii\db\Exception;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @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. * @var array the abstract column types mapped to physical column types.

2
framework/db/dao/Schema.php

@ -18,7 +18,7 @@ use yii\db\Exception;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
abstract class Schema extends \yii\base\Component abstract class Schema extends \yii\base\Object
{ {
public $connection; public $connection;

2
framework/db/dao/TableSchema.php

@ -28,7 +28,7 @@ namespace yii\db\dao;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @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. * @var string name of the schema that this table belongs to.

6
framework/db/dao/Transaction.php

@ -36,7 +36,7 @@ use yii\db\Exception;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @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 * @var boolean whether this transaction is active. Only an active transaction
@ -67,7 +67,7 @@ class Transaction extends \yii\base\Component
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', __CLASS__);
$this->connection->pdo->commit(); $this->connection->pdo->commit();
$this->active = false; $this->active = false;
} }
@ -83,7 +83,7 @@ class Transaction extends \yii\base\Component
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', __CLASS__);
$this->connection->pdo->rollBack(); $this->connection->pdo->rollBack();
$this->active = false; $this->active = false;
} }

Loading…
Cancel
Save