Schema.php 12.6 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\Object;
Qiang Xue committed
12
use yii\base\NotSupportedException;
Qiang Xue committed
13
use yii\base\InvalidCallException;
Qiang Xue committed
14
use yii\caching\Cache;
15
use yii\caching\GroupDependency;
w  
Qiang Xue committed
16

w  
Qiang Xue committed
17
/**
Qiang Xue committed
18
 * Schema is the base class for concrete DBMS-specific schema classes.
Qiang Xue committed
19
 *
Qiang Xue committed
20
 * Schema represents the database schema information that is DBMS specific.
Qiang Xue committed
21
 *
22 23 24 25 26 27
 * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the
 * sequence object. This property is read-only.
 * @property QueryBuilder $queryBuilder The query builder for this connection. This property is read-only.
 * @property string[] $tableNames All table names in the database. This property is read-only.
 * @property TableSchema[] $tableSchemas The metadata for all tables in the database. Each array element is an
 * instance of [[TableSchema]] or its child class. This property is read-only.
w  
Qiang Xue committed
28 29
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
30
 * @since 2.0
w  
Qiang Xue committed
31
 */
Qiang Xue committed
32
abstract class Schema extends Object
w  
Qiang Xue committed
33
{
Qiang Xue committed
34 35 36
	/**
	 * The followings are the supported abstract column data types.
	 */
Qiang Xue committed
37
	const TYPE_PK = 'pk';
38
	const TYPE_BIGPK = 'bigpk';
Qiang Xue committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
	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
54
	/**
Qiang Xue committed
55
	 * @var Connection the database connection
Qiang Xue committed
56
	 */
Qiang Xue committed
57
	public $db;
Qiang Xue committed
58 59 60
	/**
	 * @var array list of ALL table names in the database
	 */
Alexander Makarov committed
61
	private $_tableNames = [];
Qiang Xue committed
62
	/**
Qiang Xue committed
63
	 * @var array list of loaded table metadata (table name => TableSchema)
Qiang Xue committed
64
	 */
Alexander Makarov committed
65
	private $_tables = [];
Qiang Xue committed
66 67 68
	/**
	 * @var QueryBuilder the query builder for this database
	 */
w  
Qiang Xue committed
69 70 71 72 73
	private $_builder;

	/**
	 * Loads the metadata for the specified table.
	 * @param string $name table name
Qiang Xue committed
74
	 * @return TableSchema DBMS-dependent table metadata, null if the table does not exist.
w  
Qiang Xue committed
75
	 */
w  
Qiang Xue committed
76
	abstract protected function loadTableSchema($name);
w  
Qiang Xue committed
77 78 79 80


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

Qiang Xue committed
91
		$db = $this->db;
Qiang Xue committed
92
		$realName = $this->getRawTableName($name);
Qiang Xue committed
93

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

Qiang Xue committed
113 114 115
	/**
	 * Returns the cache key for the specified table name.
	 * @param string $name the table name
116
	 * @return mixed the cache key
Qiang Xue committed
117
	 */
118
	protected function getCacheKey($name)
Qiang Xue committed
119
	{
Alexander Makarov committed
120
		return [
Qiang Xue committed
121 122 123 124
			__CLASS__,
			$this->db->dsn,
			$this->db->username,
			$name,
Alexander Makarov committed
125
		];
Qiang Xue committed
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()
	{
Alexander Makarov committed
135
		return md5(serialize([
136 137 138
			__CLASS__,
			$this->db->dsn,
			$this->db->username,
Alexander Makarov committed
139
		]));
140 141
	}

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

	/**
	 * Returns all table names in the database.
Qiang Xue committed
166
	 * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
w  
Qiang Xue committed
167
	 * If not empty, the returned table names will be prefixed with the schema name.
Qiang Xue committed
168 169
	 * @param boolean $refresh whether to fetch the latest available table names. If this is false,
	 * table names fetched previously (if available) will be returned.
Qiang Xue committed
170
	 * @return string[] all table names in the database.
w  
Qiang Xue committed
171
	 */
Qiang Xue committed
172
	public function getTableNames($schema = '', $refresh = false)
w  
Qiang Xue committed
173
	{
Qiang Xue committed
174
		if (!isset($this->_tableNames[$schema]) || $refresh) {
w  
Qiang Xue committed
175
			$this->_tableNames[$schema] = $this->findTableNames($schema);
w  
Qiang Xue committed
176
		}
w  
Qiang Xue committed
177 178 179 180
		return $this->_tableNames[$schema];
	}

	/**
w  
Qiang Xue committed
181
	 * @return QueryBuilder the query builder for this connection.
w  
Qiang Xue committed
182
	 */
w  
Qiang Xue committed
183
	public function getQueryBuilder()
w  
Qiang Xue committed
184
	{
w  
Qiang Xue committed
185 186 187 188
		if ($this->_builder === null) {
			$this->_builder = $this->createQueryBuilder();
		}
		return $this->_builder;
w  
Qiang Xue committed
189 190
	}

191 192 193 194 195 196 197 198
	/**
	 * Determines the PDO type for the given PHP data value.
	 * @param mixed $data the data whose PDO type is to be determined
	 * @return integer the PDO type
	 * @see http://www.php.net/manual/en/pdo.constants.php
	 */
	public function getPdoType($data)
	{
Alexander Makarov committed
199
		static $typeMap = [
200 201 202 203 204 205
			// php type => PDO type
			'boolean' => \PDO::PARAM_BOOL,
			'integer' => \PDO::PARAM_INT,
			'string' => \PDO::PARAM_STR,
			'resource' => \PDO::PARAM_LOB,
			'NULL' => \PDO::PARAM_NULL,
Alexander Makarov committed
206
		];
207 208 209 210
		$type = gettype($data);
		return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR;
	}

w  
Qiang Xue committed
211 212
	/**
	 * Refreshes the schema.
213 214
	 * 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
215
	 */
216
	public function refresh()
w  
Qiang Xue committed
217
	{
slavcodev committed
218
		/** @var Cache $cache */
219 220
		$cache = is_string($this->db->schemaCache) ? Yii::$app->getComponent($this->db->schemaCache) : $this->db->schemaCache;
		if ($this->db->enableSchemaCache && $cache instanceof Cache) {
221
			GroupDependency::invalidate($cache, $this->getCacheGroup());
w  
Qiang Xue committed
222
		}
Alexander Makarov committed
223 224
		$this->_tableNames = [];
		$this->_tables = [];
225 226 227 228 229 230 231 232 233
	}

	/**
	 * 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
234
		return new QueryBuilder($this->db);
235 236 237 238 239 240 241
	}

	/**
	 * 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.
242
	 * @return array all table names in the database. The names have NO schema name prefix.
Qiang Xue committed
243
	 * @throws NotSupportedException if this method is called
244 245 246
	 */
	protected function findTableNames($schema = '')
	{
Qiang Xue committed
247
		throw new NotSupportedException(get_class($this) . ' does not support fetching all table names.');
w  
Qiang Xue committed
248 249
	}

Qiang Xue committed
250 251 252 253
	/**
	 * 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
254
	 * @throws InvalidCallException if the DB connection is not active
Qiang Xue committed
255 256 257 258
	 * @see http://www.php.net/manual/en/function.PDO-lastInsertId.php
	 */
	public function getLastInsertID($sequenceName = '')
	{
Qiang Xue committed
259 260
		if ($this->db->isActive) {
			return $this->db->pdo->lastInsertId($sequenceName);
Qiang Xue committed
261
		} else {
Qiang Xue committed
262
			throw new InvalidCallException('DB Connection is not active.');
Qiang Xue committed
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
		}
	}

	/**
	 * 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
279 280
		$this->db->open();
		if (($value = $this->db->pdo->quote($str)) !== false) {
Qiang Xue committed
281 282 283 284 285 286
			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
287 288 289
	/**
	 * Quotes a table name for use in a query.
	 * If the table name contains schema prefix, the prefix will also be properly quoted.
290
	 * If the table name is already quoted or contains '(' or '{{',
291
	 * then this method will do nothing.
w  
Qiang Xue committed
292 293
	 * @param string $name table name
	 * @return string the properly quoted table name
294
	 * @see quoteSimpleTableName()
w  
Qiang Xue committed
295 296 297
	 */
	public function quoteTableName($name)
	{
298
		if (strpos($name, '(') !== false || strpos($name, '{{') !== false) {
299 300
			return $name;
		}
w  
Qiang Xue committed
301
		if (strpos($name, '.') === false) {
w  
Qiang Xue committed
302
			return $this->quoteSimpleTableName($name);
w  
Qiang Xue committed
303
		}
w  
Qiang Xue committed
304
		$parts = explode('.', $name);
w  
Qiang Xue committed
305
		foreach ($parts as $i => $part) {
w  
Qiang Xue committed
306
			$parts[$i] = $this->quoteSimpleTableName($part);
w  
Qiang Xue committed
307
		}
w  
Qiang Xue committed
308 309 310 311 312 313 314
		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.
315
	 * If the column name is already quoted or contains '(', '[[' or '{{',
316
	 * then this method will do nothing.
w  
Qiang Xue committed
317 318
	 * @param string $name column name
	 * @return string the properly quoted column name
319
	 * @see quoteSimpleColumnName()
w  
Qiang Xue committed
320 321 322
	 */
	public function quoteColumnName($name)
	{
323 324 325
		if (strpos($name, '(') !== false || strpos($name, '[[') !== false || strpos($name, '{{') !== false) {
			return $name;
		}
w  
Qiang Xue committed
326
		if (($pos = strrpos($name, '.')) !== false) {
w  
Qiang Xue committed
327 328
			$prefix = $this->quoteTableName(substr($name, 0, $pos)) . '.';
			$name = substr($name, $pos + 1);
Qiang Xue committed
329
		} else {
w  
Qiang Xue committed
330
			$prefix = '';
Qiang Xue committed
331
		}
w  
Qiang Xue committed
332
		return $prefix . $this->quoteSimpleColumnName($name);
w  
Qiang Xue committed
333 334 335
	}

	/**
336 337 338 339 340
	 * 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
341
	 */
342
	public function quoteSimpleTableName($name)
w  
Qiang Xue committed
343
	{
344
		return strpos($name, "'") !== false ? $name : "'" . $name . "'";
w  
Qiang Xue committed
345 346 347
	}

	/**
348 349 350 351 352
	 * 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
353
	 */
354
	public function quoteSimpleColumnName($name)
w  
Qiang Xue committed
355
	{
356
		return strpos($name, '"') !== false || $name === '*' ? $name : '"' . $name . '"';
w  
Qiang Xue committed
357 358 359
	}

	/**
Qiang Xue committed
360
	 * Returns the actual name of a given table name.
361
	 * This method will strip off curly brackets from the given table name
362
	 * and replace the percentage character '%' with [[Connection::tablePrefix]].
363 364
	 * @param string $name the table name to be converted
	 * @return string the real name of the given table name
w  
Qiang Xue committed
365
	 */
Qiang Xue committed
366
	public function getRawTableName($name)
w  
Qiang Xue committed
367
	{
368
		if (strpos($name, '{{') !== false) {
369
			$name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name);
Qiang Xue committed
370
			return str_replace('%', $this->db->tablePrefix, $name);
371 372 373
		} else {
			return $name;
		}
w  
Qiang Xue committed
374
	}
Qiang Xue committed
375 376 377

	/**
	 * Extracts the PHP type from abstract DB type.
378
	 * @param ColumnSchema $column the column schema information
Qiang Xue committed
379 380
	 * @return string PHP type name
	 */
381
	protected function getColumnPhpType($column)
Qiang Xue committed
382
	{
Alexander Makarov committed
383
		static $typeMap = [ // abstract type => php type
Qiang Xue committed
384 385 386 387 388
			'smallint' => 'integer',
			'integer' => 'integer',
			'bigint' => 'integer',
			'boolean' => 'boolean',
			'float' => 'double',
Alexander Makarov committed
389
		];
390 391 392 393 394
		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
395
			} else {
396
				return $typeMap[$column->type];
Qiang Xue committed
397 398 399 400 401
			}
		} else {
			return 'string';
		}
	}
w  
Qiang Xue committed
402
}