Commit abd3d827 by Qiang Xue

refactoring.

parent 7f6a5568
...@@ -39,7 +39,7 @@ use yii\db\Query; ...@@ -39,7 +39,7 @@ use yii\db\Query;
* *
* Please refer to [[Cache]] for common cache operations that are supported by DbCache. * Please refer to [[Cache]] for common cache operations that are supported by DbCache.
* *
* @property Connection $dbConnection The DB connection instance. * @property Connection $db The DB connection instance.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
...@@ -71,7 +71,7 @@ class DbCache extends Cache ...@@ -71,7 +71,7 @@ class DbCache extends Cache
* @return Connection the DB connection instance * @return Connection the DB connection instance
* @throws Exception if [[connectionID]] does not point to a valid application component. * @throws Exception if [[connectionID]] does not point to a valid application component.
*/ */
public function getDbConnection() public function getDb()
{ {
if ($this->_db === null) { if ($this->_db === null) {
$db = \Yii::$application->getComponent($this->connectionID); $db = \Yii::$application->getComponent($this->connectionID);
...@@ -88,7 +88,7 @@ class DbCache extends Cache ...@@ -88,7 +88,7 @@ class DbCache extends Cache
* Sets the DB connection used by the cache component. * Sets the DB connection used by the cache component.
* @param Connection $value the DB connection instance * @param Connection $value the DB connection instance
*/ */
public function setDbConnection($value) public function setDb($value)
{ {
$this->_db = $value; $this->_db = $value;
} }
...@@ -105,7 +105,7 @@ class DbCache extends Cache ...@@ -105,7 +105,7 @@ class DbCache extends Cache
$query->select(array('data')) $query->select(array('data'))
->from($this->cacheTableName) ->from($this->cacheTableName)
->where('id = :id AND (expire = 0 OR expire > :time)', array(':id' => $key, ':time' => time())); ->where('id = :id AND (expire = 0 OR expire > :time)', array(':id' => $key, ':time' => time()));
$db = $this->getDbConnection(); $db = $this->getDb();
if ($db->enableQueryCache) { if ($db->enableQueryCache) {
// temporarily disable and re-enable query caching // temporarily disable and re-enable query caching
$db->enableQueryCache = false; $db->enableQueryCache = false;
...@@ -133,7 +133,7 @@ class DbCache extends Cache ...@@ -133,7 +133,7 @@ class DbCache extends Cache
->where(array('id' => $keys)) ->where(array('id' => $keys))
->andWhere("expire = 0 OR expire > " . time() . ")"); ->andWhere("expire = 0 OR expire > " . time() . ")");
$db = $this->getDbConnection(); $db = $this->getDb();
if ($db->enableQueryCache) { if ($db->enableQueryCache) {
$db->enableQueryCache = false; $db->enableQueryCache = false;
$rows = $query->createCommand($db)->queryAll(); $rows = $query->createCommand($db)->queryAll();
...@@ -169,7 +169,7 @@ class DbCache extends Cache ...@@ -169,7 +169,7 @@ class DbCache extends Cache
'data' => array($value, \PDO::PARAM_LOB), 'data' => array($value, \PDO::PARAM_LOB),
), array( ), array(
'id' => $key, 'id' => $key,
))->createCommand($this->getDbConnection()); ))->createCommand($this->getDb());
if ($command->execute()) { if ($command->execute()) {
$this->gc(); $this->gc();
...@@ -203,7 +203,7 @@ class DbCache extends Cache ...@@ -203,7 +203,7 @@ class DbCache extends Cache
'id' => $key, 'id' => $key,
'expire' => $expire, 'expire' => $expire,
'data' => array($value, \PDO::PARAM_LOB), 'data' => array($value, \PDO::PARAM_LOB),
))->createCommand($this->getDbConnection()); ))->createCommand($this->getDb());
try { try {
$command->execute(); $command->execute();
return true; return true;
...@@ -222,7 +222,7 @@ class DbCache extends Cache ...@@ -222,7 +222,7 @@ class DbCache extends Cache
{ {
$query = new Query; $query = new Query;
$query->delete($this->cacheTableName, array('id' => $key)) $query->delete($this->cacheTableName, array('id' => $key))
->createCommand($this->getDbConnection()) ->createCommand($this->getDb())
->execute(); ->execute();
return true; return true;
} }
...@@ -237,7 +237,7 @@ class DbCache extends Cache ...@@ -237,7 +237,7 @@ class DbCache extends Cache
if ($force || mt_rand(0, 1000000) < $this->gcProbability) { if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
$query = new Query; $query = new Query;
$query->delete($this->cacheTableName, 'expire > 0 AND expire < ' . time()) $query->delete($this->cacheTableName, 'expire > 0 AND expire < ' . time())
->createCommand($this->getDbConnection()) ->createCommand($this->getDb())
->execute(); ->execute();
} }
} }
...@@ -251,7 +251,7 @@ class DbCache extends Cache ...@@ -251,7 +251,7 @@ class DbCache extends Cache
{ {
$query = new Query; $query = new Query;
$query->delete($this->cacheTableName) $query->delete($this->cacheTableName)
->createCommand($this->getDbConnection()) ->createCommand($this->getDb())
->execute(); ->execute();
return true; return true;
} }
......
...@@ -67,7 +67,7 @@ class DbDependency extends Dependency ...@@ -67,7 +67,7 @@ class DbDependency extends Dependency
*/ */
protected function generateDependencyData() protected function generateDependencyData()
{ {
$db = $this->getDbConnection(); $db = $this->getDb();
$command = $this->query->createCommand($db); $command = $this->query->createCommand($db);
if ($db->enableQueryCache) { if ($db->enableQueryCache) {
// temporarily disable and re-enable query caching // temporarily disable and re-enable query caching
...@@ -85,7 +85,7 @@ class DbDependency extends Dependency ...@@ -85,7 +85,7 @@ class DbDependency extends Dependency
* @return Connection the DB connection instance * @return Connection the DB connection instance
* @throws Exception if [[connectionID]] does not point to a valid application component. * @throws Exception if [[connectionID]] does not point to a valid application component.
*/ */
public function getDbConnection() public function getDb()
{ {
if ($this->_db === null) { if ($this->_db === null) {
$db = \Yii::$application->getComponent($this->connectionID); $db = \Yii::$application->getComponent($this->connectionID);
...@@ -102,7 +102,7 @@ class DbDependency extends Dependency ...@@ -102,7 +102,7 @@ class DbDependency extends Dependency
* Sets the DB connection used by the cache component. * Sets the DB connection used by the cache component.
* @param Connection $value the DB connection instance * @param Connection $value the DB connection instance
*/ */
public function setDbConnection($value) public function setDb($value)
{ {
$this->_db = $value; $this->_db = $value;
} }
......
...@@ -278,7 +278,7 @@ class MigrateController extends Controller ...@@ -278,7 +278,7 @@ class MigrateController extends Controller
else else
die("Error: The version option must be either a timestamp (e.g. 101129_185401)\nor the full name of a migration (e.g. m101129_185401_create_user_table).\n"); die("Error: The version option must be either a timestamp (e.g. 101129_185401)\nor the full name of a migration (e.g. m101129_185401_create_user_table).\n");
$db=$this->getDbConnection(); $db=$this->getDb();
// try mark up // try mark up
$migrations=$this->getNewMigrations(); $migrations=$this->getNewMigrations();
...@@ -405,7 +405,7 @@ class MigrateController extends Controller ...@@ -405,7 +405,7 @@ class MigrateController extends Controller
$migration=$this->instantiateMigration($class); $migration=$this->instantiateMigration($class);
if($migration->up()!==false) if($migration->up()!==false)
{ {
$this->getDbConnection()->createCommand()->insert($this->migrationTable, array( $this->getDb()->createCommand()->insert($this->migrationTable, array(
'version'=>$class, 'version'=>$class,
'apply_time'=>time(), 'apply_time'=>time(),
)); ));
...@@ -430,7 +430,7 @@ class MigrateController extends Controller ...@@ -430,7 +430,7 @@ class MigrateController extends Controller
$migration=$this->instantiateMigration($class); $migration=$this->instantiateMigration($class);
if($migration->down()!==false) if($migration->down()!==false)
{ {
$db=$this->getDbConnection(); $db=$this->getDb();
$db->createCommand()->delete($this->migrationTable, $db->quoteColumnName('version').'=:version', array(':version'=>$class)); $db->createCommand()->delete($this->migrationTable, $db->quoteColumnName('version').'=:version', array(':version'=>$class));
$time=microtime(true)-$start; $time=microtime(true)-$start;
echo "*** reverted $class (time: ".sprintf("%.3f",$time)."s)\n\n"; echo "*** reverted $class (time: ".sprintf("%.3f",$time)."s)\n\n";
...@@ -448,7 +448,7 @@ class MigrateController extends Controller ...@@ -448,7 +448,7 @@ class MigrateController extends Controller
$file=$this->migrationPath.DIRECTORY_SEPARATOR.$class.'.php'; $file=$this->migrationPath.DIRECTORY_SEPARATOR.$class.'.php';
require_once($file); require_once($file);
$migration=new $class; $migration=new $class;
$migration->setDbConnection($this->getDbConnection()); $migration->setDb($this->getDb());
return $migration; return $migration;
} }
...@@ -456,7 +456,7 @@ class MigrateController extends Controller ...@@ -456,7 +456,7 @@ class MigrateController extends Controller
* @var CDbConnection * @var CDbConnection
*/ */
private $_db; private $_db;
protected function getDbConnection() protected function getDb()
{ {
if($this->_db!==null) if($this->_db!==null)
return $this->_db; return $this->_db;
...@@ -468,7 +468,7 @@ class MigrateController extends Controller ...@@ -468,7 +468,7 @@ class MigrateController extends Controller
protected function getMigrationHistory($limit) protected function getMigrationHistory($limit)
{ {
$db=$this->getDbConnection(); $db=$this->getDb();
if($db->schema->getTable($this->migrationTable)===null) if($db->schema->getTable($this->migrationTable)===null)
{ {
$this->createMigrationHistoryTable(); $this->createMigrationHistoryTable();
...@@ -483,7 +483,7 @@ class MigrateController extends Controller ...@@ -483,7 +483,7 @@ class MigrateController extends Controller
protected function createMigrationHistoryTable() protected function createMigrationHistoryTable()
{ {
$db=$this->getDbConnection(); $db=$this->getDb();
echo 'Creating migration history table "'.$this->migrationTable.'"...'; echo 'Creating migration history table "'.$this->migrationTable.'"...';
$db->createCommand()->createTable($this->migrationTable,array( $db->createCommand()->createTable($this->migrationTable,array(
'version'=>'string NOT NULL PRIMARY KEY', 'version'=>'string NOT NULL PRIMARY KEY',
......
...@@ -232,7 +232,7 @@ class ActiveQuery extends Query ...@@ -232,7 +232,7 @@ class ActiveQuery extends Query
/** @var $modelClass ActiveRecord */ /** @var $modelClass ActiveRecord */
$modelClass = $this->modelClass; $modelClass = $this->modelClass;
if ($db === null) { if ($db === null) {
$db = $modelClass::getDbConnection(); $db = $modelClass::getDb();
} }
if ($this->sql === null) { if ($this->sql === null) {
if ($this->from === null) { if ($this->from === null) {
......
...@@ -24,7 +24,7 @@ use yii\util\StringHelper; ...@@ -24,7 +24,7 @@ use yii\util\StringHelper;
* *
* @include @yii/db/ActiveRecord.md * @include @yii/db/ActiveRecord.md
* *
* @property Connection $dbConnection the database connection used by this AR class. * @property Connection $db the database connection used by this AR class.
* @property TableSchema $tableSchema the schema information of the DB table associated with this AR class. * @property TableSchema $tableSchema the schema information of the DB table associated with this AR class.
* @property array $oldAttributes the old attribute values (name-value pairs). * @property array $oldAttributes the old attribute values (name-value pairs).
* @property array $dirtyAttributes the changed attribute values (name-value pairs). * @property array $dirtyAttributes the changed attribute values (name-value pairs).
...@@ -69,7 +69,7 @@ class ActiveRecord extends Model ...@@ -69,7 +69,7 @@ class ActiveRecord extends Model
* You may override this method if you want to use a different database connection. * You may override this method if you want to use a different database connection.
* @return Connection the database connection used by this AR class. * @return Connection the database connection used by this AR class.
*/ */
public static function getDbConnection() public static function getDb()
{ {
return \Yii::$application->getDb(); return \Yii::$application->getDb();
} }
...@@ -145,7 +145,7 @@ class ActiveRecord extends Model ...@@ -145,7 +145,7 @@ class ActiveRecord extends Model
*/ */
public static function updateAll($attributes, $condition = '', $params = array()) public static function updateAll($attributes, $condition = '', $params = array())
{ {
$command = static::getDbConnection()->createCommand(); $command = static::getDb()->createCommand();
$command->update(static::tableName(), $attributes, $condition, $params); $command->update(static::tableName(), $attributes, $condition, $params);
return $command->execute(); return $command->execute();
} }
...@@ -168,7 +168,7 @@ class ActiveRecord extends Model ...@@ -168,7 +168,7 @@ class ActiveRecord extends Model
*/ */
public static function updateAllCounters($counters, $condition = '', $params = array()) public static function updateAllCounters($counters, $condition = '', $params = array())
{ {
$db = static::getDbConnection(); $db = static::getDb();
$n = 0; $n = 0;
foreach ($counters as $name => $value) { foreach ($counters as $name => $value) {
$quotedName = $db->quoteColumnName($name); $quotedName = $db->quoteColumnName($name);
...@@ -198,7 +198,7 @@ class ActiveRecord extends Model ...@@ -198,7 +198,7 @@ class ActiveRecord extends Model
*/ */
public static function deleteAll($condition = '', $params = array()) public static function deleteAll($condition = '', $params = array())
{ {
$command = static::getDbConnection()->createCommand(); $command = static::getDb()->createCommand();
$command->delete(static::tableName(), $condition, $params); $command->delete(static::tableName(), $condition, $params);
return $command->execute(); return $command->execute();
} }
...@@ -235,7 +235,7 @@ class ActiveRecord extends Model ...@@ -235,7 +235,7 @@ class ActiveRecord extends Model
*/ */
public static function getTableSchema() public static function getTableSchema()
{ {
return static::getDbConnection()->getTableSchema(static::tableName()); return static::getDb()->getTableSchema(static::tableName());
} }
/** /**
...@@ -618,7 +618,7 @@ class ActiveRecord extends Model ...@@ -618,7 +618,7 @@ class ActiveRecord extends Model
$values[$key] = isset($this->_attributes[$key]) ? $this->_attributes[$key] : null; $values[$key] = isset($this->_attributes[$key]) ? $this->_attributes[$key] : null;
} }
} }
$db = static::getDbConnection(); $db = static::getDb();
$command = $db->createCommand()->insert($this->tableName(), $values); $command = $db->createCommand()->insert($this->tableName(), $values);
if ($command->execute()) { if ($command->execute()) {
$table = $this->getTableSchema(); $table = $this->getTableSchema();
...@@ -1079,7 +1079,7 @@ class ActiveRecord extends Model ...@@ -1079,7 +1079,7 @@ class ActiveRecord extends Model
foreach ($extraColumns as $k => $v) { foreach ($extraColumns as $k => $v) {
$columns[$k] = $v; $columns[$k] = $v;
} }
static::getDbConnection()->createCommand() static::getDb()->createCommand()
->insert($viaTable, $columns)->execute(); ->insert($viaTable, $columns)->execute();
} else { } else {
$p1 = $model->isPrimaryKey(array_keys($relation->link)); $p1 = $model->isPrimaryKey(array_keys($relation->link));
...@@ -1150,7 +1150,7 @@ class ActiveRecord extends Model ...@@ -1150,7 +1150,7 @@ class ActiveRecord extends Model
foreach ($relation->link as $a => $b) { foreach ($relation->link as $a => $b) {
$columns[$b] = $model->$a; $columns[$b] = $model->$a;
} }
$command = static::getDbConnection()->createCommand(); $command = static::getDb()->createCommand();
if ($delete) { if ($delete) {
$command->delete($viaTable, $columns)->execute(); $command->delete($viaTable, $columns)->execute();
} else { } else {
......
...@@ -299,7 +299,7 @@ class ActiveRelation extends ActiveQuery ...@@ -299,7 +299,7 @@ class ActiveRelation extends ActiveQuery
$this->filterByModels($primaryModels); $this->filterByModels($primaryModels);
/** @var $primaryModel ActiveRecord */ /** @var $primaryModel ActiveRecord */
$primaryModel = reset($primaryModels); $primaryModel = reset($primaryModels);
$db = $primaryModel->getDbConnection(); $db = $primaryModel->getDb();
$sql = $db->getQueryBuilder()->build($this); $sql = $db->getQueryBuilder()->build($this);
return $db->createCommand($sql, $this->params)->queryAll(); return $db->createCommand($sql, $this->params)->queryAll();
} }
......
...@@ -54,7 +54,7 @@ class Command extends \yii\base\Component ...@@ -54,7 +54,7 @@ class Command extends \yii\base\Component
/** /**
* @var Connection the DB connection that this command is associated with * @var Connection the DB connection that this command is associated with
*/ */
public $connection; public $db;
/** /**
* @var \PDOStatement the PDOStatement object that this command is associated with * @var \PDOStatement the PDOStatement object that this command is associated with
*/ */
...@@ -91,7 +91,7 @@ class Command extends \yii\base\Component ...@@ -91,7 +91,7 @@ class Command extends \yii\base\Component
public function setSql($sql) public function setSql($sql)
{ {
if ($sql !== $this->_sql) { if ($sql !== $this->_sql) {
if ($this->connection->enableAutoQuoting && $sql != '') { if ($this->db->enableAutoQuoting && $sql != '') {
$sql = $this->expandSql($sql); $sql = $this->expandSql($sql);
} }
$this->cancel(); $this->cancel();
...@@ -108,12 +108,13 @@ class Command extends \yii\base\Component ...@@ -108,12 +108,13 @@ class Command extends \yii\base\Component
*/ */
protected function expandSql($sql) protected function expandSql($sql)
{ {
return preg_replace_callback('/(\\{\\{(.*?)\\}\\}|\\[\\[(.*?)\\]\\])/', function($matches) { $db = $this->db;
return preg_replace_callback('/(\\{\\{(.*?)\\}\\}|\\[\\[(.*?)\\]\\])/', function($matches) use($db) {
if (isset($matches[3])) { if (isset($matches[3])) {
return $this->connection->quoteColumnName($matches[3]); return $db->quoteColumnName($matches[3]);
} else { } else {
$name = str_replace('%', $this->connection->tablePrefix, $matches[2]); $name = str_replace('%', $db->tablePrefix, $matches[2]);
return $this->connection->quoteTableName($name); return $db->quoteTableName($name);
} }
}, $sql); }, $sql);
} }
...@@ -131,7 +132,7 @@ class Command extends \yii\base\Component ...@@ -131,7 +132,7 @@ class Command extends \yii\base\Component
if ($this->pdoStatement == null) { if ($this->pdoStatement == null) {
$sql = $this->getSql(); $sql = $this->getSql();
try { try {
$this->pdoStatement = $this->connection->pdo->prepare($sql); $this->pdoStatement = $this->db->pdo->prepare($sql);
} catch (\Exception $e) { } catch (\Exception $e) {
\Yii::error($e->getMessage() . "\nFailed to prepare SQL: $sql", __CLASS__); \Yii::error($e->getMessage() . "\nFailed to prepare SQL: $sql", __CLASS__);
$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null; $errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
...@@ -276,7 +277,7 @@ class Command extends \yii\base\Component ...@@ -276,7 +277,7 @@ class Command extends \yii\base\Component
} }
try { try {
if ($this->connection->enableProfiling) { if ($this->db->enableProfiling) {
\Yii::beginProfile(__METHOD__ . "($sql)", __CLASS__); \Yii::beginProfile(__METHOD__ . "($sql)", __CLASS__);
} }
...@@ -288,12 +289,12 @@ class Command extends \yii\base\Component ...@@ -288,12 +289,12 @@ class Command extends \yii\base\Component
} }
$n = $this->pdoStatement->rowCount(); $n = $this->pdoStatement->rowCount();
if ($this->connection->enableProfiling) { if ($this->db->enableProfiling) {
\Yii::endProfile(__METHOD__ . "($sql)", __CLASS__); \Yii::endProfile(__METHOD__ . "($sql)", __CLASS__);
} }
return $n; return $n;
} catch (\Exception $e) { } catch (\Exception $e) {
if ($this->connection->enableProfiling) { if ($this->db->enableProfiling) {
\Yii::endProfile(__METHOD__ . "($sql)", __CLASS__); \Yii::endProfile(__METHOD__ . "($sql)", __CLASS__);
} }
$message = $e->getMessage(); $message = $e->getMessage();
...@@ -400,7 +401,7 @@ class Command extends \yii\base\Component ...@@ -400,7 +401,7 @@ class Command extends \yii\base\Component
*/ */
private function queryInternal($method, $params, $fetchMode = null) private function queryInternal($method, $params, $fetchMode = null)
{ {
$db = $this->connection; $db = $this->db;
$sql = $this->getSql(); $sql = $this->getSql();
$this->_params = array_merge($this->_params, $params); $this->_params = array_merge($this->_params, $params);
if ($this->_params === array()) { if ($this->_params === array()) {
...@@ -489,7 +490,7 @@ class Command extends \yii\base\Component ...@@ -489,7 +490,7 @@ class Command extends \yii\base\Component
*/ */
public function insert($table, $columns, $params = array()) public function insert($table, $columns, $params = array())
{ {
$sql = $this->connection->getQueryBuilder()->insert($table, $columns, $params); $sql = $this->db->getQueryBuilder()->insert($table, $columns, $params);
return $this->setSql($sql)->bindValues($params); return $this->setSql($sql)->bindValues($params);
} }
...@@ -516,7 +517,7 @@ class Command extends \yii\base\Component ...@@ -516,7 +517,7 @@ class Command extends \yii\base\Component
*/ */
public function update($table, $columns, $condition = '', $params = array()) public function update($table, $columns, $condition = '', $params = array())
{ {
$sql = $this->connection->getQueryBuilder()->update($table, $columns, $condition, $params); $sql = $this->db->getQueryBuilder()->update($table, $columns, $condition, $params);
return $this->setSql($sql)->bindValues($params); return $this->setSql($sql)->bindValues($params);
} }
...@@ -540,7 +541,7 @@ class Command extends \yii\base\Component ...@@ -540,7 +541,7 @@ class Command extends \yii\base\Component
*/ */
public function delete($table, $condition = '', $params = array()) public function delete($table, $condition = '', $params = array())
{ {
$sql = $this->connection->getQueryBuilder()->delete($table, $condition); $sql = $this->db->getQueryBuilder()->delete($table, $condition);
return $this->setSql($sql)->bindValues($params); return $this->setSql($sql)->bindValues($params);
} }
...@@ -551,7 +552,7 @@ class Command extends \yii\base\Component ...@@ -551,7 +552,7 @@ class Command extends \yii\base\Component
* The columns in the new table should be specified as name-definition pairs (e.g. 'name'=>'string'), * The columns in the new table should be specified as name-definition pairs (e.g. 'name'=>'string'),
* where name stands for a column name which will be properly quoted by the method, and definition * where name stands for a column name which will be properly quoted by the method, and definition
* stands for the column type which can contain an abstract DB type. * stands for the column type which can contain an abstract DB type.
* The method [[\yii\db\QueryBuilder::getColumnType()]] will be called * The method [[QueryBuilder::getColumnType()]] will be called
* to convert the abstract column types to physical ones. For example, `string` will be converted * to convert the abstract column types to physical ones. For example, `string` will be converted
* as `varchar(255)`, and `string not null` becomes `varchar(255) not null`. * as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
* *
...@@ -565,7 +566,7 @@ class Command extends \yii\base\Component ...@@ -565,7 +566,7 @@ class Command extends \yii\base\Component
*/ */
public function createTable($table, $columns, $options = null) public function createTable($table, $columns, $options = null)
{ {
$sql = $this->connection->getQueryBuilder()->createTable($table, $columns, $options); $sql = $this->db->getQueryBuilder()->createTable($table, $columns, $options);
return $this->setSql($sql); return $this->setSql($sql);
} }
...@@ -577,7 +578,7 @@ class Command extends \yii\base\Component ...@@ -577,7 +578,7 @@ class Command extends \yii\base\Component
*/ */
public function renameTable($table, $newName) public function renameTable($table, $newName)
{ {
$sql = $this->connection->getQueryBuilder()->renameTable($table, $newName); $sql = $this->db->getQueryBuilder()->renameTable($table, $newName);
return $this->setSql($sql); return $this->setSql($sql);
} }
...@@ -588,7 +589,7 @@ class Command extends \yii\base\Component ...@@ -588,7 +589,7 @@ class Command extends \yii\base\Component
*/ */
public function dropTable($table) public function dropTable($table)
{ {
$sql = $this->connection->getQueryBuilder()->dropTable($table); $sql = $this->db->getQueryBuilder()->dropTable($table);
return $this->setSql($sql); return $this->setSql($sql);
} }
...@@ -599,7 +600,7 @@ class Command extends \yii\base\Component ...@@ -599,7 +600,7 @@ class Command extends \yii\base\Component
*/ */
public function truncateTable($table) public function truncateTable($table)
{ {
$sql = $this->connection->getQueryBuilder()->truncateTable($table); $sql = $this->db->getQueryBuilder()->truncateTable($table);
return $this->setSql($sql); return $this->setSql($sql);
} }
...@@ -614,7 +615,7 @@ class Command extends \yii\base\Component ...@@ -614,7 +615,7 @@ class Command extends \yii\base\Component
*/ */
public function addColumn($table, $column, $type) public function addColumn($table, $column, $type)
{ {
$sql = $this->connection->getQueryBuilder()->addColumn($table, $column, $type); $sql = $this->db->getQueryBuilder()->addColumn($table, $column, $type);
return $this->setSql($sql); return $this->setSql($sql);
} }
...@@ -626,7 +627,7 @@ class Command extends \yii\base\Component ...@@ -626,7 +627,7 @@ class Command extends \yii\base\Component
*/ */
public function dropColumn($table, $column) public function dropColumn($table, $column)
{ {
$sql = $this->connection->getQueryBuilder()->dropColumn($table, $column); $sql = $this->db->getQueryBuilder()->dropColumn($table, $column);
return $this->setSql($sql); return $this->setSql($sql);
} }
...@@ -639,7 +640,7 @@ class Command extends \yii\base\Component ...@@ -639,7 +640,7 @@ class Command extends \yii\base\Component
*/ */
public function renameColumn($table, $oldName, $newName) public function renameColumn($table, $oldName, $newName)
{ {
$sql = $this->connection->getQueryBuilder()->renameColumn($table, $oldName, $newName); $sql = $this->db->getQueryBuilder()->renameColumn($table, $oldName, $newName);
return $this->setSql($sql); return $this->setSql($sql);
} }
...@@ -654,7 +655,7 @@ class Command extends \yii\base\Component ...@@ -654,7 +655,7 @@ class Command extends \yii\base\Component
*/ */
public function alterColumn($table, $column, $type) public function alterColumn($table, $column, $type)
{ {
$sql = $this->connection->getQueryBuilder()->alterColumn($table, $column, $type); $sql = $this->db->getQueryBuilder()->alterColumn($table, $column, $type);
return $this->setSql($sql); return $this->setSql($sql);
} }
...@@ -672,7 +673,7 @@ class Command extends \yii\base\Component ...@@ -672,7 +673,7 @@ class Command extends \yii\base\Component
*/ */
public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null) public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
{ {
$sql = $this->connection->getQueryBuilder()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update); $sql = $this->db->getQueryBuilder()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update);
return $this->setSql($sql); return $this->setSql($sql);
} }
...@@ -684,7 +685,7 @@ class Command extends \yii\base\Component ...@@ -684,7 +685,7 @@ class Command extends \yii\base\Component
*/ */
public function dropForeignKey($name, $table) public function dropForeignKey($name, $table)
{ {
$sql = $this->connection->getQueryBuilder()->dropForeignKey($name, $table); $sql = $this->db->getQueryBuilder()->dropForeignKey($name, $table);
return $this->setSql($sql); return $this->setSql($sql);
} }
...@@ -699,7 +700,7 @@ class Command extends \yii\base\Component ...@@ -699,7 +700,7 @@ class Command extends \yii\base\Component
*/ */
public function createIndex($name, $table, $columns, $unique = false) public function createIndex($name, $table, $columns, $unique = false)
{ {
$sql = $this->connection->getQueryBuilder()->createIndex($name, $table, $columns, $unique); $sql = $this->db->getQueryBuilder()->createIndex($name, $table, $columns, $unique);
return $this->setSql($sql); return $this->setSql($sql);
} }
...@@ -711,7 +712,7 @@ class Command extends \yii\base\Component ...@@ -711,7 +712,7 @@ class Command extends \yii\base\Component
*/ */
public function dropIndex($name, $table) public function dropIndex($name, $table)
{ {
$sql = $this->connection->getQueryBuilder()->dropIndex($name, $table); $sql = $this->db->getQueryBuilder()->dropIndex($name, $table);
return $this->setSql($sql); return $this->setSql($sql);
} }
...@@ -727,7 +728,7 @@ class Command extends \yii\base\Component ...@@ -727,7 +728,7 @@ class Command extends \yii\base\Component
*/ */
public function resetSequence($table, $value = null) public function resetSequence($table, $value = null)
{ {
$sql = $this->connection->getQueryBuilder()->resetSequence($table, $value); $sql = $this->db->getQueryBuilder()->resetSequence($table, $value);
return $this->setSql($sql); return $this->setSql($sql);
} }
...@@ -741,7 +742,7 @@ class Command extends \yii\base\Component ...@@ -741,7 +742,7 @@ class Command extends \yii\base\Component
*/ */
public function checkIntegrity($check = true, $schema = '') public function checkIntegrity($check = true, $schema = '')
{ {
$sql = $this->connection->getQueryBuilder()->checkIntegrity($check, $schema); $sql = $this->db->getQueryBuilder()->checkIntegrity($check, $schema);
return $this->setSql($sql); return $this->setSql($sql);
} }
} }
...@@ -395,7 +395,7 @@ class Connection extends \yii\base\ApplicationComponent ...@@ -395,7 +395,7 @@ class Connection extends \yii\base\ApplicationComponent
{ {
$this->open(); $this->open();
$command = new Command(array( $command = new Command(array(
'connection' => $this, 'db' => $this,
'sql' => $sql, 'sql' => $sql,
)); ));
return $command->bindValues($params); return $command->bindValues($params);
...@@ -418,7 +418,7 @@ class Connection extends \yii\base\ApplicationComponent ...@@ -418,7 +418,7 @@ class Connection extends \yii\base\ApplicationComponent
{ {
$this->open(); $this->open();
$this->_transaction = new Transaction(array( $this->_transaction = new Transaction(array(
'connection' => $this, 'db' => $this,
)); ));
$this->_transaction->begin(); $this->_transaction->begin();
return $this->_transaction; return $this->_transaction;
...@@ -437,7 +437,7 @@ class Connection extends \yii\base\ApplicationComponent ...@@ -437,7 +437,7 @@ class Connection extends \yii\base\ApplicationComponent
$driver = $this->getDriverName(); $driver = $this->getDriverName();
if (isset($this->schemaMap[$driver])) { if (isset($this->schemaMap[$driver])) {
$this->_schema = \Yii::createObject($this->schemaMap[$driver]); $this->_schema = \Yii::createObject($this->schemaMap[$driver]);
$this->_schema->connection = $this; $this->_schema->db = $this;
return $this->_schema; return $this->_schema;
} else { } else {
throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS."); throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS.");
......
<?php <?php
/** /**
* CMysqlSchema class file. * Migration class file.
* *
* @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 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
namespace yii\db;
/** /**
* CDbMigration is the base class for representing a database migration. * Migration is the base class for representing a database migration.
* *
* CDbMigration is designed to be used together with the "yiic migrate" command. * Migration is designed to be used together with the "yiic migrate" command.
* *
* Each child class of CDbMigration represents an individual database migration which * Each child class of Migration represents an individual database migration which
* is identified by the child class name. * is identified by the child class name.
* *
* Within each migration, the {@link up} method contains the logic for "upgrading" * Within each migration, the [[up()]] method should be overwritten to contain the logic
* the database used in an application; while the {@link down} method contains "downgrading" * for "upgrading" the database; while the [[down()]] method for the "downgrading"
* logic. The "yiic migrate" command manages all available migrations in an application. * logic. The "yiic migrate" command manages all available migrations in an application.
* *
* CDbMigration provides a set of convenient methods for manipulating database data and schema. * If the database supports transactions, you may also overwrite [[safeUp()]] and
* For example, the {@link insert} method can be used to easily insert a row of data into * [[safeDown()]] so that if anything wrong happens during the upgrading or downgrading,
* a database table; the {@link createTable} method can be used to create a database table. * the whole migration can be reverted in a whole.
* Compared with the same methods in {@link CDbCommand}, these methods will display extra *
* Migration provides a set of convenient methods for manipulating database data and schema.
* For example, the [[insert()]] method can be used to easily insert a row of data into
* a database table; the [[createTable()]] method can be used to create a database table.
* Compared with the same methods in [[Command]], these methods will display extra
* information showing the method parameters and execution time, which may be useful when * information showing the method parameters and execution time, which may be useful when
* applying migrations. * applying migrations.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
abstract class CDbMigration extends yii\base\Component class Migration extends \yii\base\Component
{ {
private $_db; /**
* @var Connection the database connection that this migration should work with.
* If not set, it will be initialized as the 'db' application component.
*/
public $db;
/**
* Initializes the migration.
* This method will set [[db]] to be the 'db' application component, if it is null.
*/
public function init()
{
parent::init();
if ($this->db === null) {
$this->db = \Yii::$application->getComponent('db');
}
}
/** /**
* This method contains the logic to be executed when applying this migration. * This method contains the logic to be executed when applying this migration.
* Child classes may implement this method to provide actual migration logic. * Child classes may overwrite this method to provide actual migration logic.
* @return boolean * @return boolean return a false value to indicate the migration fails
* and should not proceed further. All other return values mean the migration succeeds.
*/ */
public function up() public function up()
{ {
$transaction = $this->getDbConnection()->beginTransaction(); $transaction = $this->db->beginTransaction();
try try {
{
if ($this->safeUp() === false) { if ($this->safeUp() === false) {
$transaction->rollBack(); $transaction->rollBack();
return false; return false;
} }
$transaction->commit(); $transaction->commit();
} } catch (\Exception $e) {
catch (Exception $e)
{
echo "Exception: " . $e->getMessage() . ' (' . $e->getFile() . ':' . $e->getLine() . ")\n"; echo "Exception: " . $e->getMessage() . ' (' . $e->getFile() . ':' . $e->getLine() . ")\n";
echo $e->getTraceAsString() . "\n"; echo $e->getTraceAsString() . "\n";
$transaction->rollBack(); $transaction->rollBack();
return false; return false;
} }
return null;
} }
/** /**
* This method contains the logic to be executed when removing this migration. * This method contains the logic to be executed when removing this migration.
* The default implementation throws an exception indicating the migration cannot be removed. * The default implementation throws an exception indicating the migration cannot be removed.
* Child classes may override this method if the corresponding migrations can be removed. * Child classes may override this method if the corresponding migrations can be removed.
* @return boolean * @return boolean return a false value to indicate the migration fails
* and should not proceed further. All other return values mean the migration succeeds.
*/ */
public function down() public function down()
{ {
$transaction = $this->getDbConnection()->beginTransaction(); $transaction = $this->db->beginTransaction();
try try {
{
if ($this->safeDown() === false) { if ($this->safeDown() === false) {
$transaction->rollBack(); $transaction->rollBack();
return false; return false;
} }
$transaction->commit(); $transaction->commit();
} } catch (\Exception $e) {
catch (Exception $e)
{
echo "Exception: " . $e->getMessage() . ' (' . $e->getFile() . ':' . $e->getLine() . ")\n"; echo "Exception: " . $e->getMessage() . ' (' . $e->getFile() . ':' . $e->getLine() . ")\n";
echo $e->getTraceAsString() . "\n"; echo $e->getTraceAsString() . "\n";
$transaction->rollBack(); $transaction->rollBack();
return false; return false;
} }
return null;
} }
/** /**
* This method contains the logic to be executed when applying this migration. * This method contains the logic to be executed when applying this migration.
* This method differs from {@link up} in that the DB logic implemented here will * This method differs from [[up()]] in that the DB logic implemented here will
* be enclosed within a DB transaction. * be enclosed within a DB transaction.
* Child classes may implement this method instead of {@link up} if the DB logic * Child classes may implement this method instead of [[up()]] if the DB logic
* needs to be within a transaction. * needs to be within a transaction.
* @return boolean * @return boolean return a false value to indicate the migration fails
* and should not proceed further. All other return values mean the migration succeeds.
*/ */
public function safeUp() public function safeUp()
{ {
...@@ -99,55 +119,28 @@ abstract class CDbMigration extends yii\base\Component ...@@ -99,55 +119,28 @@ abstract class CDbMigration extends yii\base\Component
/** /**
* This method contains the logic to be executed when removing this migration. * This method contains the logic to be executed when removing this migration.
* This method differs from {@link down} in that the DB logic implemented here will * This method differs from [[down()]] in that the DB logic implemented here will
* be enclosed within a DB transaction. * be enclosed within a DB transaction.
* Child classes may implement this method instead of {@link up} if the DB logic * Child classes may implement this method instead of [[up()]] if the DB logic
* needs to be within a transaction. * needs to be within a transaction.
* @return boolean * @return boolean return a false value to indicate the migration fails
* and should not proceed further. All other return values mean the migration succeeds.
*/ */
public function safeDown() public function safeDown()
{ {
} }
/** /**
* Returns the currently active database connection.
* By default, the 'db' application component will be returned and activated.
* You can call {@link setDbConnection} to switch to a different database connection.
* Methods such as {@link insert}, {@link createTable} will use this database connection
* to perform DB queries.
* @return CDbConnection the currently active database connection
*/
public function getDbConnection()
{
if ($this->_db === null) {
$this->_db = \Yii::$application->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.'));
}
return $this->_db;
}
/**
* Sets the currently active database connection.
* The database connection will be used by the methods such as {@link insert}, {@link createTable}.
* @param CDbConnection $db the database connection component
*/
public function setDbConnection($db)
{
$this->_db = $db;
}
/**
* Executes a SQL statement. * Executes a SQL statement.
* This method executes the specified SQL statement using {@link dbConnection}. * This method executes the specified SQL statement using [[db]].
* @param string $sql the SQL statement to be executed * @param string $sql the SQL statement to be executed
* @param array $params input parameters (name=>value) for the SQL execution. See {@link CDbCommand::execute} for more details. * @param array $params input parameters (name=>value) for the SQL execution. See [[Command::execute()]] for more details.
*/ */
public function execute($sql, $params = array()) public function execute($sql, $params = array())
{ {
echo " > execute SQL: $sql ..."; echo " > execute SQL: $sql ...";
$time = microtime(true); $time = microtime(true);
$this->getDbConnection()->createCommand($sql)->execute($params); $this->db->createCommand($sql)->execute($params);
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n"; echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
} }
...@@ -161,7 +154,7 @@ abstract class CDbMigration extends yii\base\Component ...@@ -161,7 +154,7 @@ abstract class CDbMigration extends yii\base\Component
{ {
echo " > insert into $table ..."; echo " > insert into $table ...";
$time = microtime(true); $time = microtime(true);
$this->getDbConnection()->createCommand()->insert($table, $columns); $this->db->createCommand()->insert($table, $columns)->execute();
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n"; echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
} }
...@@ -170,30 +163,30 @@ abstract class CDbMigration extends yii\base\Component ...@@ -170,30 +163,30 @@ abstract class CDbMigration extends yii\base\Component
* The method will properly escape the column names and bind the values to be updated. * The method will properly escape the column names and bind the values to be updated.
* @param string $table the table to be updated. * @param string $table the table to be updated.
* @param array $columns the column data (name=>value) to be updated. * @param array $columns the column data (name=>value) to be updated.
* @param mixed $conditions the conditions that will be put in the WHERE part. Please * @param mixed $condition the conditions that will be put in the WHERE part. Please
* refer to {@link CDbCommand::where} on how to specify conditions. * refer to [[Query::where()]] on how to specify conditions.
* @param array $params the parameters to be bound to the query. * @param array $params the parameters to be bound to the query.
*/ */
public function update($table, $columns, $conditions = '', $params = array()) public function update($table, $columns, $condition = '', $params = array())
{ {
echo " > update $table ..."; echo " > update $table ...";
$time = microtime(true); $time = microtime(true);
$this->getDbConnection()->createCommand()->update($table, $columns, $conditions, $params); $this->db->createCommand()->update($table, $columns, $condition, $params)->execute();
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n"; echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
} }
/** /**
* Creates and executes a DELETE SQL statement. * Creates and executes a DELETE SQL statement.
* @param string $table the table where the data will be deleted from. * @param string $table the table where the data will be deleted from.
* @param mixed $conditions the conditions that will be put in the WHERE part. Please * @param mixed $condition the conditions that will be put in the WHERE part. Please
* refer to {@link CDbCommand::where} on how to specify conditions. * refer to [[Query::where()]] on how to specify conditions.
* @param array $params the parameters to be bound to the query. * @param array $params the parameters to be bound to the query.
*/ */
public function delete($table, $conditions = '', $params = array()) public function delete($table, $condition = '', $params = array())
{ {
echo " > delete from $table ..."; echo " > delete from $table ...";
$time = microtime(true); $time = microtime(true);
$this->getDbConnection()->createCommand()->delete($table, $conditions, $params); $this->db->createCommand()->delete($table, $condition, $params)->execute();
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n"; echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
} }
...@@ -203,10 +196,11 @@ abstract class CDbMigration extends yii\base\Component ...@@ -203,10 +196,11 @@ abstract class CDbMigration extends yii\base\Component
* The columns in the new table should be specified as name-definition pairs (e.g. 'name'=>'string'), * The columns in the new table should be specified as name-definition pairs (e.g. 'name'=>'string'),
* where name stands for a column name which will be properly quoted by the method, and definition * where name stands for a column name which will be properly quoted by the method, and definition
* stands for the column type which can contain an abstract DB type. * stands for the column type which can contain an abstract DB type.
* The {@link getColumnType} method will be invoked to convert any abstract type into a physical one. *
* The [[QueryBuilder::getColumnType()]] method will be invoked to convert any abstract type into a physical one.
* *
* If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
* inserted into the generated SQL. * put into the generated SQL.
* *
* @param string $table the name of the table to be created. The name will be properly quoted by the method. * @param string $table the name of the table to be created. The name will be properly quoted by the method.
* @param array $columns the columns (name=>definition) in the new table. * @param array $columns the columns (name=>definition) in the new table.
...@@ -216,7 +210,7 @@ abstract class CDbMigration extends yii\base\Component ...@@ -216,7 +210,7 @@ abstract class CDbMigration extends yii\base\Component
{ {
echo " > create table $table ..."; echo " > create table $table ...";
$time = microtime(true); $time = microtime(true);
$this->getDbConnection()->createCommand()->createTable($table, $columns, $options); $this->db->createCommand()->createTable($table, $columns, $options)->execute();
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n"; echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
} }
...@@ -229,7 +223,7 @@ abstract class CDbMigration extends yii\base\Component ...@@ -229,7 +223,7 @@ abstract class CDbMigration extends yii\base\Component
{ {
echo " > rename table $table to $newName ..."; echo " > rename table $table to $newName ...";
$time = microtime(true); $time = microtime(true);
$this->getDbConnection()->createCommand()->renameTable($table, $newName); $this->db->createCommand()->renameTable($table, $newName)->execute();
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n"; echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
} }
...@@ -241,7 +235,7 @@ abstract class CDbMigration extends yii\base\Component ...@@ -241,7 +235,7 @@ abstract class CDbMigration extends yii\base\Component
{ {
echo " > drop table $table ..."; echo " > drop table $table ...";
$time = microtime(true); $time = microtime(true);
$this->getDbConnection()->createCommand()->dropTable($table); $this->db->createCommand()->dropTable($table)->execute();
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n"; echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
} }
...@@ -253,7 +247,7 @@ abstract class CDbMigration extends yii\base\Component ...@@ -253,7 +247,7 @@ abstract class CDbMigration extends yii\base\Component
{ {
echo " > truncate table $table ..."; echo " > truncate table $table ...";
$time = microtime(true); $time = microtime(true);
$this->getDbConnection()->createCommand()->truncateTable($table); $this->db->createCommand()->truncateTable($table)->execute();
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n"; echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
} }
...@@ -261,7 +255,7 @@ abstract class CDbMigration extends yii\base\Component ...@@ -261,7 +255,7 @@ abstract class CDbMigration extends yii\base\Component
* Builds and executes a SQL statement for adding a new DB column. * Builds and executes a SQL statement for adding a new DB column.
* @param string $table the table that the new column will be added to. The table name will be properly quoted by the method. * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
* @param string $column the name of the new column. The name will be properly quoted by the method. * @param string $column the name of the new column. The name will be properly quoted by the method.
* @param string $type the column type. The {@link getColumnType} method will be invoked to convert abstract column type (if any) * @param string $type the column type. The [[QueryBuilder::getColumnType()]] method will be invoked to convert abstract column type (if any)
* into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL. * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
* For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'. * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
*/ */
...@@ -269,7 +263,7 @@ abstract class CDbMigration extends yii\base\Component ...@@ -269,7 +263,7 @@ abstract class CDbMigration extends yii\base\Component
{ {
echo " > add column $column $type to table $table ..."; echo " > add column $column $type to table $table ...";
$time = microtime(true); $time = microtime(true);
$this->getDbConnection()->createCommand()->addColumn($table, $column, $type); $this->db->createCommand()->addColumn($table, $column, $type)->execute();
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n"; echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
} }
...@@ -282,7 +276,7 @@ abstract class CDbMigration extends yii\base\Component ...@@ -282,7 +276,7 @@ abstract class CDbMigration extends yii\base\Component
{ {
echo " > drop column $column from table $table ..."; echo " > drop column $column from table $table ...";
$time = microtime(true); $time = microtime(true);
$this->getDbConnection()->createCommand()->dropColumn($table, $column); $this->db->createCommand()->dropColumn($table, $column)->execute();
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n"; echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
} }
...@@ -296,7 +290,7 @@ abstract class CDbMigration extends yii\base\Component ...@@ -296,7 +290,7 @@ abstract class CDbMigration extends yii\base\Component
{ {
echo " > rename column $name in table $table to $newName ..."; echo " > rename column $name in table $table to $newName ...";
$time = microtime(true); $time = microtime(true);
$this->getDbConnection()->createCommand()->renameColumn($table, $name, $newName); $this->db->createCommand()->renameColumn($table, $name, $newName)->execute();
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n"; echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
} }
...@@ -312,7 +306,7 @@ abstract class CDbMigration extends yii\base\Component ...@@ -312,7 +306,7 @@ abstract class CDbMigration extends yii\base\Component
{ {
echo " > alter column $column in table $table to $type ..."; echo " > alter column $column in table $table to $type ...";
$time = microtime(true); $time = microtime(true);
$this->getDbConnection()->createCommand()->alterColumn($table, $column, $type); $this->db->createCommand()->alterColumn($table, $column, $type)->execute();
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n"; echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
} }
...@@ -331,7 +325,7 @@ abstract class CDbMigration extends yii\base\Component ...@@ -331,7 +325,7 @@ abstract class CDbMigration extends yii\base\Component
{ {
echo " > add foreign key $name: $table ($columns) references $refTable ($refColumns) ..."; echo " > add foreign key $name: $table ($columns) references $refTable ($refColumns) ...";
$time = microtime(true); $time = microtime(true);
$this->getDbConnection()->createCommand()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update); $this->db->createCommand()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update)->execute();
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n"; echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
} }
...@@ -344,7 +338,7 @@ abstract class CDbMigration extends yii\base\Component ...@@ -344,7 +338,7 @@ abstract class CDbMigration extends yii\base\Component
{ {
echo " > drop foreign key $name from table $table ..."; echo " > drop foreign key $name from table $table ...";
$time = microtime(true); $time = microtime(true);
$this->getDbConnection()->createCommand()->dropForeignKey($name, $table); $this->db->createCommand()->dropForeignKey($name, $table)->execute();
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n"; echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
} }
...@@ -360,7 +354,7 @@ abstract class CDbMigration extends yii\base\Component ...@@ -360,7 +354,7 @@ abstract class CDbMigration extends yii\base\Component
{ {
echo " > create" . ($unique ? ' unique' : '') . " index $name on $table ($column) ..."; echo " > create" . ($unique ? ' unique' : '') . " index $name on $table ($column) ...";
$time = microtime(true); $time = microtime(true);
$this->getDbConnection()->createCommand()->createIndex($name, $table, $column, $unique); $this->db->createCommand()->createIndex($name, $table, $column, $unique)->execute();
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n"; echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
} }
...@@ -373,7 +367,7 @@ abstract class CDbMigration extends yii\base\Component ...@@ -373,7 +367,7 @@ abstract class CDbMigration extends yii\base\Component
{ {
echo " > drop index $name ..."; echo " > drop index $name ...";
$time = microtime(true); $time = microtime(true);
$this->getDbConnection()->createCommand()->dropIndex($name, $table); $this->db->createCommand()->dropIndex($name, $table)->execute();
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n"; echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
} }
} }
\ No newline at end of file
...@@ -26,7 +26,7 @@ class QueryBuilder extends \yii\base\Object ...@@ -26,7 +26,7 @@ class QueryBuilder extends \yii\base\Object
/** /**
* @var Connection the database connection. * @var Connection the database connection.
*/ */
public $connection; public $db;
/** /**
* @var string the separator between different fragments of a SQL statement. * @var string the separator between different fragments of a SQL statement.
* Defaults to an empty space. This is mainly used by [[build()]] when generating a SQL statement. * Defaults to an empty space. This is mainly used by [[build()]] when generating a SQL statement.
...@@ -46,7 +46,7 @@ class QueryBuilder extends \yii\base\Object ...@@ -46,7 +46,7 @@ class QueryBuilder extends \yii\base\Object
*/ */
public function __construct($connection, $config = array()) public function __construct($connection, $config = array())
{ {
$this->connection = $connection; $this->db = $connection;
parent::__construct($config); parent::__construct($config);
} }
...@@ -96,7 +96,7 @@ class QueryBuilder extends \yii\base\Object ...@@ -96,7 +96,7 @@ class QueryBuilder extends \yii\base\Object
$placeholders = array(); $placeholders = array();
$count = 0; $count = 0;
foreach ($columns as $name => $value) { foreach ($columns as $name => $value) {
$names[] = $this->connection->quoteColumnName($name); $names[] = $this->db->quoteColumnName($name);
if ($value instanceof Expression) { if ($value instanceof Expression) {
$placeholders[] = $value->expression; $placeholders[] = $value->expression;
foreach ($value->params as $n => $v) { foreach ($value->params as $n => $v) {
...@@ -109,7 +109,7 @@ class QueryBuilder extends \yii\base\Object ...@@ -109,7 +109,7 @@ class QueryBuilder extends \yii\base\Object
} }
} }
return 'INSERT INTO ' . $this->connection->quoteTableName($table) return 'INSERT INTO ' . $this->db->quoteTableName($table)
. ' (' . implode(', ', $names) . ') VALUES (' . ' (' . implode(', ', $names) . ') VALUES ('
. implode(', ', $placeholders) . ')'; . implode(', ', $placeholders) . ')';
} }
...@@ -141,17 +141,17 @@ class QueryBuilder extends \yii\base\Object ...@@ -141,17 +141,17 @@ class QueryBuilder extends \yii\base\Object
$count = 0; $count = 0;
foreach ($columns as $name => $value) { foreach ($columns as $name => $value) {
if ($value instanceof Expression) { if ($value instanceof Expression) {
$lines[] = $this->connection->quoteColumnName($name) . '=' . $value->expression; $lines[] = $this->db->quoteColumnName($name) . '=' . $value->expression;
foreach ($value->params as $n => $v) { foreach ($value->params as $n => $v) {
$params[$n] = $v; $params[$n] = $v;
} }
} else { } else {
$lines[] = $this->connection->quoteColumnName($name) . '=:p' . $count; $lines[] = $this->db->quoteColumnName($name) . '=:p' . $count;
$params[':p' . $count] = $value; $params[':p' . $count] = $value;
$count++; $count++;
} }
} }
$sql = 'UPDATE ' . $this->connection->quoteTableName($table) . ' SET ' . implode(', ', $lines); $sql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $lines);
if (($where = $this->buildCondition($condition)) !== '') { if (($where = $this->buildCondition($condition)) !== '') {
$sql .= ' WHERE ' . $where; $sql .= ' WHERE ' . $where;
} }
...@@ -176,7 +176,7 @@ class QueryBuilder extends \yii\base\Object ...@@ -176,7 +176,7 @@ class QueryBuilder extends \yii\base\Object
*/ */
public function delete($table, $condition = '') public function delete($table, $condition = '')
{ {
$sql = 'DELETE FROM ' . $this->connection->quoteTableName($table); $sql = 'DELETE FROM ' . $this->db->quoteTableName($table);
if (($where = $this->buildCondition($condition)) !== '') { if (($where = $this->buildCondition($condition)) !== '') {
$sql .= ' WHERE ' . $where; $sql .= ' WHERE ' . $where;
} }
...@@ -214,12 +214,12 @@ class QueryBuilder extends \yii\base\Object ...@@ -214,12 +214,12 @@ class QueryBuilder extends \yii\base\Object
$cols = array(); $cols = array();
foreach ($columns as $name => $type) { foreach ($columns as $name => $type) {
if (is_string($name)) { if (is_string($name)) {
$cols[] = "\t" . $this->connection->quoteColumnName($name) . ' ' . $this->getColumnType($type); $cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type);
} else { } else {
$cols[] = "\t" . $type; $cols[] = "\t" . $type;
} }
} }
$sql = "CREATE TABLE " . $this->connection->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)"; $sql = "CREATE TABLE " . $this->db->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)";
return $options === null ? $sql : $sql . ' ' . $options; return $options === null ? $sql : $sql . ' ' . $options;
} }
...@@ -231,7 +231,7 @@ class QueryBuilder extends \yii\base\Object ...@@ -231,7 +231,7 @@ class QueryBuilder extends \yii\base\Object
*/ */
public function renameTable($oldName, $newName) public function renameTable($oldName, $newName)
{ {
return 'RENAME TABLE ' . $this->connection->quoteTableName($oldName) . ' TO ' . $this->connection->quoteTableName($newName); return 'RENAME TABLE ' . $this->db->quoteTableName($oldName) . ' TO ' . $this->db->quoteTableName($newName);
} }
/** /**
...@@ -241,7 +241,7 @@ class QueryBuilder extends \yii\base\Object ...@@ -241,7 +241,7 @@ class QueryBuilder extends \yii\base\Object
*/ */
public function dropTable($table) public function dropTable($table)
{ {
return "DROP TABLE " . $this->connection->quoteTableName($table); return "DROP TABLE " . $this->db->quoteTableName($table);
} }
/** /**
...@@ -251,7 +251,7 @@ class QueryBuilder extends \yii\base\Object ...@@ -251,7 +251,7 @@ class QueryBuilder extends \yii\base\Object
*/ */
public function truncateTable($table) public function truncateTable($table)
{ {
return "TRUNCATE TABLE " . $this->connection->quoteTableName($table); return "TRUNCATE TABLE " . $this->db->quoteTableName($table);
} }
/** /**
...@@ -265,8 +265,8 @@ class QueryBuilder extends \yii\base\Object ...@@ -265,8 +265,8 @@ class QueryBuilder extends \yii\base\Object
*/ */
public function addColumn($table, $column, $type) public function addColumn($table, $column, $type)
{ {
return 'ALTER TABLE ' . $this->connection->quoteTableName($table) return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' ADD ' . $this->connection->quoteColumnName($column) . ' ' . ' ADD ' . $this->db->quoteColumnName($column) . ' '
. $this->getColumnType($type); . $this->getColumnType($type);
} }
...@@ -278,8 +278,8 @@ class QueryBuilder extends \yii\base\Object ...@@ -278,8 +278,8 @@ class QueryBuilder extends \yii\base\Object
*/ */
public function dropColumn($table, $column) public function dropColumn($table, $column)
{ {
return "ALTER TABLE " . $this->connection->quoteTableName($table) return "ALTER TABLE " . $this->db->quoteTableName($table)
. " DROP COLUMN " . $this->connection->quoteColumnName($column); . " DROP COLUMN " . $this->db->quoteColumnName($column);
} }
/** /**
...@@ -291,9 +291,9 @@ class QueryBuilder extends \yii\base\Object ...@@ -291,9 +291,9 @@ class QueryBuilder extends \yii\base\Object
*/ */
public function renameColumn($table, $oldName, $newName) public function renameColumn($table, $oldName, $newName)
{ {
return "ALTER TABLE " . $this->connection->quoteTableName($table) return "ALTER TABLE " . $this->db->quoteTableName($table)
. " RENAME COLUMN " . $this->connection->quoteColumnName($oldName) . " RENAME COLUMN " . $this->db->quoteColumnName($oldName)
. " TO " . $this->connection->quoteColumnName($newName); . " TO " . $this->db->quoteColumnName($newName);
} }
/** /**
...@@ -308,9 +308,9 @@ class QueryBuilder extends \yii\base\Object ...@@ -308,9 +308,9 @@ class QueryBuilder extends \yii\base\Object
*/ */
public function alterColumn($table, $column, $type) public function alterColumn($table, $column, $type)
{ {
return 'ALTER TABLE ' . $this->connection->quoteTableName($table) . ' CHANGE ' return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
. $this->connection->quoteColumnName($column) . ' ' . $this->db->quoteColumnName($column) . ' '
. $this->connection->quoteColumnName($column) . ' ' . $this->db->quoteColumnName($column) . ' '
. $this->getColumnType($type); . $this->getColumnType($type);
} }
...@@ -330,10 +330,10 @@ class QueryBuilder extends \yii\base\Object ...@@ -330,10 +330,10 @@ class QueryBuilder extends \yii\base\Object
*/ */
public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null) public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
{ {
$sql = 'ALTER TABLE ' . $this->connection->quoteTableName($table) $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' ADD CONSTRAINT ' . $this->connection->quoteColumnName($name) . ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name)
. ' FOREIGN KEY (' . $this->buildColumns($columns) . ')' . ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
. ' REFERENCES ' . $this->connection->quoteTableName($refTable) . ' REFERENCES ' . $this->db->quoteTableName($refTable)
. ' (' . $this->buildColumns($refColumns) . ')'; . ' (' . $this->buildColumns($refColumns) . ')';
if ($delete !== null) { if ($delete !== null) {
$sql .= ' ON DELETE ' . $delete; $sql .= ' ON DELETE ' . $delete;
...@@ -352,8 +352,8 @@ class QueryBuilder extends \yii\base\Object ...@@ -352,8 +352,8 @@ class QueryBuilder extends \yii\base\Object
*/ */
public function dropForeignKey($name, $table) public function dropForeignKey($name, $table)
{ {
return 'ALTER TABLE ' . $this->connection->quoteTableName($table) return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' DROP CONSTRAINT ' . $this->connection->quoteColumnName($name); . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
} }
/** /**
...@@ -369,8 +369,8 @@ class QueryBuilder extends \yii\base\Object ...@@ -369,8 +369,8 @@ class QueryBuilder extends \yii\base\Object
public function createIndex($name, $table, $columns, $unique = false) public function createIndex($name, $table, $columns, $unique = false)
{ {
return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ') return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
. $this->connection->quoteTableName($name) . ' ON ' . $this->db->quoteTableName($name) . ' ON '
. $this->connection->quoteTableName($table) . $this->db->quoteTableName($table)
. ' (' . $this->buildColumns($columns) . ')'; . ' (' . $this->buildColumns($columns) . ')';
} }
...@@ -382,7 +382,7 @@ class QueryBuilder extends \yii\base\Object ...@@ -382,7 +382,7 @@ class QueryBuilder extends \yii\base\Object
*/ */
public function dropIndex($name, $table) public function dropIndex($name, $table)
{ {
return 'DROP INDEX ' . $this->connection->quoteTableName($name) . ' ON ' . $this->connection->quoteTableName($table); return 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON ' . $this->db->quoteTableName($table);
} }
/** /**
...@@ -397,7 +397,7 @@ class QueryBuilder extends \yii\base\Object ...@@ -397,7 +397,7 @@ class QueryBuilder extends \yii\base\Object
*/ */
public function resetSequence($table, $value = null) public function resetSequence($table, $value = null)
{ {
throw new NotSupportedException($this->connection->getDriverName() . ' does not support resetting sequence.'); throw new NotSupportedException($this->db->getDriverName() . ' does not support resetting sequence.');
} }
/** /**
...@@ -409,7 +409,7 @@ class QueryBuilder extends \yii\base\Object ...@@ -409,7 +409,7 @@ class QueryBuilder extends \yii\base\Object
*/ */
public function checkIntegrity($check = true, $schema = '') public function checkIntegrity($check = true, $schema = '')
{ {
throw new NotSupportedException($this->connection->getDriverName() . ' does not support enabling/disabling integrity check.'); throw new NotSupportedException($this->db->getDriverName() . ' does not support enabling/disabling integrity check.');
} }
/** /**
...@@ -503,12 +503,12 @@ class QueryBuilder extends \yii\base\Object ...@@ -503,12 +503,12 @@ class QueryBuilder extends \yii\base\Object
$parts[] = $this->buildInCondition('in', array($column, $value)); $parts[] = $this->buildInCondition('in', array($column, $value));
} else { } else {
if (strpos($column, '(') === false) { if (strpos($column, '(') === false) {
$column = $this->connection->quoteColumnName($column); $column = $this->db->quoteColumnName($column);
} }
if ($value === null) { if ($value === null) {
$parts[] = "$column IS NULL"; $parts[] = "$column IS NULL";
} elseif (is_string($value)) { } elseif (is_string($value)) {
$parts[] = "$column=" . $this->connection->quoteValue($value); $parts[] = "$column=" . $this->db->quoteValue($value);
} else { } else {
$parts[] = "$column=$value"; $parts[] = "$column=$value";
} }
...@@ -544,10 +544,10 @@ class QueryBuilder extends \yii\base\Object ...@@ -544,10 +544,10 @@ class QueryBuilder extends \yii\base\Object
list($column, $value1, $value2) = $operands; list($column, $value1, $value2) = $operands;
if (strpos($column, '(') === false) { if (strpos($column, '(') === false) {
$column = $this->connection->quoteColumnName($column); $column = $this->db->quoteColumnName($column);
} }
$value1 = is_string($value1) ? $this->connection->quoteValue($value1) : (string)$value1; $value1 = is_string($value1) ? $this->db->quoteValue($value1) : (string)$value1;
$value2 = is_string($value2) ? $this->connection->quoteValue($value2) : (string)$value2; $value2 = is_string($value2) ? $this->db->quoteValue($value2) : (string)$value2;
return "$column $operator $value1 AND $value2"; return "$column $operator $value1 AND $value2";
} }
...@@ -578,13 +578,13 @@ class QueryBuilder extends \yii\base\Object ...@@ -578,13 +578,13 @@ class QueryBuilder extends \yii\base\Object
if ($value === null) { if ($value === null) {
$values[$i] = 'NULL'; $values[$i] = 'NULL';
} else { } else {
$values[$i] = is_string($value) ? $this->connection->quoteValue($value) : (string)$value; $values[$i] = is_string($value) ? $this->db->quoteValue($value) : (string)$value;
} }
} }
} }
} }
if (strpos($column, '(') === false) { if (strpos($column, '(') === false) {
$column = $this->connection->quoteColumnName($column); $column = $this->db->quoteColumnName($column);
} }
if (count($values) > 1) { if (count($values) > 1) {
...@@ -599,7 +599,7 @@ class QueryBuilder extends \yii\base\Object ...@@ -599,7 +599,7 @@ class QueryBuilder extends \yii\base\Object
{ {
foreach ($columns as $i => $column) { foreach ($columns as $i => $column) {
if (strpos($column, '(') === false) { if (strpos($column, '(') === false) {
$columns[$i] = $this->connection->quoteColumnName($column); $columns[$i] = $this->db->quoteColumnName($column);
} }
} }
$vss = array(); $vss = array();
...@@ -607,7 +607,7 @@ class QueryBuilder extends \yii\base\Object ...@@ -607,7 +607,7 @@ class QueryBuilder extends \yii\base\Object
$vs = array(); $vs = array();
foreach ($columns as $column) { foreach ($columns as $column) {
if (isset($value[$column])) { if (isset($value[$column])) {
$vs[] = is_string($value[$column]) ? $this->connection->quoteValue($value[$column]) : (string)$value[$column]; $vs[] = is_string($value[$column]) ? $this->db->quoteValue($value[$column]) : (string)$value[$column];
} else { } else {
$vs[] = 'NULL'; $vs[] = 'NULL';
} }
...@@ -639,12 +639,12 @@ class QueryBuilder extends \yii\base\Object ...@@ -639,12 +639,12 @@ class QueryBuilder extends \yii\base\Object
} }
if (strpos($column, '(') === false) { if (strpos($column, '(') === false) {
$column = $this->connection->quoteColumnName($column); $column = $this->db->quoteColumnName($column);
} }
$parts = array(); $parts = array();
foreach ($values as $value) { foreach ($values as $value) {
$parts[] = "$column $operator " . $this->connection->quoteValue($value); $parts[] = "$column $operator " . $this->db->quoteValue($value);
} }
return implode($andor, $parts); return implode($andor, $parts);
...@@ -679,9 +679,9 @@ class QueryBuilder extends \yii\base\Object ...@@ -679,9 +679,9 @@ class QueryBuilder extends \yii\base\Object
$columns[$i] = (string)$column; $columns[$i] = (string)$column;
} elseif (strpos($column, '(') === false) { } elseif (strpos($column, '(') === false) {
if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $column, $matches)) { if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $column, $matches)) {
$columns[$i] = $this->connection->quoteColumnName($matches[1]) . ' AS ' . $this->connection->quoteColumnName($matches[2]); $columns[$i] = $this->db->quoteColumnName($matches[1]) . ' AS ' . $this->db->quoteColumnName($matches[2]);
} else { } else {
$columns[$i] = $this->connection->quoteColumnName($column); $columns[$i] = $this->db->quoteColumnName($column);
} }
} }
} }
...@@ -713,9 +713,9 @@ class QueryBuilder extends \yii\base\Object ...@@ -713,9 +713,9 @@ class QueryBuilder extends \yii\base\Object
foreach ($tables as $i => $table) { foreach ($tables as $i => $table) {
if (strpos($table, '(') === false) { if (strpos($table, '(') === false) {
if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/i', $table, $matches)) { // with alias if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/i', $table, $matches)) { // with alias
$tables[$i] = $this->connection->quoteTableName($matches[1]) . ' ' . $this->connection->quoteTableName($matches[2]); $tables[$i] = $this->db->quoteTableName($matches[1]) . ' ' . $this->db->quoteTableName($matches[2]);
} else { } else {
$tables[$i] = $this->connection->quoteTableName($table); $tables[$i] = $this->db->quoteTableName($table);
} }
} }
} }
...@@ -746,9 +746,9 @@ class QueryBuilder extends \yii\base\Object ...@@ -746,9 +746,9 @@ class QueryBuilder extends \yii\base\Object
$table = $join[1]; $table = $join[1];
if (strpos($table, '(') === false) { if (strpos($table, '(') === false) {
if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/', $table, $matches)) { // with alias if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/', $table, $matches)) { // with alias
$table = $this->connection->quoteTableName($matches[1]) . ' ' . $this->connection->quoteTableName($matches[2]); $table = $this->db->quoteTableName($matches[1]) . ' ' . $this->db->quoteTableName($matches[2]);
} else { } else {
$table = $this->connection->quoteTableName($table); $table = $this->db->quoteTableName($table);
} }
} }
$joins[$i] = $join[0] . ' ' . $table; $joins[$i] = $join[0] . ' ' . $table;
...@@ -821,9 +821,9 @@ class QueryBuilder extends \yii\base\Object ...@@ -821,9 +821,9 @@ class QueryBuilder extends \yii\base\Object
$columns[$i] = (string)$column; $columns[$i] = (string)$column;
} elseif (strpos($column, '(') === false) { } elseif (strpos($column, '(') === false) {
if (preg_match('/^(.*?)\s+(asc|desc)$/i', $column, $matches)) { if (preg_match('/^(.*?)\s+(asc|desc)$/i', $column, $matches)) {
$columns[$i] = $this->connection->quoteColumnName($matches[1]) . ' ' . $matches[2]; $columns[$i] = $this->db->quoteColumnName($matches[1]) . ' ' . $matches[2];
} else { } else {
$columns[$i] = $this->connection->quoteColumnName($column); $columns[$i] = $this->db->quoteColumnName($column);
} }
} }
} }
...@@ -889,7 +889,7 @@ class QueryBuilder extends \yii\base\Object ...@@ -889,7 +889,7 @@ class QueryBuilder extends \yii\base\Object
if (is_object($column)) { if (is_object($column)) {
$columns[$i] = (string)$column; $columns[$i] = (string)$column;
} elseif (strpos($column, '(') === false) { } elseif (strpos($column, '(') === false) {
$columns[$i] = $this->connection->quoteColumnName($column); $columns[$i] = $this->db->quoteColumnName($column);
} }
} }
return is_array($columns) ? implode(', ', $columns) : $columns; return is_array($columns) ? implode(', ', $columns) : $columns;
......
...@@ -48,7 +48,7 @@ abstract class Schema extends \yii\base\Object ...@@ -48,7 +48,7 @@ abstract class Schema extends \yii\base\Object
/** /**
* @var Connection the database connection * @var Connection the database connection
*/ */
public $connection; public $db;
/** /**
* @var array list of ALL table names in the database * @var array list of ALL table names in the database
*/ */
...@@ -82,7 +82,7 @@ abstract class Schema extends \yii\base\Object ...@@ -82,7 +82,7 @@ abstract class Schema extends \yii\base\Object
return $this->_tables[$name]; return $this->_tables[$name];
} }
$db = $this->connection; $db = $this->db;
$realName = $this->getRealTableName($name); $realName = $this->getRealTableName($name);
/** @var $cache \yii\caching\Cache */ /** @var $cache \yii\caching\Cache */
...@@ -109,7 +109,7 @@ abstract class Schema extends \yii\base\Object ...@@ -109,7 +109,7 @@ abstract class Schema extends \yii\base\Object
*/ */
public function getCacheKey($name) public function getCacheKey($name)
{ {
return __CLASS__ . "/{$this->connection->dsn}/{$this->connection->username}/{$name}"; return __CLASS__ . "/{$this->db->dsn}/{$this->db->username}/{$name}";
} }
/** /**
...@@ -169,7 +169,7 @@ abstract class Schema extends \yii\base\Object ...@@ -169,7 +169,7 @@ abstract class Schema extends \yii\base\Object
public function refresh() public function refresh()
{ {
/** @var $cache \yii\caching\Cache */ /** @var $cache \yii\caching\Cache */
if ($this->connection->enableSchemaCache && ($cache = \Yii::$application->getComponent($this->connection->schemaCacheID)) !== null) { if ($this->db->enableSchemaCache && ($cache = \Yii::$application->getComponent($this->db->schemaCacheID)) !== null) {
foreach ($this->_tables as $name => $table) { foreach ($this->_tables as $name => $table) {
$cache->delete($this->getCacheKey($name)); $cache->delete($this->getCacheKey($name));
} }
...@@ -185,7 +185,7 @@ abstract class Schema extends \yii\base\Object ...@@ -185,7 +185,7 @@ abstract class Schema extends \yii\base\Object
*/ */
public function createQueryBuilder() public function createQueryBuilder()
{ {
return new QueryBuilder($this->connection); return new QueryBuilder($this->db);
} }
/** /**
...@@ -210,8 +210,8 @@ abstract class Schema extends \yii\base\Object ...@@ -210,8 +210,8 @@ abstract class Schema extends \yii\base\Object
*/ */
public function getLastInsertID($sequenceName = '') public function getLastInsertID($sequenceName = '')
{ {
if ($this->connection->isActive) { if ($this->db->isActive) {
return $this->connection->pdo->lastInsertId($sequenceName); return $this->db->pdo->lastInsertId($sequenceName);
} else { } else {
throw new InvalidCallException('DB Connection is not active.'); throw new InvalidCallException('DB Connection is not active.');
} }
...@@ -230,8 +230,8 @@ abstract class Schema extends \yii\base\Object ...@@ -230,8 +230,8 @@ abstract class Schema extends \yii\base\Object
return $str; return $str;
} }
$this->connection->open(); $this->db->open();
if (($value = $this->connection->pdo->quote($str)) !== false) { if (($value = $this->db->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") . "'";
...@@ -319,9 +319,9 @@ abstract class Schema extends \yii\base\Object ...@@ -319,9 +319,9 @@ abstract class Schema extends \yii\base\Object
*/ */
public function getRealTableName($name) public function getRealTableName($name)
{ {
if ($this->connection->enableAutoQuoting && strpos($name, '{{') !== false) { if ($this->db->enableAutoQuoting && strpos($name, '{{') !== false) {
$name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name); $name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name);
return str_replace('%', $this->connection->tablePrefix, $name); return str_replace('%', $this->db->tablePrefix, $name);
} else { } else {
return $name; return $name;
} }
......
...@@ -41,7 +41,7 @@ class Transaction extends \yii\base\Object ...@@ -41,7 +41,7 @@ class Transaction extends \yii\base\Object
/** /**
* @var Connection the database connection that this transaction is associated with. * @var Connection the database connection that this transaction is associated with.
*/ */
public $connection; public $db;
/** /**
* @var boolean whether this transaction is active. Only an active transaction * @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. * can [[commit()]] or [[rollBack()]]. This property is set true when the transaction is started.
...@@ -65,12 +65,12 @@ class Transaction extends \yii\base\Object ...@@ -65,12 +65,12 @@ class Transaction extends \yii\base\Object
public function begin() public function begin()
{ {
if (!$this->_active) { if (!$this->_active) {
if ($this->connection === null) { if ($this->db === null) {
throw new InvalidConfigException('Transaction.connection must be set.'); throw new InvalidConfigException('Transaction::db must be set.');
} }
\Yii::trace('Starting transaction', __CLASS__); \Yii::trace('Starting transaction', __CLASS__);
$this->connection->open(); $this->db->open();
$this->connection->pdo->beginTransaction(); $this->db->pdo->beginTransaction();
$this->_active = true; $this->_active = true;
} }
} }
...@@ -81,9 +81,9 @@ class Transaction extends \yii\base\Object ...@@ -81,9 +81,9 @@ class Transaction extends \yii\base\Object
*/ */
public function commit() public function commit()
{ {
if ($this->_active && $this->connection && $this->connection->isActive) { if ($this->_active && $this->db && $this->db->isActive) {
\Yii::trace('Committing transaction', __CLASS__); \Yii::trace('Committing transaction', __CLASS__);
$this->connection->pdo->commit(); $this->db->pdo->commit();
$this->_active = false; $this->_active = false;
} else { } else {
throw new Exception('Failed to commit transaction: transaction was inactive.'); throw new Exception('Failed to commit transaction: transaction was inactive.');
...@@ -96,9 +96,9 @@ class Transaction extends \yii\base\Object ...@@ -96,9 +96,9 @@ class Transaction extends \yii\base\Object
*/ */
public function rollback() public function rollback()
{ {
if ($this->_active && $this->connection && $this->connection->isActive) { if ($this->_active && $this->db && $this->db->isActive) {
\Yii::trace('Rolling back transaction', __CLASS__); \Yii::trace('Rolling back transaction', __CLASS__);
$this->connection->pdo->commit(); $this->db->pdo->commit();
$this->_active = false; $this->_active = false;
} else { } else {
throw new Exception('Failed to roll back transaction: transaction was inactive.'); throw new Exception('Failed to roll back transaction: transaction was inactive.');
......
...@@ -51,8 +51,8 @@ class QueryBuilder extends \yii\db\QueryBuilder ...@@ -51,8 +51,8 @@ class QueryBuilder extends \yii\db\QueryBuilder
*/ */
public function renameColumn($table, $oldName, $newName) public function renameColumn($table, $oldName, $newName)
{ {
$quotedTable = $this->connection->quoteTableName($table); $quotedTable = $this->db->quoteTableName($table);
$row = $this->connection->createCommand('SHOW CREATE TABLE ' . $quotedTable)->queryRow(); $row = $this->db->createCommand('SHOW CREATE TABLE ' . $quotedTable)->queryRow();
if ($row === false) { if ($row === false) {
throw new Exception("Unable to find '$oldName' in table '$table'."); throw new Exception("Unable to find '$oldName' in table '$table'.");
} }
...@@ -66,16 +66,16 @@ class QueryBuilder extends \yii\db\QueryBuilder ...@@ -66,16 +66,16 @@ class QueryBuilder extends \yii\db\QueryBuilder
foreach ($matches[1] as $i => $c) { foreach ($matches[1] as $i => $c) {
if ($c === $oldName) { if ($c === $oldName) {
return "ALTER TABLE $quotedTable CHANGE " return "ALTER TABLE $quotedTable CHANGE "
. $this->connection->quoteColumnName($oldName) . ' ' . $this->db->quoteColumnName($oldName) . ' '
. $this->connection->quoteColumnName($newName) . ' ' . $this->db->quoteColumnName($newName) . ' '
. $matches[2][$i]; . $matches[2][$i];
} }
} }
} }
// try to give back a SQL anyway // try to give back a SQL anyway
return "ALTER TABLE $quotedTable CHANGE " return "ALTER TABLE $quotedTable CHANGE "
. $this->connection->quoteColumnName($oldName) . ' ' . $this->db->quoteColumnName($oldName) . ' '
. $this->connection->quoteColumnName($newName); . $this->db->quoteColumnName($newName);
} }
/** /**
...@@ -86,8 +86,8 @@ class QueryBuilder extends \yii\db\QueryBuilder ...@@ -86,8 +86,8 @@ class QueryBuilder extends \yii\db\QueryBuilder
*/ */
public function dropForeignKey($name, $table) public function dropForeignKey($name, $table)
{ {
return 'ALTER TABLE ' . $this->connection->quoteTableName($table) return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' DROP FOREIGN KEY ' . $this->connection->quoteColumnName($name); . ' DROP FOREIGN KEY ' . $this->db->quoteColumnName($name);
} }
/** /**
...@@ -102,12 +102,12 @@ class QueryBuilder extends \yii\db\QueryBuilder ...@@ -102,12 +102,12 @@ class QueryBuilder extends \yii\db\QueryBuilder
*/ */
public function resetSequence($tableName, $value = null) public function resetSequence($tableName, $value = null)
{ {
$table = $this->connection->getTableSchema($tableName); $table = $this->db->getTableSchema($tableName);
if ($table !== null && $table->sequenceName !== null) { if ($table !== null && $table->sequenceName !== null) {
$tableName = $this->connection->quoteTableName($tableName); $tableName = $this->db->quoteTableName($tableName);
if ($value === null) { if ($value === null) {
$key = reset($table->primaryKey); $key = reset($table->primaryKey);
$value = $this->connection->createCommand("SELECT MAX(`$key`) FROM $tableName")->queryScalar() + 1; $value = $this->db->createCommand("SELECT MAX(`$key`) FROM $tableName")->queryScalar() + 1;
} else { } else {
$value = (int)$value; $value = (int)$value;
} }
......
<?php <?php
/** /**
* Driver class file. * Schema class file.
* *
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright &copy; 2008 Yii Software LLC
...@@ -13,7 +13,7 @@ use yii\db\TableSchema; ...@@ -13,7 +13,7 @@ use yii\db\TableSchema;
use yii\db\ColumnSchema; use yii\db\ColumnSchema;
/** /**
* Driver is the class for retrieving metadata from a MySQL database (version 4.1.x and 5.x). * Schema is the class for retrieving metadata from a MySQL database (version 4.1.x and 5.x).
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
...@@ -79,7 +79,7 @@ class Schema extends \yii\db\Schema ...@@ -79,7 +79,7 @@ class Schema extends \yii\db\Schema
*/ */
public function createQueryBuilder() public function createQueryBuilder()
{ {
return new QueryBuilder($this->connection); return new QueryBuilder($this->db);
} }
/** /**
...@@ -183,9 +183,9 @@ class Schema extends \yii\db\Schema ...@@ -183,9 +183,9 @@ class Schema extends \yii\db\Schema
*/ */
protected function findColumns($table) protected function findColumns($table)
{ {
$sql = 'SHOW COLUMNS FROM ' . $this->quoteSimpleTableName($table->name); $sql = 'SHOW FULL COLUMNS FROM ' . $this->quoteSimpleTableName($table->name);
try { try {
$columns = $this->connection->createCommand($sql)->queryAll(); $columns = $this->db->createCommand($sql)->queryAll();
} catch (\Exception $e) { } catch (\Exception $e) {
return false; return false;
} }
...@@ -208,7 +208,7 @@ class Schema extends \yii\db\Schema ...@@ -208,7 +208,7 @@ class Schema extends \yii\db\Schema
*/ */
protected function findConstraints($table) protected function findConstraints($table)
{ {
$row = $this->connection->createCommand('SHOW CREATE TABLE ' . $this->quoteSimpleTableName($table->name))->queryRow(); $row = $this->db->createCommand('SHOW CREATE TABLE ' . $this->quoteSimpleTableName($table->name))->queryRow();
if (isset($row['Create Table'])) { if (isset($row['Create Table'])) {
$sql = $row['Create Table']; $sql = $row['Create Table'];
} else { } else {
...@@ -243,6 +243,6 @@ class Schema extends \yii\db\Schema ...@@ -243,6 +243,6 @@ class Schema extends \yii\db\Schema
if ($schema !== '') { if ($schema !== '') {
$sql .= ' FROM ' . $this->quoteSimpleTableName($schema); $sql .= ' FROM ' . $this->quoteSimpleTableName($schema);
} }
return $this->connection->createCommand($sql)->queryColumn(); return $this->db->createCommand($sql)->queryColumn();
} }
} }
...@@ -54,7 +54,7 @@ class QueryBuilder extends \yii\db\QueryBuilder ...@@ -54,7 +54,7 @@ class QueryBuilder extends \yii\db\QueryBuilder
*/ */
public function resetSequence($tableName, $value = null) public function resetSequence($tableName, $value = null)
{ {
$db = $this->connection; $db = $this->db;
$table = $db->getTableSchema($tableName); $table = $db->getTableSchema($tableName);
if ($table !== null && $table->sequenceName !== null) { if ($table !== null && $table->sequenceName !== null) {
if ($value === null) { if ($value === null) {
...@@ -94,7 +94,7 @@ class QueryBuilder extends \yii\db\QueryBuilder ...@@ -94,7 +94,7 @@ class QueryBuilder extends \yii\db\QueryBuilder
*/ */
public function truncateTable($table) public function truncateTable($table)
{ {
return "DELETE FROM " . $this->connection->quoteTableName($table); return "DELETE FROM " . $this->db->quoteTableName($table);
} }
/** /**
...@@ -105,7 +105,7 @@ class QueryBuilder extends \yii\db\QueryBuilder ...@@ -105,7 +105,7 @@ class QueryBuilder extends \yii\db\QueryBuilder
*/ */
public function dropIndex($name, $table) public function dropIndex($name, $table)
{ {
return 'DROP INDEX ' . $this->connection->quoteTableName($name); return 'DROP INDEX ' . $this->db->quoteTableName($name);
} }
/** /**
......
<?php <?php
/** /**
* Driver class file. * Schema class file.
* *
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright &copy; 2008 Yii Software LLC
...@@ -13,7 +13,7 @@ use yii\db\TableSchema; ...@@ -13,7 +13,7 @@ use yii\db\TableSchema;
use yii\db\ColumnSchema; use yii\db\ColumnSchema;
/** /**
* Driver is the class for retrieving metadata from a SQLite (2/3) database. * Schema is the class for retrieving metadata from a SQLite (2/3) database.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
...@@ -58,7 +58,7 @@ class Schema extends \yii\db\Schema ...@@ -58,7 +58,7 @@ class Schema extends \yii\db\Schema
*/ */
public function createQueryBuilder() public function createQueryBuilder()
{ {
return new QueryBuilder($this->connection); return new QueryBuilder($this->db);
} }
/** /**
...@@ -70,7 +70,7 @@ class Schema extends \yii\db\Schema ...@@ -70,7 +70,7 @@ class Schema extends \yii\db\Schema
protected function findTableNames($schema = '') protected function findTableNames($schema = '')
{ {
$sql = "SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'"; $sql = "SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'";
return $this->connection->createCommand($sql)->queryColumn(); return $this->db->createCommand($sql)->queryColumn();
} }
/** /**
...@@ -99,7 +99,7 @@ class Schema extends \yii\db\Schema ...@@ -99,7 +99,7 @@ class Schema extends \yii\db\Schema
protected function findColumns($table) protected function findColumns($table)
{ {
$sql = "PRAGMA table_info(" . $this->quoteSimpleTableName($table->name) . ')'; $sql = "PRAGMA table_info(" . $this->quoteSimpleTableName($table->name) . ')';
$columns = $this->connection->createCommand($sql)->queryAll(); $columns = $this->db->createCommand($sql)->queryAll();
if (empty($columns)) { if (empty($columns)) {
return false; return false;
} }
...@@ -126,7 +126,7 @@ class Schema extends \yii\db\Schema ...@@ -126,7 +126,7 @@ class Schema extends \yii\db\Schema
protected function findConstraints($table) protected function findConstraints($table)
{ {
$sql = "PRAGMA foreign_key_list(" . $this->quoteSimpleTableName($table->name) . ')'; $sql = "PRAGMA foreign_key_list(" . $this->quoteSimpleTableName($table->name) . ')';
$keys = $this->connection->createCommand($sql)->queryAll(); $keys = $this->db->createCommand($sql)->queryAll();
foreach ($keys as $key) { foreach ($keys as $key) {
$table->foreignKeys[] = array($key['table'], $key['from'] => $key['to']); $table->foreignKeys[] = array($key['table'], $key['from'] => $key['to']);
} }
......
...@@ -65,7 +65,7 @@ class DbTarget extends Target ...@@ -65,7 +65,7 @@ class DbTarget extends Target
* @return \yii\db\Connection the DB connection instance * @return \yii\db\Connection the DB connection instance
* @throws \yii\base\Exception if [[connectionID]] does not refer to a valid application component ID. * @throws \yii\base\Exception if [[connectionID]] does not refer to a valid application component ID.
*/ */
public function getDbConnection() public function getDb()
{ {
if ($this->_db === null) { if ($this->_db === null) {
$this->_db = \Yii::$application->getComponent($this->connectionID); $this->_db = \Yii::$application->getComponent($this->connectionID);
...@@ -85,7 +85,7 @@ class DbTarget extends Target ...@@ -85,7 +85,7 @@ class DbTarget extends Target
$sql = "INSERT INTO {$this->tableName} $sql = "INSERT INTO {$this->tableName}
(level, category, log_time, message) VALUES (level, category, log_time, message) VALUES
(:level, :category, :log_time, :message)"; (:level, :category, :log_time, :message)";
$command = $this->getDbConnection()->createCommand($sql); $command = $this->getDb()->createCommand($sql);
foreach ($this->messages as $message) { foreach ($this->messages as $message) {
$command->bindValues(array( $command->bindValues(array(
':level' => $message[1], ':level' => $message[1],
......
...@@ -21,7 +21,7 @@ class ActiveRecord extends \yii\db\ActiveRecord ...@@ -21,7 +21,7 @@ class ActiveRecord extends \yii\db\ActiveRecord
{ {
public static $db; public static $db;
public static function getDbConnection() public static function getDb()
{ {
return self::$db; return self::$db;
} }
......
...@@ -20,11 +20,8 @@ ...@@ -20,11 +20,8 @@
* a way to invalidate/clear cached data * a way to invalidate/clear cached data
* a command to clear cached data * a command to clear cached data
- db - db
* sqlite, pgsql, sql server, oracle, db2 drivers * pgsql, sql server, oracle, db2 drivers
* write a guide on creating own schema definitions * write a guide on creating own schema definitions
* AR
* saving related records
* collection support for results
* document-based (should allow storage-specific methods additionally to generic ones) * document-based (should allow storage-specific methods additionally to generic ones)
* mongodb * mongodb
* key-value-based (should allow storage-specific methods additionally to generic ones) * key-value-based (should allow storage-specific methods additionally to generic ones)
...@@ -61,4 +58,3 @@ ...@@ -61,4 +58,3 @@
* if we're going to supply default ones, these should generate really unique IDs. This will solve a lot of AJAX-nesting problems. * if we're going to supply default ones, these should generate really unique IDs. This will solve a lot of AJAX-nesting problems.
- Make sure type hinting is used when components are passed to methods - Make sure type hinting is used when components are passed to methods
- Decouple controller from application (by passing web application instance to controller and if not passed, using Yii::app())? - Decouple controller from application (by passing web application instance to controller and if not passed, using Yii::app())?
- Decouple view renderer from controller so it can be used separately (useful for sending emails from console etc.)
\ No newline at end of file
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