Browse Source

refactoring.

tags/2.0.0-alpha
Qiang Xue 12 years ago
parent
commit
abd3d827a2
  1. 20
      framework/caching/DbCache.php
  2. 6
      framework/caching/DbDependency.php
  3. 14
      framework/console/controllers/MigrateController.php
  4. 2
      framework/db/ActiveQuery.php
  5. 18
      framework/db/ActiveRecord.php
  6. 2
      framework/db/ActiveRelation.php
  7. 59
      framework/db/Command.php
  8. 6
      framework/db/Connection.php
  9. 174
      framework/db/Migration.php
  10. 106
      framework/db/QueryBuilder.php
  11. 22
      framework/db/Schema.php
  12. 18
      framework/db/Transaction.php
  13. 22
      framework/db/mysql/QueryBuilder.php
  14. 14
      framework/db/mysql/Schema.php
  15. 6
      framework/db/sqlite/QueryBuilder.php
  16. 12
      framework/db/sqlite/Schema.php
  17. 4
      framework/logging/DbTarget.php
  18. 2
      tests/unit/data/ar/ActiveRecord.php
  19. 6
      todo.md

20
framework/caching/DbCache.php

@ -39,7 +39,7 @@ use yii\db\Query;
*
* 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>
* @since 2.0
@ -71,7 +71,7 @@ class DbCache extends Cache
* @return Connection the DB connection instance
* @throws Exception if [[connectionID]] does not point to a valid application component.
*/
public function getDbConnection()
public function getDb()
{
if ($this->_db === null) {
$db = \Yii::$application->getComponent($this->connectionID);
@ -88,7 +88,7 @@ class DbCache extends Cache
* Sets the DB connection used by the cache component.
* @param Connection $value the DB connection instance
*/
public function setDbConnection($value)
public function setDb($value)
{
$this->_db = $value;
}
@ -105,7 +105,7 @@ class DbCache extends Cache
$query->select(array('data'))
->from($this->cacheTableName)
->where('id = :id AND (expire = 0 OR expire > :time)', array(':id' => $key, ':time' => time()));
$db = $this->getDbConnection();
$db = $this->getDb();
if ($db->enableQueryCache) {
// temporarily disable and re-enable query caching
$db->enableQueryCache = false;
@ -133,7 +133,7 @@ class DbCache extends Cache
->where(array('id' => $keys))
->andWhere("expire = 0 OR expire > " . time() . ")");
$db = $this->getDbConnection();
$db = $this->getDb();
if ($db->enableQueryCache) {
$db->enableQueryCache = false;
$rows = $query->createCommand($db)->queryAll();
@ -169,7 +169,7 @@ class DbCache extends Cache
'data' => array($value, \PDO::PARAM_LOB),
), array(
'id' => $key,
))->createCommand($this->getDbConnection());
))->createCommand($this->getDb());
if ($command->execute()) {
$this->gc();
@ -203,7 +203,7 @@ class DbCache extends Cache
'id' => $key,
'expire' => $expire,
'data' => array($value, \PDO::PARAM_LOB),
))->createCommand($this->getDbConnection());
))->createCommand($this->getDb());
try {
$command->execute();
return true;
@ -222,7 +222,7 @@ class DbCache extends Cache
{
$query = new Query;
$query->delete($this->cacheTableName, array('id' => $key))
->createCommand($this->getDbConnection())
->createCommand($this->getDb())
->execute();
return true;
}
@ -237,7 +237,7 @@ class DbCache extends Cache
if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
$query = new Query;
$query->delete($this->cacheTableName, 'expire > 0 AND expire < ' . time())
->createCommand($this->getDbConnection())
->createCommand($this->getDb())
->execute();
}
}
@ -251,7 +251,7 @@ class DbCache extends Cache
{
$query = new Query;
$query->delete($this->cacheTableName)
->createCommand($this->getDbConnection())
->createCommand($this->getDb())
->execute();
return true;
}

6
framework/caching/DbDependency.php

@ -67,7 +67,7 @@ class DbDependency extends Dependency
*/
protected function generateDependencyData()
{
$db = $this->getDbConnection();
$db = $this->getDb();
$command = $this->query->createCommand($db);
if ($db->enableQueryCache) {
// temporarily disable and re-enable query caching
@ -85,7 +85,7 @@ class DbDependency extends Dependency
* @return Connection the DB connection instance
* @throws Exception if [[connectionID]] does not point to a valid application component.
*/
public function getDbConnection()
public function getDb()
{
if ($this->_db === null) {
$db = \Yii::$application->getComponent($this->connectionID);
@ -102,7 +102,7 @@ class DbDependency extends Dependency
* Sets the DB connection used by the cache component.
* @param Connection $value the DB connection instance
*/
public function setDbConnection($value)
public function setDb($value)
{
$this->_db = $value;
}

14
framework/console/controllers/MigrateController.php

@ -278,7 +278,7 @@ class MigrateController extends Controller
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");
$db=$this->getDbConnection();
$db=$this->getDb();
// try mark up
$migrations=$this->getNewMigrations();
@ -405,7 +405,7 @@ class MigrateController extends Controller
$migration=$this->instantiateMigration($class);
if($migration->up()!==false)
{
$this->getDbConnection()->createCommand()->insert($this->migrationTable, array(
$this->getDb()->createCommand()->insert($this->migrationTable, array(
'version'=>$class,
'apply_time'=>time(),
));
@ -430,7 +430,7 @@ class MigrateController extends Controller
$migration=$this->instantiateMigration($class);
if($migration->down()!==false)
{
$db=$this->getDbConnection();
$db=$this->getDb();
$db->createCommand()->delete($this->migrationTable, $db->quoteColumnName('version').'=:version', array(':version'=>$class));
$time=microtime(true)-$start;
echo "*** reverted $class (time: ".sprintf("%.3f",$time)."s)\n\n";
@ -448,7 +448,7 @@ class MigrateController extends Controller
$file=$this->migrationPath.DIRECTORY_SEPARATOR.$class.'.php';
require_once($file);
$migration=new $class;
$migration->setDbConnection($this->getDbConnection());
$migration->setDb($this->getDb());
return $migration;
}
@ -456,7 +456,7 @@ class MigrateController extends Controller
* @var CDbConnection
*/
private $_db;
protected function getDbConnection()
protected function getDb()
{
if($this->_db!==null)
return $this->_db;
@ -468,7 +468,7 @@ class MigrateController extends Controller
protected function getMigrationHistory($limit)
{
$db=$this->getDbConnection();
$db=$this->getDb();
if($db->schema->getTable($this->migrationTable)===null)
{
$this->createMigrationHistoryTable();
@ -483,7 +483,7 @@ class MigrateController extends Controller
protected function createMigrationHistoryTable()
{
$db=$this->getDbConnection();
$db=$this->getDb();
echo 'Creating migration history table "'.$this->migrationTable.'"...';
$db->createCommand()->createTable($this->migrationTable,array(
'version'=>'string NOT NULL PRIMARY KEY',

2
framework/db/ActiveQuery.php

@ -232,7 +232,7 @@ class ActiveQuery extends Query
/** @var $modelClass ActiveRecord */
$modelClass = $this->modelClass;
if ($db === null) {
$db = $modelClass::getDbConnection();
$db = $modelClass::getDb();
}
if ($this->sql === null) {
if ($this->from === null) {

18
framework/db/ActiveRecord.php

@ -24,7 +24,7 @@ use yii\util\StringHelper;
*
* @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 array $oldAttributes the old attribute values (name-value pairs).
* @property array $dirtyAttributes the changed attribute values (name-value pairs).
@ -69,7 +69,7 @@ class ActiveRecord extends Model
* You may override this method if you want to use a different database connection.
* @return Connection the database connection used by this AR class.
*/
public static function getDbConnection()
public static function getDb()
{
return \Yii::$application->getDb();
}
@ -145,7 +145,7 @@ class ActiveRecord extends Model
*/
public static function updateAll($attributes, $condition = '', $params = array())
{
$command = static::getDbConnection()->createCommand();
$command = static::getDb()->createCommand();
$command->update(static::tableName(), $attributes, $condition, $params);
return $command->execute();
}
@ -168,7 +168,7 @@ class ActiveRecord extends Model
*/
public static function updateAllCounters($counters, $condition = '', $params = array())
{
$db = static::getDbConnection();
$db = static::getDb();
$n = 0;
foreach ($counters as $name => $value) {
$quotedName = $db->quoteColumnName($name);
@ -198,7 +198,7 @@ class ActiveRecord extends Model
*/
public static function deleteAll($condition = '', $params = array())
{
$command = static::getDbConnection()->createCommand();
$command = static::getDb()->createCommand();
$command->delete(static::tableName(), $condition, $params);
return $command->execute();
}
@ -235,7 +235,7 @@ class ActiveRecord extends Model
*/
public static function getTableSchema()
{
return static::getDbConnection()->getTableSchema(static::tableName());
return static::getDb()->getTableSchema(static::tableName());
}
/**
@ -618,7 +618,7 @@ class ActiveRecord extends Model
$values[$key] = isset($this->_attributes[$key]) ? $this->_attributes[$key] : null;
}
}
$db = static::getDbConnection();
$db = static::getDb();
$command = $db->createCommand()->insert($this->tableName(), $values);
if ($command->execute()) {
$table = $this->getTableSchema();
@ -1079,7 +1079,7 @@ class ActiveRecord extends Model
foreach ($extraColumns as $k => $v) {
$columns[$k] = $v;
}
static::getDbConnection()->createCommand()
static::getDb()->createCommand()
->insert($viaTable, $columns)->execute();
} else {
$p1 = $model->isPrimaryKey(array_keys($relation->link));
@ -1150,7 +1150,7 @@ class ActiveRecord extends Model
foreach ($relation->link as $a => $b) {
$columns[$b] = $model->$a;
}
$command = static::getDbConnection()->createCommand();
$command = static::getDb()->createCommand();
if ($delete) {
$command->delete($viaTable, $columns)->execute();
} else {

2
framework/db/ActiveRelation.php

@ -299,7 +299,7 @@ class ActiveRelation extends ActiveQuery
$this->filterByModels($primaryModels);
/** @var $primaryModel ActiveRecord */
$primaryModel = reset($primaryModels);
$db = $primaryModel->getDbConnection();
$db = $primaryModel->getDb();
$sql = $db->getQueryBuilder()->build($this);
return $db->createCommand($sql, $this->params)->queryAll();
}

59
framework/db/Command.php

@ -54,7 +54,7 @@ class Command extends \yii\base\Component
/**
* @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
*/
@ -91,7 +91,7 @@ class Command extends \yii\base\Component
public function setSql($sql)
{
if ($sql !== $this->_sql) {
if ($this->connection->enableAutoQuoting && $sql != '') {
if ($this->db->enableAutoQuoting && $sql != '') {
$sql = $this->expandSql($sql);
}
$this->cancel();
@ -108,12 +108,13 @@ class Command extends \yii\base\Component
*/
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])) {
return $this->connection->quoteColumnName($matches[3]);
return $db->quoteColumnName($matches[3]);
} else {
$name = str_replace('%', $this->connection->tablePrefix, $matches[2]);
return $this->connection->quoteTableName($name);
$name = str_replace('%', $db->tablePrefix, $matches[2]);
return $db->quoteTableName($name);
}
}, $sql);
}
@ -131,7 +132,7 @@ class Command extends \yii\base\Component
if ($this->pdoStatement == null) {
$sql = $this->getSql();
try {
$this->pdoStatement = $this->connection->pdo->prepare($sql);
$this->pdoStatement = $this->db->pdo->prepare($sql);
} catch (\Exception $e) {
\Yii::error($e->getMessage() . "\nFailed to prepare SQL: $sql", __CLASS__);
$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
@ -276,7 +277,7 @@ class Command extends \yii\base\Component
}
try {
if ($this->connection->enableProfiling) {
if ($this->db->enableProfiling) {
\Yii::beginProfile(__METHOD__ . "($sql)", __CLASS__);
}
@ -288,12 +289,12 @@ class Command extends \yii\base\Component
}
$n = $this->pdoStatement->rowCount();
if ($this->connection->enableProfiling) {
if ($this->db->enableProfiling) {
\Yii::endProfile(__METHOD__ . "($sql)", __CLASS__);
}
return $n;
} catch (\Exception $e) {
if ($this->connection->enableProfiling) {
if ($this->db->enableProfiling) {
\Yii::endProfile(__METHOD__ . "($sql)", __CLASS__);
}
$message = $e->getMessage();
@ -400,7 +401,7 @@ class Command extends \yii\base\Component
*/
private function queryInternal($method, $params, $fetchMode = null)
{
$db = $this->connection;
$db = $this->db;
$sql = $this->getSql();
$this->_params = array_merge($this->_params, $params);
if ($this->_params === array()) {
@ -489,7 +490,7 @@ class Command extends \yii\base\Component
*/
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);
}
@ -516,7 +517,7 @@ class Command extends \yii\base\Component
*/
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);
}
@ -540,7 +541,7 @@ class Command extends \yii\base\Component
*/
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);
}
@ -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'),
* 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.
* 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
* as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
*
@ -565,7 +566,7 @@ class Command extends \yii\base\Component
*/
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);
}
@ -577,7 +578,7 @@ class Command extends \yii\base\Component
*/
public function renameTable($table, $newName)
{
$sql = $this->connection->getQueryBuilder()->renameTable($table, $newName);
$sql = $this->db->getQueryBuilder()->renameTable($table, $newName);
return $this->setSql($sql);
}
@ -588,7 +589,7 @@ class Command extends \yii\base\Component
*/
public function dropTable($table)
{
$sql = $this->connection->getQueryBuilder()->dropTable($table);
$sql = $this->db->getQueryBuilder()->dropTable($table);
return $this->setSql($sql);
}
@ -599,7 +600,7 @@ class Command extends \yii\base\Component
*/
public function truncateTable($table)
{
$sql = $this->connection->getQueryBuilder()->truncateTable($table);
$sql = $this->db->getQueryBuilder()->truncateTable($table);
return $this->setSql($sql);
}
@ -614,7 +615,7 @@ class Command extends \yii\base\Component
*/
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);
}
@ -626,7 +627,7 @@ class Command extends \yii\base\Component
*/
public function dropColumn($table, $column)
{
$sql = $this->connection->getQueryBuilder()->dropColumn($table, $column);
$sql = $this->db->getQueryBuilder()->dropColumn($table, $column);
return $this->setSql($sql);
}
@ -639,7 +640,7 @@ class Command extends \yii\base\Component
*/
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);
}
@ -654,7 +655,7 @@ class Command extends \yii\base\Component
*/
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);
}
@ -672,7 +673,7 @@ class Command extends \yii\base\Component
*/
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);
}
@ -684,7 +685,7 @@ class Command extends \yii\base\Component
*/
public function dropForeignKey($name, $table)
{
$sql = $this->connection->getQueryBuilder()->dropForeignKey($name, $table);
$sql = $this->db->getQueryBuilder()->dropForeignKey($name, $table);
return $this->setSql($sql);
}
@ -699,7 +700,7 @@ class Command extends \yii\base\Component
*/
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);
}
@ -711,7 +712,7 @@ class Command extends \yii\base\Component
*/
public function dropIndex($name, $table)
{
$sql = $this->connection->getQueryBuilder()->dropIndex($name, $table);
$sql = $this->db->getQueryBuilder()->dropIndex($name, $table);
return $this->setSql($sql);
}
@ -727,7 +728,7 @@ class Command extends \yii\base\Component
*/
public function resetSequence($table, $value = null)
{
$sql = $this->connection->getQueryBuilder()->resetSequence($table, $value);
$sql = $this->db->getQueryBuilder()->resetSequence($table, $value);
return $this->setSql($sql);
}
@ -741,7 +742,7 @@ class Command extends \yii\base\Component
*/
public function checkIntegrity($check = true, $schema = '')
{
$sql = $this->connection->getQueryBuilder()->checkIntegrity($check, $schema);
$sql = $this->db->getQueryBuilder()->checkIntegrity($check, $schema);
return $this->setSql($sql);
}
}

6
framework/db/Connection.php

@ -395,7 +395,7 @@ class Connection extends \yii\base\ApplicationComponent
{
$this->open();
$command = new Command(array(
'connection' => $this,
'db' => $this,
'sql' => $sql,
));
return $command->bindValues($params);
@ -418,7 +418,7 @@ class Connection extends \yii\base\ApplicationComponent
{
$this->open();
$this->_transaction = new Transaction(array(
'connection' => $this,
'db' => $this,
));
$this->_transaction->begin();
return $this->_transaction;
@ -437,7 +437,7 @@ class Connection extends \yii\base\ApplicationComponent
$driver = $this->getDriverName();
if (isset($this->schemaMap[$driver])) {
$this->_schema = \Yii::createObject($this->schemaMap[$driver]);
$this->_schema->connection = $this;
$this->_schema->db = $this;
return $this->_schema;
} else {
throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS.");

174
framework/db/Migration.php

@ -1,97 +1,117 @@
<?php
/**
* CMysqlSchema class file.
* Migration class file.
*
* @author Qiang Xue <qiang.xue@gmail.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/
*/
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.
*
* Within each migration, the {@link up} method contains the logic for "upgrading"
* the database used in an application; while the {@link down} method contains "downgrading"
* Within each migration, the [[up()]] method should be overwritten to contain the logic
* for "upgrading" the database; while the [[down()]] method for the "downgrading"
* 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.
* For example, the {@link insert} method can be used to easily insert a row of data into
* a database table; the {@link createTable} method can be used to create a database table.
* Compared with the same methods in {@link CDbCommand}, these methods will display extra
* If the database supports transactions, you may also overwrite [[safeUp()]] and
* [[safeDown()]] so that if anything wrong happens during the upgrading or downgrading,
* the whole migration can be reverted in a whole.
*
* 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
* applying migrations.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @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.
* Child classes may implement this method to provide actual migration logic.
* @return boolean
* Child classes may overwrite this method to provide actual migration logic.
* @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()
{
$transaction = $this->getDbConnection()->beginTransaction();
try
{
$transaction = $this->db->beginTransaction();
try {
if ($this->safeUp() === false) {
$transaction->rollBack();
return false;
}
$transaction->commit();
}
catch (Exception $e)
{
} catch (\Exception $e) {
echo "Exception: " . $e->getMessage() . ' (' . $e->getFile() . ':' . $e->getLine() . ")\n";
echo $e->getTraceAsString() . "\n";
$transaction->rollBack();
return false;
}
return null;
}
/**
* This method contains the logic to be executed when removing this migration.
* 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.
* @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()
{
$transaction = $this->getDbConnection()->beginTransaction();
try
{
$transaction = $this->db->beginTransaction();
try {
if ($this->safeDown() === false) {
$transaction->rollBack();
return false;
}
$transaction->commit();
}
catch (Exception $e)
{
} catch (\Exception $e) {
echo "Exception: " . $e->getMessage() . ' (' . $e->getFile() . ':' . $e->getLine() . ")\n";
echo $e->getTraceAsString() . "\n";
$transaction->rollBack();
return false;
}
return null;
}
/**
* 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.
* 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.
* @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()
{
@ -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 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.
* 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.
* @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()
{
}
/**
* 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.
* 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 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())
{
echo " > execute SQL: $sql ...";
$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";
}
@ -161,7 +154,7 @@ abstract class CDbMigration extends yii\base\Component
{
echo " > insert into $table ...";
$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";
}
@ -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.
* @param string $table the table 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
* refer to {@link CDbCommand::where} on how to specify conditions.
* @param mixed $condition the conditions that will be put in the WHERE part. Please
* refer to [[Query::where()]] on how to specify conditions.
* @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 ...";
$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";
}
/**
* Creates and executes a DELETE SQL statement.
* @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
* refer to {@link CDbCommand::where} on how to specify conditions.
* @param mixed $condition the conditions that will be put in the WHERE part. Please
* refer to [[Query::where()]] on how to specify conditions.
* @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 ...";
$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";
}
@ -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'),
* 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.
* 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
* 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 array $columns the columns (name=>definition) in the new table.
@ -216,7 +210,7 @@ abstract class CDbMigration extends yii\base\Component
{
echo " > create table $table ...";
$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";
}
@ -229,7 +223,7 @@ abstract class CDbMigration extends yii\base\Component
{
echo " > rename table $table to $newName ...";
$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";
}
@ -241,7 +235,7 @@ abstract class CDbMigration extends yii\base\Component
{
echo " > drop table $table ...";
$time = microtime(true);
$this->getDbConnection()->createCommand()->dropTable($table);
$this->db->createCommand()->dropTable($table)->execute();
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
}
@ -253,7 +247,7 @@ abstract class CDbMigration extends yii\base\Component
{
echo " > truncate table $table ...";
$time = microtime(true);
$this->getDbConnection()->createCommand()->truncateTable($table);
$this->db->createCommand()->truncateTable($table)->execute();
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
}
@ -261,7 +255,7 @@ abstract class CDbMigration extends yii\base\Component
* 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 $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.
* 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
{
echo " > add column $column $type to table $table ...";
$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";
}
@ -282,7 +276,7 @@ abstract class CDbMigration extends yii\base\Component
{
echo " > drop column $column from table $table ...";
$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";
}
@ -296,7 +290,7 @@ abstract class CDbMigration extends yii\base\Component
{
echo " > rename column $name in table $table to $newName ...";
$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";
}
@ -312,7 +306,7 @@ abstract class CDbMigration extends yii\base\Component
{
echo " > alter column $column in table $table to $type ...";
$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";
}
@ -331,7 +325,7 @@ abstract class CDbMigration extends yii\base\Component
{
echo " > add foreign key $name: $table ($columns) references $refTable ($refColumns) ...";
$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";
}
@ -344,7 +338,7 @@ abstract class CDbMigration extends yii\base\Component
{
echo " > drop foreign key $name from table $table ...";
$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";
}
@ -360,7 +354,7 @@ abstract class CDbMigration extends yii\base\Component
{
echo " > create" . ($unique ? ' unique' : '') . " index $name on $table ($column) ...";
$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";
}
@ -373,7 +367,7 @@ abstract class CDbMigration extends yii\base\Component
{
echo " > drop index $name ...";
$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";
}
}

106
framework/db/QueryBuilder.php

@ -26,7 +26,7 @@ class QueryBuilder extends \yii\base\Object
/**
* @var Connection the database connection.
*/
public $connection;
public $db;
/**
* @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.
@ -46,7 +46,7 @@ class QueryBuilder extends \yii\base\Object
*/
public function __construct($connection, $config = array())
{
$this->connection = $connection;
$this->db = $connection;
parent::__construct($config);
}
@ -96,7 +96,7 @@ class QueryBuilder extends \yii\base\Object
$placeholders = array();
$count = 0;
foreach ($columns as $name => $value) {
$names[] = $this->connection->quoteColumnName($name);
$names[] = $this->db->quoteColumnName($name);
if ($value instanceof Expression) {
$placeholders[] = $value->expression;
foreach ($value->params as $n => $v) {
@ -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(', ', $placeholders) . ')';
}
@ -141,17 +141,17 @@ class QueryBuilder extends \yii\base\Object
$count = 0;
foreach ($columns as $name => $value) {
if ($value instanceof Expression) {
$lines[] = $this->connection->quoteColumnName($name) . '=' . $value->expression;
$lines[] = $this->db->quoteColumnName($name) . '=' . $value->expression;
foreach ($value->params as $n => $v) {
$params[$n] = $v;
}
} else {
$lines[] = $this->connection->quoteColumnName($name) . '=:p' . $count;
$lines[] = $this->db->quoteColumnName($name) . '=:p' . $count;
$params[':p' . $count] = $value;
$count++;
}
}
$sql = 'UPDATE ' . $this->connection->quoteTableName($table) . ' SET ' . implode(', ', $lines);
$sql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $lines);
if (($where = $this->buildCondition($condition)) !== '') {
$sql .= ' WHERE ' . $where;
}
@ -176,7 +176,7 @@ class QueryBuilder extends \yii\base\Object
*/
public function delete($table, $condition = '')
{
$sql = 'DELETE FROM ' . $this->connection->quoteTableName($table);
$sql = 'DELETE FROM ' . $this->db->quoteTableName($table);
if (($where = $this->buildCondition($condition)) !== '') {
$sql .= ' WHERE ' . $where;
}
@ -214,12 +214,12 @@ class QueryBuilder extends \yii\base\Object
$cols = array();
foreach ($columns as $name => $type) {
if (is_string($name)) {
$cols[] = "\t" . $this->connection->quoteColumnName($name) . ' ' . $this->getColumnType($type);
$cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type);
} else {
$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;
}
@ -231,7 +231,7 @@ class QueryBuilder extends \yii\base\Object
*/
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
*/
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
*/
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
*/
public function addColumn($table, $column, $type)
{
return 'ALTER TABLE ' . $this->connection->quoteTableName($table)
. ' ADD ' . $this->connection->quoteColumnName($column) . ' '
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' ADD ' . $this->db->quoteColumnName($column) . ' '
. $this->getColumnType($type);
}
@ -278,8 +278,8 @@ class QueryBuilder extends \yii\base\Object
*/
public function dropColumn($table, $column)
{
return "ALTER TABLE " . $this->connection->quoteTableName($table)
. " DROP COLUMN " . $this->connection->quoteColumnName($column);
return "ALTER TABLE " . $this->db->quoteTableName($table)
. " DROP COLUMN " . $this->db->quoteColumnName($column);
}
/**
@ -291,9 +291,9 @@ class QueryBuilder extends \yii\base\Object
*/
public function renameColumn($table, $oldName, $newName)
{
return "ALTER TABLE " . $this->connection->quoteTableName($table)
. " RENAME COLUMN " . $this->connection->quoteColumnName($oldName)
. " TO " . $this->connection->quoteColumnName($newName);
return "ALTER TABLE " . $this->db->quoteTableName($table)
. " RENAME COLUMN " . $this->db->quoteColumnName($oldName)
. " TO " . $this->db->quoteColumnName($newName);
}
/**
@ -308,9 +308,9 @@ class QueryBuilder extends \yii\base\Object
*/
public function alterColumn($table, $column, $type)
{
return 'ALTER TABLE ' . $this->connection->quoteTableName($table) . ' CHANGE '
. $this->connection->quoteColumnName($column) . ' '
. $this->connection->quoteColumnName($column) . ' '
return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
. $this->db->quoteColumnName($column) . ' '
. $this->db->quoteColumnName($column) . ' '
. $this->getColumnType($type);
}
@ -330,10 +330,10 @@ class QueryBuilder extends \yii\base\Object
*/
public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
{
$sql = 'ALTER TABLE ' . $this->connection->quoteTableName($table)
. ' ADD CONSTRAINT ' . $this->connection->quoteColumnName($name)
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name)
. ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
. ' REFERENCES ' . $this->connection->quoteTableName($refTable)
. ' REFERENCES ' . $this->db->quoteTableName($refTable)
. ' (' . $this->buildColumns($refColumns) . ')';
if ($delete !== null) {
$sql .= ' ON DELETE ' . $delete;
@ -352,8 +352,8 @@ class QueryBuilder extends \yii\base\Object
*/
public function dropForeignKey($name, $table)
{
return 'ALTER TABLE ' . $this->connection->quoteTableName($table)
. ' DROP CONSTRAINT ' . $this->connection->quoteColumnName($name);
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
}
/**
@ -369,8 +369,8 @@ class QueryBuilder extends \yii\base\Object
public function createIndex($name, $table, $columns, $unique = false)
{
return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
. $this->connection->quoteTableName($name) . ' ON '
. $this->connection->quoteTableName($table)
. $this->db->quoteTableName($name) . ' ON '
. $this->db->quoteTableName($table)
. ' (' . $this->buildColumns($columns) . ')';
}
@ -382,7 +382,7 @@ class QueryBuilder extends \yii\base\Object
*/
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
*/
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
*/
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
$parts[] = $this->buildInCondition('in', array($column, $value));
} else {
if (strpos($column, '(') === false) {
$column = $this->connection->quoteColumnName($column);
$column = $this->db->quoteColumnName($column);
}
if ($value === null) {
$parts[] = "$column IS NULL";
} elseif (is_string($value)) {
$parts[] = "$column=" . $this->connection->quoteValue($value);
$parts[] = "$column=" . $this->db->quoteValue($value);
} else {
$parts[] = "$column=$value";
}
@ -544,10 +544,10 @@ class QueryBuilder extends \yii\base\Object
list($column, $value1, $value2) = $operands;
if (strpos($column, '(') === false) {
$column = $this->connection->quoteColumnName($column);
$column = $this->db->quoteColumnName($column);
}
$value1 = is_string($value1) ? $this->connection->quoteValue($value1) : (string)$value1;
$value2 = is_string($value2) ? $this->connection->quoteValue($value2) : (string)$value2;
$value1 = is_string($value1) ? $this->db->quoteValue($value1) : (string)$value1;
$value2 = is_string($value2) ? $this->db->quoteValue($value2) : (string)$value2;
return "$column $operator $value1 AND $value2";
}
@ -578,13 +578,13 @@ class QueryBuilder extends \yii\base\Object
if ($value === null) {
$values[$i] = 'NULL';
} 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) {
$column = $this->connection->quoteColumnName($column);
$column = $this->db->quoteColumnName($column);
}
if (count($values) > 1) {
@ -599,7 +599,7 @@ class QueryBuilder extends \yii\base\Object
{
foreach ($columns as $i => $column) {
if (strpos($column, '(') === false) {
$columns[$i] = $this->connection->quoteColumnName($column);
$columns[$i] = $this->db->quoteColumnName($column);
}
}
$vss = array();
@ -607,7 +607,7 @@ class QueryBuilder extends \yii\base\Object
$vs = array();
foreach ($columns as $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 {
$vs[] = 'NULL';
}
@ -639,12 +639,12 @@ class QueryBuilder extends \yii\base\Object
}
if (strpos($column, '(') === false) {
$column = $this->connection->quoteColumnName($column);
$column = $this->db->quoteColumnName($column);
}
$parts = array();
foreach ($values as $value) {
$parts[] = "$column $operator " . $this->connection->quoteValue($value);
$parts[] = "$column $operator " . $this->db->quoteValue($value);
}
return implode($andor, $parts);
@ -679,9 +679,9 @@ class QueryBuilder extends \yii\base\Object
$columns[$i] = (string)$column;
} elseif (strpos($column, '(') === false) {
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 {
$columns[$i] = $this->connection->quoteColumnName($column);
$columns[$i] = $this->db->quoteColumnName($column);
}
}
}
@ -713,9 +713,9 @@ class QueryBuilder extends \yii\base\Object
foreach ($tables as $i => $table) {
if (strpos($table, '(') === false) {
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 {
$tables[$i] = $this->connection->quoteTableName($table);
$tables[$i] = $this->db->quoteTableName($table);
}
}
}
@ -746,9 +746,9 @@ class QueryBuilder extends \yii\base\Object
$table = $join[1];
if (strpos($table, '(') === false) {
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 {
$table = $this->connection->quoteTableName($table);
$table = $this->db->quoteTableName($table);
}
}
$joins[$i] = $join[0] . ' ' . $table;
@ -821,9 +821,9 @@ class QueryBuilder extends \yii\base\Object
$columns[$i] = (string)$column;
} elseif (strpos($column, '(') === false) {
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 {
$columns[$i] = $this->connection->quoteColumnName($column);
$columns[$i] = $this->db->quoteColumnName($column);
}
}
}
@ -889,7 +889,7 @@ class QueryBuilder extends \yii\base\Object
if (is_object($column)) {
$columns[$i] = (string)$column;
} elseif (strpos($column, '(') === false) {
$columns[$i] = $this->connection->quoteColumnName($column);
$columns[$i] = $this->db->quoteColumnName($column);
}
}
return is_array($columns) ? implode(', ', $columns) : $columns;

22
framework/db/Schema.php

@ -48,7 +48,7 @@ abstract class Schema extends \yii\base\Object
/**
* @var Connection the database connection
*/
public $connection;
public $db;
/**
* @var array list of ALL table names in the database
*/
@ -82,7 +82,7 @@ abstract class Schema extends \yii\base\Object
return $this->_tables[$name];
}
$db = $this->connection;
$db = $this->db;
$realName = $this->getRealTableName($name);
/** @var $cache \yii\caching\Cache */
@ -109,7 +109,7 @@ abstract class Schema extends \yii\base\Object
*/
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
public function refresh()
{
/** @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) {
$cache->delete($this->getCacheKey($name));
}
@ -185,7 +185,7 @@ abstract class Schema extends \yii\base\Object
*/
public function createQueryBuilder()
{
return new QueryBuilder($this->connection);
return new QueryBuilder($this->db);
}
/**
@ -210,8 +210,8 @@ abstract class Schema extends \yii\base\Object
*/
public function getLastInsertID($sequenceName = '')
{
if ($this->connection->isActive) {
return $this->connection->pdo->lastInsertId($sequenceName);
if ($this->db->isActive) {
return $this->db->pdo->lastInsertId($sequenceName);
} else {
throw new InvalidCallException('DB Connection is not active.');
}
@ -230,8 +230,8 @@ abstract class Schema extends \yii\base\Object
return $str;
}
$this->connection->open();
if (($value = $this->connection->pdo->quote($str)) !== false) {
$this->db->open();
if (($value = $this->db->pdo->quote($str)) !== false) {
return $value;
} else { // the driver doesn't support quote (e.g. oci)
return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
@ -319,9 +319,9 @@ abstract class Schema extends \yii\base\Object
*/
public function getRealTableName($name)
{
if ($this->connection->enableAutoQuoting && strpos($name, '{{') !== false) {
if ($this->db->enableAutoQuoting && strpos($name, '{{') !== false) {
$name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name);
return str_replace('%', $this->connection->tablePrefix, $name);
return str_replace('%', $this->db->tablePrefix, $name);
} else {
return $name;
}

18
framework/db/Transaction.php

@ -41,7 +41,7 @@ class Transaction extends \yii\base\Object
/**
* @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
* can [[commit()]] or [[rollBack()]]. This property is set true when the transaction is started.
@ -65,12 +65,12 @@ class Transaction extends \yii\base\Object
public function begin()
{
if (!$this->_active) {
if ($this->connection === null) {
throw new InvalidConfigException('Transaction.connection must be set.');
if ($this->db === null) {
throw new InvalidConfigException('Transaction::db must be set.');
}
\Yii::trace('Starting transaction', __CLASS__);
$this->connection->open();
$this->connection->pdo->beginTransaction();
$this->db->open();
$this->db->pdo->beginTransaction();
$this->_active = true;
}
}
@ -81,9 +81,9 @@ class Transaction extends \yii\base\Object
*/
public function commit()
{
if ($this->_active && $this->connection && $this->connection->isActive) {
if ($this->_active && $this->db && $this->db->isActive) {
\Yii::trace('Committing transaction', __CLASS__);
$this->connection->pdo->commit();
$this->db->pdo->commit();
$this->_active = false;
} else {
throw new Exception('Failed to commit transaction: transaction was inactive.');
@ -96,9 +96,9 @@ class Transaction extends \yii\base\Object
*/
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__);
$this->connection->pdo->commit();
$this->db->pdo->commit();
$this->_active = false;
} else {
throw new Exception('Failed to roll back transaction: transaction was inactive.');

22
framework/db/mysql/QueryBuilder.php

@ -51,8 +51,8 @@ class QueryBuilder extends \yii\db\QueryBuilder
*/
public function renameColumn($table, $oldName, $newName)
{
$quotedTable = $this->connection->quoteTableName($table);
$row = $this->connection->createCommand('SHOW CREATE TABLE ' . $quotedTable)->queryRow();
$quotedTable = $this->db->quoteTableName($table);
$row = $this->db->createCommand('SHOW CREATE TABLE ' . $quotedTable)->queryRow();
if ($row === false) {
throw new Exception("Unable to find '$oldName' in table '$table'.");
}
@ -66,16 +66,16 @@ class QueryBuilder extends \yii\db\QueryBuilder
foreach ($matches[1] as $i => $c) {
if ($c === $oldName) {
return "ALTER TABLE $quotedTable CHANGE "
. $this->connection->quoteColumnName($oldName) . ' '
. $this->connection->quoteColumnName($newName) . ' '
. $this->db->quoteColumnName($oldName) . ' '
. $this->db->quoteColumnName($newName) . ' '
. $matches[2][$i];
}
}
}
// try to give back a SQL anyway
return "ALTER TABLE $quotedTable CHANGE "
. $this->connection->quoteColumnName($oldName) . ' '
. $this->connection->quoteColumnName($newName);
. $this->db->quoteColumnName($oldName) . ' '
. $this->db->quoteColumnName($newName);
}
/**
@ -86,8 +86,8 @@ class QueryBuilder extends \yii\db\QueryBuilder
*/
public function dropForeignKey($name, $table)
{
return 'ALTER TABLE ' . $this->connection->quoteTableName($table)
. ' DROP FOREIGN KEY ' . $this->connection->quoteColumnName($name);
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' DROP FOREIGN KEY ' . $this->db->quoteColumnName($name);
}
/**
@ -102,12 +102,12 @@ class QueryBuilder extends \yii\db\QueryBuilder
*/
public function resetSequence($tableName, $value = null)
{
$table = $this->connection->getTableSchema($tableName);
$table = $this->db->getTableSchema($tableName);
if ($table !== null && $table->sequenceName !== null) {
$tableName = $this->connection->quoteTableName($tableName);
$tableName = $this->db->quoteTableName($tableName);
if ($value === null) {
$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 {
$value = (int)$value;
}

14
framework/db/mysql/Schema.php

@ -1,6 +1,6 @@
<?php
/**
* Driver class file.
* Schema class file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC
@ -13,7 +13,7 @@ use yii\db\TableSchema;
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>
* @since 2.0
@ -79,7 +79,7 @@ class Schema extends \yii\db\Schema
*/
public function createQueryBuilder()
{
return new QueryBuilder($this->connection);
return new QueryBuilder($this->db);
}
/**
@ -183,9 +183,9 @@ class Schema extends \yii\db\Schema
*/
protected function findColumns($table)
{
$sql = 'SHOW COLUMNS FROM ' . $this->quoteSimpleTableName($table->name);
$sql = 'SHOW FULL COLUMNS FROM ' . $this->quoteSimpleTableName($table->name);
try {
$columns = $this->connection->createCommand($sql)->queryAll();
$columns = $this->db->createCommand($sql)->queryAll();
} catch (\Exception $e) {
return false;
}
@ -208,7 +208,7 @@ class Schema extends \yii\db\Schema
*/
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'])) {
$sql = $row['Create Table'];
} else {
@ -243,6 +243,6 @@ class Schema extends \yii\db\Schema
if ($schema !== '') {
$sql .= ' FROM ' . $this->quoteSimpleTableName($schema);
}
return $this->connection->createCommand($sql)->queryColumn();
return $this->db->createCommand($sql)->queryColumn();
}
}

6
framework/db/sqlite/QueryBuilder.php

@ -54,7 +54,7 @@ class QueryBuilder extends \yii\db\QueryBuilder
*/
public function resetSequence($tableName, $value = null)
{
$db = $this->connection;
$db = $this->db;
$table = $db->getTableSchema($tableName);
if ($table !== null && $table->sequenceName !== null) {
if ($value === null) {
@ -94,7 +94,7 @@ class QueryBuilder extends \yii\db\QueryBuilder
*/
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
*/
public function dropIndex($name, $table)
{
return 'DROP INDEX ' . $this->connection->quoteTableName($name);
return 'DROP INDEX ' . $this->db->quoteTableName($name);
}
/**

12
framework/db/sqlite/Schema.php

@ -1,6 +1,6 @@
<?php
/**
* Driver class file.
* Schema class file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC
@ -13,7 +13,7 @@ use yii\db\TableSchema;
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>
* @since 2.0
@ -58,7 +58,7 @@ class Schema extends \yii\db\Schema
*/
public function createQueryBuilder()
{
return new QueryBuilder($this->connection);
return new QueryBuilder($this->db);
}
/**
@ -70,7 +70,7 @@ class Schema extends \yii\db\Schema
protected function findTableNames($schema = '')
{
$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
protected function findColumns($table)
{
$sql = "PRAGMA table_info(" . $this->quoteSimpleTableName($table->name) . ')';
$columns = $this->connection->createCommand($sql)->queryAll();
$columns = $this->db->createCommand($sql)->queryAll();
if (empty($columns)) {
return false;
}
@ -126,7 +126,7 @@ class Schema extends \yii\db\Schema
protected function findConstraints($table)
{
$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) {
$table->foreignKeys[] = array($key['table'], $key['from'] => $key['to']);
}

4
framework/logging/DbTarget.php

@ -65,7 +65,7 @@ class DbTarget extends Target
* @return \yii\db\Connection the DB connection instance
* @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) {
$this->_db = \Yii::$application->getComponent($this->connectionID);
@ -85,7 +85,7 @@ class DbTarget extends Target
$sql = "INSERT INTO {$this->tableName}
(level, category, log_time, message) VALUES
(:level, :category, :log_time, :message)";
$command = $this->getDbConnection()->createCommand($sql);
$command = $this->getDb()->createCommand($sql);
foreach ($this->messages as $message) {
$command->bindValues(array(
':level' => $message[1],

2
tests/unit/data/ar/ActiveRecord.php

@ -21,7 +21,7 @@ class ActiveRecord extends \yii\db\ActiveRecord
{
public static $db;
public static function getDbConnection()
public static function getDb()
{
return self::$db;
}

6
todo.md

@ -20,11 +20,8 @@
* a way to invalidate/clear cached data
* a command to clear cached data
- db
* sqlite, pgsql, sql server, oracle, db2 drivers
* pgsql, sql server, oracle, db2 drivers
* 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)
* mongodb
* key-value-based (should allow storage-specific methods additionally to generic ones)
@ -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.
- 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 view renderer from controller so it can be used separately (useful for sending emails from console etc.)
Loading…
Cancel
Save