Yii2 Bootstrap 3
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

357 lines
11 KiB

13 years ago
<?php
/**
13 years ago
* Driver class file.
13 years ago
*
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC
13 years ago
* @license http://www.yiiframework.com/license/
*/
namespace yii\db;
13 years ago
12 years ago
use yii\base\NotSupportedException;
use yii\base\InvalidCallException;
13 years ago
13 years ago
/**
* Schema is the base class for concrete DBMS-specific schema classes.
13 years ago
*
* Schema represents the database schema information that is DBMS specific.
13 years ago
*
* @property QueryBuilder $queryBuilder the query builder for the DBMS represented by this schema
13 years ago
* @property array $tableNames the names of all tables in this database.
* @property array $tableSchemas the schema information for all tables in this database.
13 years ago
*
* @author Qiang Xue <qiang.xue@gmail.com>
13 years ago
* @since 2.0
13 years ago
*/
abstract class Schema extends \yii\base\Object
13 years ago
{
13 years ago
/**
13 years ago
* The followings are the supported abstract column data types.
*/
13 years ago
const TYPE_PK = 'pk';
13 years ago
const TYPE_STRING = 'string';
const TYPE_TEXT = 'text';
const TYPE_SMALLINT = 'smallint';
const TYPE_INTEGER = 'integer';
const TYPE_BIGINT = 'bigint';
const TYPE_FLOAT = 'float';
const TYPE_DECIMAL = 'decimal';
const TYPE_DATETIME = 'datetime';
const TYPE_TIMESTAMP = 'timestamp';
const TYPE_TIME = 'time';
const TYPE_DATE = 'date';
const TYPE_BINARY = 'binary';
const TYPE_BOOLEAN = 'boolean';
const TYPE_MONEY = 'money';
/**
13 years ago
* @var Connection the database connection
13 years ago
*/
12 years ago
public $db;
13 years ago
/**
* @var array list of ALL table names in the database
*/
13 years ago
private $_tableNames = array();
13 years ago
/**
13 years ago
* @var array list of loaded table metadata (table name => TableSchema)
13 years ago
*/
13 years ago
private $_tables = array();
13 years ago
/**
* @var QueryBuilder the query builder for this database
*/
13 years ago
private $_builder;
/**
* Loads the metadata for the specified table.
* @param string $name table name
13 years ago
* @return TableSchema DBMS-dependent table metadata, null if the table does not exist.
13 years ago
*/
13 years ago
abstract protected function loadTableSchema($name);
13 years ago
/**
* Obtains the metadata for the named table.
13 years ago
* @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
13 years ago
* @param boolean $refresh whether to reload the table schema even if it is found in the cache.
13 years ago
* @return TableSchema table metadata. Null if the named table does not exist.
13 years ago
*/
13 years ago
public function getTableSchema($name, $refresh = false)
13 years ago
{
13 years ago
if (isset($this->_tables[$name]) && !$refresh) {
13 years ago
return $this->_tables[$name];
13 years ago
}
13 years ago
12 years ago
$db = $this->db;
$realName = $this->getRealTableName($name);
13 years ago
/** @var $cache \yii\caching\Cache */
if ($db->enableSchemaCache && ($cache = \Yii::$application->getComponent($db->schemaCacheID)) !== null && !in_array($name, $db->schemaCacheExclude, true)) {
13 years ago
$key = $this->getCacheKey($name);
if ($refresh || ($table = $cache->get($key)) === false) {
13 years ago
$table = $this->loadTableSchema($realName);
if ($table !== null) {
$cache->set($key, $table, $db->schemaCacheDuration);
13 years ago
}
}
13 years ago
$this->_tables[$name] = $table;
13 years ago
} else {
13 years ago
$this->_tables[$name] = $table = $this->loadTableSchema($realName);
}
13 years ago
13 years ago
return $table;
13 years ago
}
/**
13 years ago
* Returns the cache key for the specified table name.
* @param string $name the table name
* @return string the cache key
*/
public function getCacheKey($name)
{
12 years ago
return __CLASS__ . "/{$this->db->dsn}/{$this->db->username}/{$name}";
13 years ago
}
/**
13 years ago
* Returns the metadata for all tables in the database.
12 years ago
* @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
* @param boolean $refresh whether to fetch the latest available table schemas. If this is false,
* cached data may be returned if available.
13 years ago
* @return array the metadata for all tables in the database.
12 years ago
* Each array element is an instance of [[TableSchema]] or its child class.
13 years ago
*/
12 years ago
public function getTableSchemas($schema = '', $refresh = false)
13 years ago
{
$tables = array();
12 years ago
foreach ($this->getTableNames($schema, $refresh) as $name) {
if ($schema !== '') {
$name = $schema . '.' . $name;
}
if (($table = $this->getTableSchema($name, $refresh)) !== null) {
13 years ago
$tables[] = $table;
}
13 years ago
}
return $tables;
}
/**
* Returns all table names in the database.
12 years ago
* @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
13 years ago
* If not empty, the returned table names will be prefixed with the schema name.
13 years ago
* @param boolean $refresh whether to fetch the latest available table names. If this is false,
* table names fetched previously (if available) will be returned.
13 years ago
* @return array all table names in the database.
*/
13 years ago
public function getTableNames($schema = '', $refresh = false)
13 years ago
{
13 years ago
if (!isset($this->_tableNames[$schema]) || $refresh) {
13 years ago
$this->_tableNames[$schema] = $this->findTableNames($schema);
13 years ago
}
13 years ago
return $this->_tableNames[$schema];
}
/**
13 years ago
* @return QueryBuilder the query builder for this connection.
13 years ago
*/
13 years ago
public function getQueryBuilder()
13 years ago
{
13 years ago
if ($this->_builder === null) {
$this->_builder = $this->createQueryBuilder();
}
return $this->_builder;
13 years ago
}
/**
* Refreshes the schema.
* This method cleans up all cached table schemas so that they can be re-created later
* to reflect the database schema change.
13 years ago
*/
public function refresh()
13 years ago
{
/** @var $cache \yii\caching\Cache */
12 years ago
if ($this->db->enableSchemaCache && ($cache = \Yii::$application->getComponent($this->db->schemaCacheID)) !== null) {
foreach ($this->_tables as $name => $table) {
$cache->delete($this->getCacheKey($name));
13 years ago
}
}
12 years ago
$this->_tableNames = array();
$this->_tables = array();
}
/**
* Creates a query builder for the database.
* This method may be overridden by child classes to create a DBMS-specific query builder.
* @return QueryBuilder query builder instance
*/
public function createQueryBuilder()
{
12 years ago
return new QueryBuilder($this->db);
}
/**
* Returns all table names in the database.
* This method should be overridden by child classes in order to support this feature
* because the default implementation simply throws an exception.
* @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
12 years ago
* @return array all table names in the database. The names have NO the schema name prefix.
* @throws NotSupportedException if this method is called
*/
protected function findTableNames($schema = '')
{
12 years ago
throw new NotSupportedException(get_class($this) . ' does not support fetching all table names.');
13 years ago
}
/**
* 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
* @throws InvalidCallException if the DB connection is not active
* @see http://www.php.net/manual/en/function.PDO-lastInsertId.php
*/
public function getLastInsertID($sequenceName = '')
{
12 years ago
if ($this->db->isActive) {
return $this->db->pdo->lastInsertId($sequenceName);
} else {
throw new InvalidCallException('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;
}
12 years ago
$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") . "'";
}
}
/**
13 years ago
* 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 is already quoted or contains special characters including '(', '[[' and '{{',
* then this method will do nothing.
13 years ago
* @param string $name table name
* @return string the properly quoted table name
* @see quoteSimpleTableName
*/
public function quoteTableName($name)
{
if (strpos($name, '(') !== false || strpos($name, '[[') !== false || strpos($name, '{{') !== false) {
return $name;
}
13 years ago
if (strpos($name, '.') === false) {
13 years ago
return $this->quoteSimpleTableName($name);
13 years ago
}
13 years ago
$parts = explode('.', $name);
13 years ago
foreach ($parts as $i => $part) {
13 years ago
$parts[$i] = $this->quoteSimpleTableName($part);
13 years ago
}
13 years ago
return implode('.', $parts);
}
/**
* Quotes a column name for use in a query.
* If the column name contains prefix, the prefix will also be properly quoted.
* If the column name is already quoted or contains special characters including '(', '[[' and '{{',
* then this method will do nothing.
13 years ago
* @param string $name column name
* @return string the properly quoted column name
* @see quoteSimpleColumnName
*/
public function quoteColumnName($name)
{
if (strpos($name, '(') !== false || strpos($name, '[[') !== false || strpos($name, '{{') !== false) {
return $name;
}
13 years ago
if (($pos = strrpos($name, '.')) !== false) {
13 years ago
$prefix = $this->quoteTableName(substr($name, 0, $pos)) . '.';
$name = substr($name, $pos + 1);
13 years ago
} else {
13 years ago
$prefix = '';
13 years ago
}
13 years ago
return $prefix . $this->quoteSimpleColumnName($name);
13 years ago
}
/**
* Quotes a simple table name for use in a query.
* A simple table name should contain the table name only without any schema prefix.
* If the table name is already quoted, this method will do nothing.
* @param string $name table name
* @return string the properly quoted table name
13 years ago
*/
public function quoteSimpleTableName($name)
13 years ago
{
return strpos($name, "'") !== false ? $name : "'" . $name . "'";
13 years ago
}
/**
* Quotes a simple column name for use in a query.
* A simple column name should contain the column name only without any prefix.
* If the column name is already quoted or is the asterisk character '*', this method will do nothing.
* @param string $name column name
* @return string the properly quoted column name
13 years ago
*/
public function quoteSimpleColumnName($name)
13 years ago
{
return strpos($name, '"') !== false || $name === '*' ? $name : '"' . $name . '"';
13 years ago
}
/**
* Returns the real name of a table name.
* This method will strip off curly brackets from the given table name
* and replace the percentage character in the name with [[Connection::tablePrefix]].
* @param string $name the table name to be converted
* @return string the real name of the given table name
13 years ago
*/
public function getRealTableName($name)
13 years ago
{
12 years ago
if ($this->db->enableAutoQuoting && strpos($name, '{{') !== false) {
$name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name);
12 years ago
return str_replace('%', $this->db->tablePrefix, $name);
} else {
return $name;
}
13 years ago
}
12 years ago
/**
* Extracts the PHP type from abstract DB type.
* @param ColumnSchema $column the column schema information
12 years ago
* @return string PHP type name
*/
protected function getColumnPhpType($column)
12 years ago
{
static $typeMap = array( // abstract type => php type
'smallint' => 'integer',
'integer' => 'integer',
'bigint' => 'integer',
'boolean' => 'boolean',
'float' => 'double',
);
if (isset($typeMap[$column->type])) {
if ($column->type === 'bigint') {
return PHP_INT_SIZE == 8 && !$column->unsigned ? 'integer' : 'string';
} elseif ($column->type === 'integer') {
return PHP_INT_SIZE == 4 && $column->unsigned ? 'string' : 'integer';
12 years ago
} else {
return $typeMap[$column->type];
12 years ago
}
} else {
return 'string';
}
}
13 years ago
}