Schema.php 11.7 KB
Newer Older
w  
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
w  
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
8
namespace yii\db;
w  
Qiang Xue committed
9

10
use Yii;
Qiang Xue committed
11
use yii\base\NotSupportedException;
Qiang Xue committed
12
use yii\base\InvalidCallException;
Qiang Xue committed
13
use yii\caching\Cache;
14
use yii\caching\GroupDependency;
w  
Qiang Xue committed
15

w  
Qiang Xue committed
16
/**
Qiang Xue committed
17
 * Schema is the base class for concrete DBMS-specific schema classes.
Qiang Xue committed
18
 *
Qiang Xue committed
19
 * Schema represents the database schema information that is DBMS specific.
Qiang Xue committed
20
 *
Qiang Xue committed
21
 * @property QueryBuilder $queryBuilder the query builder for the DBMS represented by this schema
Qiang Xue committed
22
 * @property array $tableNames the names of all tables in this database.
Qiang Xue committed
23
 * @property array $tableSchemas the schema information for all tables in this database.
w  
Qiang Xue committed
24 25
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
26
 * @since 2.0
w  
Qiang Xue committed
27
 */
Qiang Xue committed
28
abstract class Schema extends \yii\base\Object
w  
Qiang Xue committed
29
{
Qiang Xue committed
30 31 32
	/**
	 * The followings are the supported abstract column data types.
	 */
Qiang Xue committed
33
	const TYPE_PK = 'pk';
Qiang Xue committed
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
	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
49
	/**
Qiang Xue committed
50
	 * @var Connection the database connection
Qiang Xue committed
51
	 */
Qiang Xue committed
52
	public $db;
Qiang Xue committed
53 54 55
	/**
	 * @var array list of ALL table names in the database
	 */
w  
Qiang Xue committed
56
	private $_tableNames = array();
Qiang Xue committed
57
	/**
Qiang Xue committed
58
	 * @var array list of loaded table metadata (table name => TableSchema)
Qiang Xue committed
59
	 */
w  
Qiang Xue committed
60
	private $_tables = array();
Qiang Xue committed
61 62 63
	/**
	 * @var QueryBuilder the query builder for this database
	 */
w  
Qiang Xue committed
64 65 66 67 68
	private $_builder;

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


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

Qiang Xue committed
86
		$db = $this->db;
Qiang Xue committed
87
		$realName = $this->getRawTableName($name);
Qiang Xue committed
88

89 90 91 92
		if ($db->enableSchemaCache && !in_array($name, $db->schemaCacheExclude, true)) {
			/** @var $cache Cache */
			$cache = is_string($db->schemaCache) ? Yii::$app->getComponent($db->schemaCache) : $db->schemaCache;
			if ($cache instanceof Cache) {
93
				$key = $this->getCacheKey($name);
94 95 96
				if ($refresh || ($table = $cache->get($key)) === false) {
					$table = $this->loadTableSchema($realName);
					if ($table !== null) {
97
						$cache->set($key, $table, $db->schemaCacheDuration, new GroupDependency($this->getCacheGroup()));
98
					}
w  
Qiang Xue committed
99
				}
100
				return $this->_tables[$name] = $table;
w  
Qiang Xue committed
101
			}
w  
Qiang Xue committed
102
		}
103
		return $this->_tables[$name] = $table = $this->loadTableSchema($realName);
w  
Qiang Xue committed
104 105
	}

Qiang Xue committed
106 107 108
	/**
	 * Returns the cache key for the specified table name.
	 * @param string $name the table name
109
	 * @return mixed the cache key
Qiang Xue committed
110
	 */
111
	protected function getCacheKey($name)
Qiang Xue committed
112
	{
113
		return array(
Qiang Xue committed
114 115 116 117
			__CLASS__,
			$this->db->dsn,
			$this->db->username,
			$name,
118
		);
Qiang Xue committed
119 120
	}

121 122 123 124 125 126 127 128 129 130 131 132 133 134
	/**
	 * Returns the cache group name.
	 * This allows [[refresh()]] to invalidate all cached table schemas.
	 * @return string the cache group name
	 */
	protected function getCacheGroup()
	{
		return md5(serialize(array(
			__CLASS__,
			$this->db->dsn,
			$this->db->username,
		)));
	}

w  
Qiang Xue committed
135 136
	/**
	 * Returns the metadata for all tables in the database.
Qiang Xue committed
137 138 139
	 * @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.
w  
Qiang Xue committed
140
	 * @return array the metadata for all tables in the database.
Qiang Xue committed
141
	 * Each array element is an instance of [[TableSchema]] or its child class.
w  
Qiang Xue committed
142
	 */
Qiang Xue committed
143
	public function getTableSchemas($schema = '', $refresh = false)
w  
Qiang Xue committed
144 145
	{
		$tables = array();
Qiang Xue committed
146 147 148 149 150
		foreach ($this->getTableNames($schema, $refresh) as $name) {
			if ($schema !== '') {
				$name = $schema . '.' . $name;
			}
			if (($table = $this->getTableSchema($name, $refresh)) !== null) {
w  
Qiang Xue committed
151 152
				$tables[] = $table;
			}
w  
Qiang Xue committed
153 154 155 156 157 158
		}
		return $tables;
	}

	/**
	 * Returns all table names in the database.
Qiang Xue committed
159
	 * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
w  
Qiang Xue committed
160
	 * If not empty, the returned table names will be prefixed with the schema name.
Qiang Xue committed
161 162
	 * @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
163 164
	 * @return array all table names in the database.
	 */
Qiang Xue committed
165
	public function getTableNames($schema = '', $refresh = false)
w  
Qiang Xue committed
166
	{
Qiang Xue committed
167
		if (!isset($this->_tableNames[$schema]) || $refresh) {
w  
Qiang Xue committed
168
			$this->_tableNames[$schema] = $this->findTableNames($schema);
w  
Qiang Xue committed
169
		}
w  
Qiang Xue committed
170 171 172 173
		return $this->_tableNames[$schema];
	}

	/**
w  
Qiang Xue committed
174
	 * @return QueryBuilder the query builder for this connection.
w  
Qiang Xue committed
175
	 */
w  
Qiang Xue committed
176
	public function getQueryBuilder()
w  
Qiang Xue committed
177
	{
w  
Qiang Xue committed
178 179 180 181
		if ($this->_builder === null) {
			$this->_builder = $this->createQueryBuilder();
		}
		return $this->_builder;
w  
Qiang Xue committed
182 183 184 185
	}

	/**
	 * Refreshes the schema.
186 187
	 * This method cleans up all cached table schemas so that they can be re-created later
	 * to reflect the database schema change.
w  
Qiang Xue committed
188
	 */
189
	public function refresh()
w  
Qiang Xue committed
190
	{
191 192 193
		/** @var $cache Cache */
		$cache = is_string($this->db->schemaCache) ? Yii::$app->getComponent($this->db->schemaCache) : $this->db->schemaCache;
		if ($this->db->enableSchemaCache && $cache instanceof Cache) {
194
			GroupDependency::invalidate($cache, $this->getCacheGroup());
w  
Qiang Xue committed
195
		}
Qiang Xue committed
196
		$this->_tableNames = array();
197 198 199 200 201 202 203 204 205 206
		$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()
	{
Qiang Xue committed
207
		return new QueryBuilder($this->db);
208 209 210 211 212 213 214
	}

	/**
	 * 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.
Qiang Xue committed
215 216
	 * @return array all table names in the database. The names have NO the schema name prefix.
	 * @throws NotSupportedException if this method is called
217 218 219
	 */
	protected function findTableNames($schema = '')
	{
Qiang Xue committed
220
		throw new NotSupportedException(get_class($this) . ' does not support fetching all table names.');
w  
Qiang Xue committed
221 222
	}

Qiang Xue committed
223 224 225 226
	/**
	 * 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
Qiang Xue committed
227
	 * @throws InvalidCallException if the DB connection is not active
Qiang Xue committed
228 229 230 231
	 * @see http://www.php.net/manual/en/function.PDO-lastInsertId.php
	 */
	public function getLastInsertID($sequenceName = '')
	{
Qiang Xue committed
232 233
		if ($this->db->isActive) {
			return $this->db->pdo->lastInsertId($sequenceName);
Qiang Xue committed
234
		} else {
Qiang Xue committed
235
			throw new InvalidCallException('DB Connection is not active.');
Qiang Xue committed
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
		}
	}

	/**
	 * 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;
		}

Qiang Xue committed
252 253
		$this->db->open();
		if (($value = $this->db->pdo->quote($str)) !== false) {
Qiang Xue committed
254 255 256 257 258 259
			return $value;
		} else { // the driver doesn't support quote (e.g. oci)
			return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
		}
	}

w  
Qiang Xue committed
260 261 262
	/**
	 * Quotes a table name for use in a query.
	 * If the table name contains schema prefix, the prefix will also be properly quoted.
263
	 * If the table name is already quoted or contains '(' or '{{',
264
	 * then this method will do nothing.
w  
Qiang Xue committed
265 266 267 268 269 270
	 * @param string $name table name
	 * @return string the properly quoted table name
	 * @see quoteSimpleTableName
	 */
	public function quoteTableName($name)
	{
271
		if (strpos($name, '(') !== false || strpos($name, '{{') !== false) {
272 273
			return $name;
		}
w  
Qiang Xue committed
274
		if (strpos($name, '.') === false) {
w  
Qiang Xue committed
275
			return $this->quoteSimpleTableName($name);
w  
Qiang Xue committed
276
		}
w  
Qiang Xue committed
277
		$parts = explode('.', $name);
w  
Qiang Xue committed
278
		foreach ($parts as $i => $part) {
w  
Qiang Xue committed
279
			$parts[$i] = $this->quoteSimpleTableName($part);
w  
Qiang Xue committed
280
		}
w  
Qiang Xue committed
281 282 283 284 285 286 287
		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.
288
	 * If the column name is already quoted or contains '(', '[[' or '{{',
289
	 * then this method will do nothing.
w  
Qiang Xue committed
290 291 292 293 294 295
	 * @param string $name column name
	 * @return string the properly quoted column name
	 * @see quoteSimpleColumnName
	 */
	public function quoteColumnName($name)
	{
296 297 298
		if (strpos($name, '(') !== false || strpos($name, '[[') !== false || strpos($name, '{{') !== false) {
			return $name;
		}
w  
Qiang Xue committed
299
		if (($pos = strrpos($name, '.')) !== false) {
w  
Qiang Xue committed
300 301
			$prefix = $this->quoteTableName(substr($name, 0, $pos)) . '.';
			$name = substr($name, $pos + 1);
Qiang Xue committed
302
		} else {
w  
Qiang Xue committed
303
			$prefix = '';
Qiang Xue committed
304
		}
w  
Qiang Xue committed
305
		return $prefix . $this->quoteSimpleColumnName($name);
w  
Qiang Xue committed
306 307 308
	}

	/**
309 310 311 312 313
	 * 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
w  
Qiang Xue committed
314
	 */
315
	public function quoteSimpleTableName($name)
w  
Qiang Xue committed
316
	{
317
		return strpos($name, "'") !== false ? $name : "'" . $name . "'";
w  
Qiang Xue committed
318 319 320
	}

	/**
321 322 323 324 325
	 * 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
w  
Qiang Xue committed
326
	 */
327
	public function quoteSimpleColumnName($name)
w  
Qiang Xue committed
328
	{
329
		return strpos($name, '"') !== false || $name === '*' ? $name : '"' . $name . '"';
w  
Qiang Xue committed
330 331 332
	}

	/**
Qiang Xue committed
333
	 * Returns the actual name of a given table name.
334
	 * This method will strip off curly brackets from the given table name
335
	 * and replace the percentage character '%' with [[Connection::tablePrefix]].
336 337
	 * @param string $name the table name to be converted
	 * @return string the real name of the given table name
w  
Qiang Xue committed
338
	 */
Qiang Xue committed
339
	public function getRawTableName($name)
w  
Qiang Xue committed
340
	{
341
		if (strpos($name, '{{') !== false) {
342
			$name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name);
Qiang Xue committed
343
			return str_replace('%', $this->db->tablePrefix, $name);
344 345 346
		} else {
			return $name;
		}
w  
Qiang Xue committed
347
	}
Qiang Xue committed
348 349 350

	/**
	 * Extracts the PHP type from abstract DB type.
351
	 * @param ColumnSchema $column the column schema information
Qiang Xue committed
352 353
	 * @return string PHP type name
	 */
354
	protected function getColumnPhpType($column)
Qiang Xue committed
355 356 357 358 359 360 361 362
	{
		static $typeMap = array( // abstract type => php type
			'smallint' => 'integer',
			'integer' => 'integer',
			'bigint' => 'integer',
			'boolean' => 'boolean',
			'float' => 'double',
		);
363 364 365 366 367
		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';
Qiang Xue committed
368
			} else {
369
				return $typeMap[$column->type];
Qiang Xue committed
370 371 372 373 374
			}
		} else {
			return 'string';
		}
	}
w  
Qiang Xue committed
375
}