Driver.php 8.41 KB
Newer Older
w  
Qiang Xue committed
1 2
<?php
/**
Qiang Xue committed
3
 * Driver class file.
w  
Qiang Xue committed
4 5
 *
 * @link http://www.yiiframework.com/
Qiang Xue committed
6
 * @copyright Copyright &copy; 2008-2012 Yii Software LLC
w  
Qiang Xue committed
7 8 9
 * @license http://www.yiiframework.com/license/
 */

w  
Qiang Xue committed
10 11
namespace yii\db\dao;

w  
Qiang Xue committed
12 13
use yii\db\Exception;

w  
Qiang Xue committed
14
/**
Qiang Xue committed
15
 * Driver is the base class for all database driver classes.
Qiang Xue committed
16
 *
Qiang Xue committed
17
 * Driver implements the DBMS-specific methods to support retrieving metadata of a database.
Qiang Xue committed
18 19 20
 *
 * @property QueryBuilder $queryBuilder the query builder for this connection.
 * @property array $tableNames the names of all tables in this database.
Qiang Xue committed
21
 * @property array $tableSchemas the metadata for all tables in this database.
w  
Qiang Xue committed
22 23
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
24
 * @since 2.0
w  
Qiang Xue committed
25
 */
Qiang Xue committed
26
abstract class Driver extends \yii\base\Object
w  
Qiang Xue committed
27
{
Qiang Xue committed
28 29 30
	/**
	 * The followings are the supported abstract column data types.
	 */
Qiang Xue committed
31
	const TYPE_PK = 'pk';
Qiang Xue committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
	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';

Qiang Xue committed
47
	/**
Qiang Xue committed
48
	 * @var Connection the database connection
Qiang Xue committed
49
	 */
w  
Qiang Xue committed
50
	public $connection;
Qiang Xue committed
51 52 53
	/**
	 * @var array list of ALL table names in the database
	 */
w  
Qiang Xue committed
54
	private $_tableNames = array();
Qiang Xue committed
55
	/**
Qiang Xue committed
56
	 * @var array list of loaded table metadata (table name => TableSchema)
Qiang Xue committed
57
	 */
w  
Qiang Xue committed
58
	private $_tables = array();
Qiang Xue committed
59 60 61
	/**
	 * @var QueryBuilder the query builder for this database
	 */
w  
Qiang Xue committed
62 63 64 65 66
	private $_builder;

	/**
	 * Loads the metadata for the specified table.
	 * @param string $name table name
Qiang Xue committed
67
	 * @return TableSchema DBMS-dependent table metadata, null if the table does not exist.
w  
Qiang Xue committed
68
	 */
w  
Qiang Xue committed
69
	abstract protected function loadTableSchema($name);
w  
Qiang Xue committed
70 71 72

	/**
	 * Constructor.
Qiang Xue committed
73
	 * @param Connection $connection database connection.
w  
Qiang Xue committed
74
	 */
w  
Qiang Xue committed
75
	public function __construct($connection)
w  
Qiang Xue committed
76
	{
w  
Qiang Xue committed
77
		$this->connection = $connection;
w  
Qiang Xue committed
78 79 80 81
	}

	/**
	 * Obtains the metadata for the named table.
w  
Qiang Xue committed
82
	 * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
Qiang Xue committed
83
	 * @param boolean $refresh whether to reload the table schema even if it is found in the cache.
Qiang Xue committed
84
	 * @return TableSchema table metadata. Null if the named table does not exist.
w  
Qiang Xue committed
85
	 */
Qiang Xue committed
86
	public function getTableSchema($name, $refresh = false)
w  
Qiang Xue committed
87
	{
Qiang Xue committed
88
		if (isset($this->_tables[$name]) && !$refresh) {
w  
Qiang Xue committed
89
			return $this->_tables[$name];
w  
Qiang Xue committed
90
		}
w  
Qiang Xue committed
91

w  
Qiang Xue committed
92
		$db = $this->connection;
w  
Qiang Xue committed
93

Qiang Xue committed
94 95
		$realName = $db->expandTablePrefix($name);

w  
Qiang Xue committed
96 97 98 99 100 101
		// temporarily disable query caching
		if ($db->queryCachingDuration >= 0) {
			$qcDuration = $db->queryCachingDuration;
			$db->queryCachingDuration = -1;
		}

Qiang Xue committed
102 103 104
		if (!in_array($name, $db->schemaCachingExclude, true) && $db->schemaCachingDuration >= 0 && ($cache = \Yii::$application->getComponent($db->schemaCacheID)) !== null) {
			$key = $this->getCacheKey($name);
			if ($refresh || ($table = $cache->get($key)) === false) {
w  
Qiang Xue committed
105 106 107
				$table = $this->loadTableSchema($realName);
				if ($table !== null) {
					$cache->set($key, $table, $db->schemaCachingDuration);
w  
Qiang Xue committed
108 109
				}
			}
w  
Qiang Xue committed
110
			$this->_tables[$name] = $table;
Qiang Xue committed
111
		} else {
w  
Qiang Xue committed
112 113
			$this->_tables[$name] = $table = $this->loadTableSchema($realName);
		}
w  
Qiang Xue committed
114

w  
Qiang Xue committed
115 116
		if (isset($qcDuration)) { // re-enable query caching
			$db->queryCachingDuration = $qcDuration;
w  
Qiang Xue committed
117
		}
w  
Qiang Xue committed
118 119

		return $table;
w  
Qiang Xue committed
120 121
	}

Qiang Xue committed
122 123 124 125 126 127 128 129 130 131
	/**
	 * Returns the cache key for the specified table name.
	 * @param string $name the table name
	 * @return string the cache key
	 */
	public function getCacheKey($name)
	{
		return  __CLASS__ . "/{$this->connection->dsn}/{$this->connection->username}/{$name}";
	}

w  
Qiang Xue committed
132 133 134 135
	/**
	 * Returns the metadata for all tables in the database.
	 * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
	 * @return array the metadata for all tables in the database.
Qiang Xue committed
136
	 * Each array element is an instance of [[TableSchema]] (or its child class).
w  
Qiang Xue committed
137
	 */
w  
Qiang Xue committed
138
	public function getTableSchemas($schema = '')
w  
Qiang Xue committed
139 140
	{
		$tables = array();
w  
Qiang Xue committed
141 142 143 144
		foreach ($this->getTableNames($schema) as $name) {
			if (($table = $this->getTableSchema($name)) !== null) {
				$tables[] = $table;
			}
w  
Qiang Xue committed
145 146 147 148 149 150 151 152
		}
		return $tables;
	}

	/**
	 * Returns all table names in the database.
	 * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
	 * If not empty, the returned table names will be prefixed with the schema name.
Qiang Xue committed
153 154
	 * @param boolean $refresh whether to fetch the latest available table names. If this is false,
	 * table names fetched previously (if available) will be returned.
w  
Qiang Xue committed
155 156
	 * @return array all table names in the database.
	 */
Qiang Xue committed
157
	public function getTableNames($schema = '', $refresh = false)
w  
Qiang Xue committed
158
	{
Qiang Xue committed
159
		if (!isset($this->_tableNames[$schema]) || $refresh) {
w  
Qiang Xue committed
160
			$this->_tableNames[$schema] = $this->findTableNames($schema);
w  
Qiang Xue committed
161
		}
w  
Qiang Xue committed
162 163 164 165
		return $this->_tableNames[$schema];
	}

	/**
w  
Qiang Xue committed
166
	 * @return QueryBuilder the query builder for this connection.
w  
Qiang Xue committed
167
	 */
w  
Qiang Xue committed
168
	public function getQueryBuilder()
w  
Qiang Xue committed
169
	{
w  
Qiang Xue committed
170 171 172 173
		if ($this->_builder === null) {
			$this->_builder = $this->createQueryBuilder();
		}
		return $this->_builder;
w  
Qiang Xue committed
174 175 176 177
	}

	/**
	 * Refreshes the schema.
Qiang Xue committed
178 179 180 181
	 * This method cleans up the cached table schema and names
	 * so that they can be recreated to reflect the database schema change.
	 * @param string $tableName the name of the table that needs to be refreshed.
	 * If null, all currently loaded tables will be refreshed.
w  
Qiang Xue committed
182
	 */
Qiang Xue committed
183
	public function refresh($tableName = null)
w  
Qiang Xue committed
184
	{
w  
Qiang Xue committed
185
		$db = $this->connection;
Qiang Xue committed
186
		if ($db->schemaCachingDuration >= 0 && ($cache = \Yii::$application->getComponent($db->schemaCacheID)) !== null) {
Qiang Xue committed
187 188 189 190 191 192 193 194
			if ($tableName === null) {
				foreach ($this->_tables as $name => $table) {
					$cache->delete($this->getCacheKey($name));
				}
				$this->_tables = array();
			} else {
				$cache->delete($this->getCacheKey($tableName));
				unset($this->_tables[$tableName]);
w  
Qiang Xue committed
195 196 197 198 199 200 201 202 203 204 205 206 207
			}
		}
	}

	/**
	 * Quotes a table name for use in a query.
	 * If the table name contains schema prefix, the prefix will also be properly quoted.
	 * @param string $name table name
	 * @return string the properly quoted table name
	 * @see quoteSimpleTableName
	 */
	public function quoteTableName($name)
	{
w  
Qiang Xue committed
208
		if (strpos($name, '.') === false) {
w  
Qiang Xue committed
209
			return $this->quoteSimpleTableName($name);
w  
Qiang Xue committed
210
		}
w  
Qiang Xue committed
211
		$parts = explode('.', $name);
w  
Qiang Xue committed
212
		foreach ($parts as $i => $part) {
w  
Qiang Xue committed
213
			$parts[$i] = $this->quoteSimpleTableName($part);
w  
Qiang Xue committed
214
		}
w  
Qiang Xue committed
215 216 217 218 219 220 221 222 223 224 225 226
		return implode('.', $parts);

	}

	/**
	 * Quotes a simple table name for use in a query.
	 * A simple table name does not schema prefix.
	 * @param string $name table name
	 * @return string the properly quoted table name
	 */
	public function quoteSimpleTableName($name)
	{
w  
Qiang Xue committed
227
		return strpos($name, "'") !== false ? $name : "'" . $name . "'";
w  
Qiang Xue committed
228 229 230 231 232 233 234 235 236 237 238
	}

	/**
	 * Quotes a column name for use in a query.
	 * If the column name contains prefix, the prefix will also be properly quoted.
	 * @param string $name column name
	 * @return string the properly quoted column name
	 * @see quoteSimpleColumnName
	 */
	public function quoteColumnName($name)
	{
w  
Qiang Xue committed
239
		if (($pos = strrpos($name, '.')) !== false) {
w  
Qiang Xue committed
240 241
			$prefix = $this->quoteTableName(substr($name, 0, $pos)) . '.';
			$name = substr($name, $pos + 1);
Qiang Xue committed
242
		} else {
w  
Qiang Xue committed
243
			$prefix = '';
Qiang Xue committed
244
		}
w  
Qiang Xue committed
245
		return $prefix . $this->quoteSimpleColumnName($name);
w  
Qiang Xue committed
246 247 248 249 250 251 252 253 254 255
	}

	/**
	 * Quotes a simple column name for use in a query.
	 * A simple column name does not contain prefix.
	 * @param string $name column name
	 * @return string the properly quoted column name
	 */
	public function quoteSimpleColumnName($name)
	{
w  
Qiang Xue committed
256
		return strpos($name, '"') !== false || $name === '*' ? $name : '"' . $name . '"';
w  
Qiang Xue committed
257 258 259
	}

	/**
w  
Qiang Xue committed
260 261 262
	 * 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
w  
Qiang Xue committed
263
	 */
w  
Qiang Xue committed
264
	public function createQueryBuilder()
w  
Qiang Xue committed
265
	{
Qiang Xue committed
266
		return new QueryBuilder($this->connection);
w  
Qiang Xue committed
267 268 269 270 271 272 273 274 275 276 277 278
	}

	/**
	 * 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.
	 * If not empty, the returned table names will be prefixed with the schema name.
	 * @return array all table names in the database.
	 */
	protected function findTableNames($schema = '')
	{
w  
Qiang Xue committed
279
		throw new Exception(get_class($this) . 'does not support fetching all table names.');
w  
Qiang Xue committed
280 281
	}
}