Browse Source

renamed Driver to Schema.

tags/2.0.0-beta
Qiang Xue 12 years ago
parent
commit
e150b7fae7
  1. 102
      framework/db/Connection.php
  2. 57
      framework/db/Schema.php
  3. 2
      framework/db/Transaction.php
  4. 30
      framework/db/mysql/QueryBuilder.php
  5. 2
      framework/db/mysql/Schema.php
  6. 2
      framework/db/sqlite/Schema.php

102
framework/db/Connection.php

@ -10,6 +10,7 @@
namespace yii\db; namespace yii\db;
use yii\db\Exception; use yii\db\Exception;
use yii\base\BadConfigException;
/** /**
* Connection represents a connection to a database via [PDO](http://www.php.net/manual/en/ref.pdo.php). * Connection represents a connection to a database via [PDO](http://www.php.net/manual/en/ref.pdo.php).
@ -87,8 +88,8 @@ use yii\db\Exception;
* ~~~ * ~~~
* *
* @property boolean $isActive Whether the DB connection is established. This property is read-only. * @property boolean $isActive Whether the DB connection is established. This property is read-only.
* @property Transaction $currentTransaction The currently active transaction. Null if no active transaction. * @property Transaction $transaction The currently active transaction. Null if no active transaction.
* @property Driver $driver The database driver for the current connection. * @property Schema $schema The database schema information for the current connection.
* @property QueryBuilder $queryBuilder The query builder. * @property QueryBuilder $queryBuilder The query builder.
* @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the sequence object. * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the sequence object.
* @property string $driverName Name of the DB driver currently being used. * @property string $driverName Name of the DB driver currently being used.
@ -237,34 +238,34 @@ class Connection extends \yii\base\ApplicationComponent
*/ */
public $initSQLs; public $initSQLs;
/** /**
* @var array mapping between PDO driver names and [[Driver]] classes. * @var array mapping between PDO driver names and [[Schema]] classes.
* The keys of the array are PDO driver names while the values the corresponding * The keys of the array are PDO driver names while the values the corresponding
* driver class name or configuration. Please refer to [[\Yii::createObject]] for * schema class name or configuration. Please refer to [[\Yii::createObject()]] for
* details on how to specify a configuration. * details on how to specify a configuration.
* *
* This property is mainly used by [[getDriver()]] when fetching the database schema information. * This property is mainly used by [[getSchema()]] when fetching the database schema information.
* You normally do not need to set this property unless you want to use your own * You normally do not need to set this property unless you want to use your own
* [[Driver]] class to support DBMS that is not supported by Yii. * [[Schema]] class to support DBMS that is not supported by Yii.
*/ */
public $driverMap = array( public $schemaMap = array(
'pgsql' => 'yii\db\pgsql\Driver', // PostgreSQL 'pgsql' => 'yii\db\pgsql\Schema', // PostgreSQL
'mysqli' => 'yii\db\mysql\Driver', // MySQL 'mysqli' => 'yii\db\mysql\Schema', // MySQL
'mysql' => 'yii\db\mysql\Driver', // MySQL 'mysql' => 'yii\db\mysql\Schema', // MySQL
'sqlite' => 'yii\db\sqlite\Driver', // sqlite 3 'sqlite' => 'yii\db\sqlite\Schema', // sqlite 3
'sqlite2' => 'yii\db\sqlite\Driver', // sqlite 2 'sqlite2' => 'yii\db\sqlite\Schema', // sqlite 2
'mssql' => 'yi\db\dao\mssql\Driver', // Mssql driver on windows hosts 'mssql' => 'yi\db\dao\mssql\Schema', // Mssql driver on windows hosts
'dblib' => 'yii\db\mssql\Driver', // dblib drivers on linux (and maybe others os) hosts 'dblib' => 'yii\db\mssql\Schema', // dblib drivers on linux (and maybe others os) hosts
'sqlsrv' => 'yii\db\mssql\Driver', // Mssql 'sqlsrv' => 'yii\db\mssql\Schema', // Mssql
'oci' => 'yii\db\oci\Driver', // Oracle driver 'oci' => 'yii\db\oci\Schema', // Oracle driver
); );
/** /**
* @var Transaction the currently active transaction * @var Transaction the currently active transaction
*/ */
private $_transaction; private $_transaction;
/** /**
* @var Driver the database driver * @var Schema the database schema
*/ */
private $_driver; private $_schema;
/** /**
* Closes the connection when this component is being serialized. * Closes the connection when this component is being serialized.
@ -330,7 +331,7 @@ class Connection extends \yii\base\ApplicationComponent
{ {
if ($this->pdo === null) { if ($this->pdo === null) {
if (empty($this->dsn)) { if (empty($this->dsn)) {
throw new Exception('Connection.dsn cannot be empty.'); throw new BadConfigException('Connection.dsn cannot be empty.');
} }
try { try {
\Yii::trace('Opening DB connection: ' . $this->dsn, __CLASS__); \Yii::trace('Opening DB connection: ' . $this->dsn, __CLASS__);
@ -354,7 +355,7 @@ class Connection extends \yii\base\ApplicationComponent
if ($this->pdo !== null) { if ($this->pdo !== null) {
\Yii::trace('Closing DB connection: ' . $this->dsn, __CLASS__); \Yii::trace('Closing DB connection: ' . $this->dsn, __CLASS__);
$this->pdo = null; $this->pdo = null;
$this->_driver = null; $this->_schema = null;
$this->_transaction = null; $this->_transaction = null;
} }
} }
@ -372,7 +373,7 @@ class Connection extends \yii\base\ApplicationComponent
if (($pos = strpos($this->dsn, ':')) !== false) { if (($pos = strpos($this->dsn, ':')) !== false) {
$driver = strtolower(substr($this->dsn, 0, $pos)); $driver = strtolower(substr($this->dsn, 0, $pos));
if ($driver === 'mssql' || $driver === 'dblib' || $driver === 'sqlsrv') { if ($driver === 'mssql' || $driver === 'dblib' || $driver === 'sqlsrv') {
$pdoClass = 'mssql\PDO'; $pdoClass = 'yii\db\mssql\PDO';
} }
} }
return new $pdoClass($this->dsn, $this->username, $this->password, $this->attributes); return new $pdoClass($this->dsn, $this->username, $this->password, $this->attributes);
@ -421,13 +422,9 @@ class Connection extends \yii\base\ApplicationComponent
* Returns the currently active transaction. * Returns the currently active transaction.
* @return Transaction the currently active transaction. Null if no active transaction. * @return Transaction the currently active transaction. Null if no active transaction.
*/ */
public function getCurrentTransaction() public function getTransaction()
{ {
if ($this->_transaction !== null && $this->_transaction->isActive) { return $this->_transaction && $this->_transaction->isActive ? $this->_transaction : null;
return $this->_transaction;
} else {
return null;
}
} }
/** /**
@ -445,19 +442,22 @@ class Connection extends \yii\base\ApplicationComponent
} }
/** /**
* Returns the metadata information for the underlying database. * Returns the schema information for the database opened by this connection.
* @return Driver the metadata information for the underlying database. * @return Schema the schema information for the database opened by this connection.
* @throws BadConfigException if there is no support for the current driver type
*/ */
public function getDriver() public function getSchema()
{ {
if ($this->_driver !== null) { if ($this->_schema !== null) {
return $this->_driver; return $this->_schema;
} else { } else {
$driver = $this->getDriverName(); $driver = $this->getDriverName();
if (isset($this->driverMap[$driver])) { if (isset($this->schemaMap[$driver])) {
return $this->_driver = \Yii::createObject($this->driverMap[$driver], $this); $this->_schema = \Yii::createObject($this->schemaMap[$driver]);
$this->_schema->connection = $this;
return $this->_schema;
} else { } else {
throw new Exception("Connection does not support reading metadata for '$driver' database."); throw new BadConfigException("Connection does not support reading schema information for '$driver' DBMS.");
} }
} }
} }
@ -468,18 +468,18 @@ class Connection extends \yii\base\ApplicationComponent
*/ */
public function getQueryBuilder() public function getQueryBuilder()
{ {
return $this->getDriver()->getQueryBuilder(); return $this->getSchema()->getQueryBuilder();
} }
/** /**
* Obtains the metadata for the named table. * Obtains the schema information for the named table.
* @param string $name table name. The table name may contain schema name if any. Do not quote the table name. * @param string $name table name.
* @param boolean $refresh whether to reload the table schema even if it is found in the cache. * @param boolean $refresh whether to reload the table schema even if it is found in the cache.
* @return TableSchema table metadata. Null if the named table does not exist. * @return TableSchema table schema information. Null if the named table does not exist.
*/ */
public function getTableSchema($name, $refresh = false) public function getTableSchema($name, $refresh = false)
{ {
return $this->getDriver()->getTableSchema($name, $refresh); return $this->getSchema()->getTableSchema($name, $refresh);
} }
/** /**
@ -490,8 +490,7 @@ class Connection extends \yii\base\ApplicationComponent
*/ */
public function getLastInsertID($sequenceName = '') public function getLastInsertID($sequenceName = '')
{ {
$this->open(); return $this->getSchema()->getLastInsertID($sequenceName);
return $this->pdo->lastInsertId($sequenceName);
} }
/** /**
@ -503,16 +502,7 @@ class Connection extends \yii\base\ApplicationComponent
*/ */
public function quoteValue($str) public function quoteValue($str)
{ {
if (!is_string($str)) { return $this->getSchema()->quoteValue($str);
return $str;
}
$this->open();
if (($value = $this->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") . "'";
}
} }
/** /**
@ -525,7 +515,7 @@ class Connection extends \yii\base\ApplicationComponent
*/ */
public function quoteTableName($name) public function quoteTableName($name)
{ {
return $this->getDriver()->quoteTableName($name); return $this->getSchema()->quoteTableName($name);
} }
/** /**
@ -538,7 +528,7 @@ class Connection extends \yii\base\ApplicationComponent
*/ */
public function quoteColumnName($name) public function quoteColumnName($name)
{ {
return $this->getDriver()->quoteColumnName($name); return $this->getSchema()->quoteColumnName($name);
} }
/** /**
@ -587,7 +577,7 @@ class Connection extends \yii\base\ApplicationComponent
* and the second element the total time spent in SQL execution. * and the second element the total time spent in SQL execution.
* @see \yii\logging\Logger::getProfiling() * @see \yii\logging\Logger::getProfiling()
*/ */
public function getStats() public function getExecutionSummary()
{ {
$logger = \Yii::getLogger(); $logger = \Yii::getLogger();
$timings = $logger->getProfiling(array('yii\db\Command::query', 'yii\db\Command::execute')); $timings = $logger->getProfiling(array('yii\db\Command::query', 'yii\db\Command::execute'));

57
framework/db/Driver.php → framework/db/Schema.php

@ -12,18 +12,18 @@ namespace yii\db;
use yii\db\Exception; use yii\db\Exception;
/** /**
* Driver is the base class for all database driver classes. * Schema is the base class for concrete DBMS-specific schema classes.
* *
* Driver implements the DBMS-specific methods to support retrieving metadata of a database. * Schema represents the database schema information that is DBMS specific.
* *
* @property QueryBuilder $queryBuilder the query builder for this connection. * @property QueryBuilder $queryBuilder the query builder for the DBMS represented by this schema
* @property array $tableNames the names of all tables in this database. * @property array $tableNames the names of all tables in this database.
* @property array $tableSchemas the metadata for all tables in this database. * @property array $tableSchemas the schema information for all tables in this database.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
abstract class Driver extends \yii\base\Object abstract class Schema extends \yii\base\Object
{ {
/** /**
* The followings are the supported abstract column data types. * The followings are the supported abstract column data types.
@ -68,16 +68,6 @@ abstract class Driver extends \yii\base\Object
*/ */
abstract protected function loadTableSchema($name); abstract protected function loadTableSchema($name);
/**
* Constructor.
* @param Connection $connection database connection.
* @param array $config name-value pairs that will be used to initialize the object properties
*/
public function __construct($connection, $config = array())
{
$this->connection = $connection;
parent::__construct($config);
}
/** /**
* Obtains the metadata for the named table. * Obtains the metadata for the named table.
@ -205,6 +195,43 @@ abstract class Driver extends \yii\base\Object
} }
/** /**
* Returns the ID of the last inserted row or sequence value.
* @param string $sequenceName name of the sequence object (required by some DBMS)
* @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
* @see http://www.php.net/manual/en/function.PDO-lastInsertId.php
*/
public function getLastInsertID($sequenceName = '')
{
if ($this->connection->isActive) {
return $this->connection->pdo->lastInsertId($sequenceName);
} else {
throw new Exception('DB Connection is not active.');
}
}
/**
* Quotes a string value for use in a query.
* Note that if the parameter is not a string, it will be returned without change.
* @param string $str string to be quoted
* @return string the properly quoted string
* @see http://www.php.net/manual/en/function.PDO-quote.php
*/
public function quoteValue($str)
{
if (!is_string($str)) {
return $str;
}
$this->connection->open();
if (($value = $this->connection->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") . "'";
}
}
/**
* Quotes a table name for use in a query. * Quotes a table name for use in a query.
* If the table name contains schema prefix, the prefix will also be properly quoted. * If the table name contains schema prefix, the prefix will also be properly quoted.
* If the table name is already quoted or contains special characters including '(', '[[' and '{{', * If the table name is already quoted or contains special characters including '(', '[[' and '{{',

2
framework/db/Transaction.php

@ -67,7 +67,7 @@ class Transaction extends \yii\base\Object
{ {
if (!$this->_active) { if (!$this->_active) {
if ($this->connection === null) { if ($this->connection === null) {
throw new BadConfigException('Transaction::connection must be set.'); throw new BadConfigException('Transaction.connection must be set.');
} }
\Yii::trace('Starting transaction', __CLASS__); \Yii::trace('Starting transaction', __CLASS__);
$this->connection->open(); $this->connection->open();

30
framework/db/mysql/QueryBuilder.php

@ -23,21 +23,21 @@ class QueryBuilder extends \yii\db\QueryBuilder
* @var array mapping from abstract column types (keys) to physical column types (values). * @var array mapping from abstract column types (keys) to physical column types (values).
*/ */
public $typeMap = array( public $typeMap = array(
Driver::TYPE_PK => 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY', Schema::TYPE_PK => 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY',
Driver::TYPE_STRING => 'varchar(255)', Schema::TYPE_STRING => 'varchar(255)',
Driver::TYPE_TEXT => 'text', Schema::TYPE_TEXT => 'text',
Driver::TYPE_SMALLINT => 'smallint(6)', Schema::TYPE_SMALLINT => 'smallint(6)',
Driver::TYPE_INTEGER => 'int(11)', Schema::TYPE_INTEGER => 'int(11)',
Driver::TYPE_BIGINT => 'bigint(20)', Schema::TYPE_BIGINT => 'bigint(20)',
Driver::TYPE_FLOAT => 'float', Schema::TYPE_FLOAT => 'float',
Driver::TYPE_DECIMAL => 'decimal', Schema::TYPE_DECIMAL => 'decimal',
Driver::TYPE_DATETIME => 'datetime', Schema::TYPE_DATETIME => 'datetime',
Driver::TYPE_TIMESTAMP => 'timestamp', Schema::TYPE_TIMESTAMP => 'timestamp',
Driver::TYPE_TIME => 'time', Schema::TYPE_TIME => 'time',
Driver::TYPE_DATE => 'date', Schema::TYPE_DATE => 'date',
Driver::TYPE_BINARY => 'blob', Schema::TYPE_BINARY => 'blob',
Driver::TYPE_BOOLEAN => 'tinyint(1)', Schema::TYPE_BOOLEAN => 'tinyint(1)',
Driver::TYPE_MONEY => 'decimal(19,4)', Schema::TYPE_MONEY => 'decimal(19,4)',
); );
/** /**

2
framework/db/mysql/Driver.php → framework/db/mysql/Schema.php

@ -18,7 +18,7 @@ use yii\db\ColumnSchema;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class Driver extends \yii\db\Driver class Schema extends \yii\db\Schema
{ {
/** /**
* @var array mapping from physical column types (keys) to abstract column types (values) * @var array mapping from physical column types (keys) to abstract column types (values)

2
framework/db/sqlite/Driver.php → framework/db/sqlite/Schema.php

@ -18,7 +18,7 @@ use yii\db\ColumnSchema;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class Driver extends \yii\db\Driver class Schema extends \yii\db\Schema
{ {
/** /**
* @var array mapping from physical column types (keys) to abstract column types (values) * @var array mapping from physical column types (keys) to abstract column types (values)
Loading…
Cancel
Save