Driver.php 8.56 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.
Qiang Xue committed
74
	 * @param array $config name-value pairs that will be used to initialize the object properties
w  
Qiang Xue committed
75
	 */
Qiang Xue committed
76
	public function __construct($connection, $config = array())
w  
Qiang Xue committed
77
	{
w  
Qiang Xue committed
78
		$this->connection = $connection;
Qiang Xue committed
79
		parent::__construct($config);
w  
Qiang Xue committed
80 81 82 83
	}

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

w  
Qiang Xue committed
94
		$db = $this->connection;
w  
Qiang Xue committed
95

Qiang Xue committed
96 97
		$realName = $db->expandTablePrefix($name);

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

Qiang Xue committed
104 105 106
		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
107 108 109
				$table = $this->loadTableSchema($realName);
				if ($table !== null) {
					$cache->set($key, $table, $db->schemaCachingDuration);
w  
Qiang Xue committed
110 111
				}
			}
w  
Qiang Xue committed
112
			$this->_tables[$name] = $table;
Qiang Xue committed
113
		} else {
w  
Qiang Xue committed
114 115
			$this->_tables[$name] = $table = $this->loadTableSchema($realName);
		}
w  
Qiang Xue committed
116

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

		return $table;
w  
Qiang Xue committed
122 123
	}

Qiang Xue committed
124 125 126 127 128 129 130 131 132 133
	/**
	 * 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
134 135 136 137
	/**
	 * 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
138
	 * Each array element is an instance of [[TableSchema]] (or its child class).
w  
Qiang Xue committed
139
	 */
w  
Qiang Xue committed
140
	public function getTableSchemas($schema = '')
w  
Qiang Xue committed
141 142
	{
		$tables = array();
w  
Qiang Xue committed
143 144 145 146
		foreach ($this->getTableNames($schema) as $name) {
			if (($table = $this->getTableSchema($name)) !== null) {
				$tables[] = $table;
			}
w  
Qiang Xue committed
147 148 149 150 151 152 153 154
		}
		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
155 156
	 * @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
157 158
	 * @return array all table names in the database.
	 */
Qiang Xue committed
159
	public function getTableNames($schema = '', $refresh = false)
w  
Qiang Xue committed
160
	{
Qiang Xue committed
161
		if (!isset($this->_tableNames[$schema]) || $refresh) {
w  
Qiang Xue committed
162
			$this->_tableNames[$schema] = $this->findTableNames($schema);
w  
Qiang Xue committed
163
		}
w  
Qiang Xue committed
164 165 166 167
		return $this->_tableNames[$schema];
	}

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

	/**
	 * Refreshes the schema.
Qiang Xue committed
180 181 182 183
	 * 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
184
	 */
Qiang Xue committed
185
	public function refresh($tableName = null)
w  
Qiang Xue committed
186
	{
w  
Qiang Xue committed
187
		$db = $this->connection;
Qiang Xue committed
188
		if ($db->schemaCachingDuration >= 0 && ($cache = \Yii::$application->getComponent($db->schemaCacheID)) !== null) {
Qiang Xue committed
189 190 191 192 193 194 195 196
			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
197 198 199 200 201 202 203 204 205 206 207 208 209
			}
		}
	}

	/**
	 * 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
210
		if (strpos($name, '.') === false) {
w  
Qiang Xue committed
211
			return $this->quoteSimpleTableName($name);
w  
Qiang Xue committed
212
		}
w  
Qiang Xue committed
213
		$parts = explode('.', $name);
w  
Qiang Xue committed
214
		foreach ($parts as $i => $part) {
w  
Qiang Xue committed
215
			$parts[$i] = $this->quoteSimpleTableName($part);
w  
Qiang Xue committed
216
		}
w  
Qiang Xue committed
217 218 219 220 221 222 223 224 225 226 227 228
		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
229
		return strpos($name, "'") !== false ? $name : "'" . $name . "'";
w  
Qiang Xue committed
230 231 232 233 234 235 236 237 238 239 240
	}

	/**
	 * 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
241
		if (($pos = strrpos($name, '.')) !== false) {
w  
Qiang Xue committed
242 243
			$prefix = $this->quoteTableName(substr($name, 0, $pos)) . '.';
			$name = substr($name, $pos + 1);
Qiang Xue committed
244
		} else {
w  
Qiang Xue committed
245
			$prefix = '';
Qiang Xue committed
246
		}
w  
Qiang Xue committed
247
		return $prefix . $this->quoteSimpleColumnName($name);
w  
Qiang Xue committed
248 249 250 251 252 253 254 255 256 257
	}

	/**
	 * 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
258
		return strpos($name, '"') !== false || $name === '*' ? $name : '"' . $name . '"';
w  
Qiang Xue committed
259 260 261
	}

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

	/**
	 * 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
281
		throw new Exception(get_class($this) . 'does not support fetching all table names.');
w  
Qiang Xue committed
282 283
	}
}