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

w  
Qiang Xue committed
11 12
namespace yii\db\dao\mysql;

w  
Qiang Xue committed
13
/**
w  
Qiang Xue committed
14
 * Schema is the class for retrieving metadata information from a MySQL database (version 4.1.x and 5.x).
w  
Qiang Xue committed
15 16
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
17
 * @since 2.0
w  
Qiang Xue committed
18
 */
w  
Qiang Xue committed
19
class Schema extends \yii\db\dao\Schema
w  
Qiang Xue committed
20 21 22 23 24 25 26 27 28
{
	/**
	 * Quotes a 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
29
		return strpos($name, "`") !== false ? $name : "`" . $name . "`";
w  
Qiang Xue committed
30 31 32 33 34 35 36 37 38 39
	}

	/**
	 * Quotes a 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
40
		return strpos($name, '`') !== false || $name === '*' ? $name : '`' . $name . '`';
w  
Qiang Xue committed
41 42 43 44 45
	}

	/**
	 * Loads the metadata for the specified table.
	 * @param string $name table name
w  
Qiang Xue committed
46
	 * @return TableSchema driver dependent table metadata. Null if the table does not exist.
w  
Qiang Xue committed
47
	 */
w  
Qiang Xue committed
48
	protected function loadTableSchema($name)
w  
Qiang Xue committed
49
	{
w  
Qiang Xue committed
50
		$table = new TableSchema;
w  
Qiang Xue committed
51 52
		$this->resolveTableNames($table, $name);

w  
Qiang Xue committed
53
		if ($this->findColumns($table)) {
w  
Qiang Xue committed
54 55 56 57 58 59 60 61 62 63 64 65 66
			$this->findConstraints($table);
			return $table;
		}
	}

	/**
	 * Generates various kinds of table names.
	 * @param CMysqlTableSchema $table the table instance
	 * @param string $name the unquoted table name
	 */
	protected function resolveTableNames($table, $name)
	{
		$parts = explode('.', str_replace('`', '', $name));
w  
Qiang Xue committed
67
		if (isset($parts[1])) {
w  
Qiang Xue committed
68 69
			$table->schemaName = $parts[0];
			$table->name = $parts[1];
w  
Qiang Xue committed
70
			$table->quotedName = $this->quoteSimpleTableName($table->schemaName) . '.' . $this->quoteSimpleTableName($table->name);
w  
Qiang Xue committed
71
		}
w  
Qiang Xue committed
72
		else {
w  
Qiang Xue committed
73
			$table->name = $parts[0];
w  
Qiang Xue committed
74
			$table->quotedName = $this->quoteSimpleTableName($table->name);
w  
Qiang Xue committed
75 76 77 78 79 80 81 82 83 84
		}
	}

	/**
	 * Creates a table column.
	 * @param array $column column metadata
	 * @return CDbColumnSchema normalized column metadata
	 */
	protected function createColumn($column)
	{
w  
Qiang Xue committed
85 86
		$c = new ColumnSchema;

w  
Qiang Xue committed
87
		$c->name = $column['Field'];
w  
Qiang Xue committed
88
		$c->quotedName = $this->quoteSimpleColumnName($c->name);
w  
Qiang Xue committed
89 90
		$c->allowNull = $column['Null'] === 'YES';
		$c->isPrimaryKey = strpos($column['Key'], 'PRI') !== false;
w  
Qiang Xue committed
91 92 93
		$c->autoIncrement = stripos($column['Extra'], 'auto_increment') !== false;
		$c->initTypes($column['Type']);
		$c->initDefaultValue($column['Default']);
w  
Qiang Xue committed
94 95 96 97 98

		return $c;
	}

	/**
w  
Qiang Xue committed
99 100 101
	 * Collects the table column metadata.
	 * @param CMysqlTableSchema $table the table metadata
	 * @return boolean whether the table exists in the database
w  
Qiang Xue committed
102
	 */
w  
Qiang Xue committed
103
	protected function findColumns($table)
w  
Qiang Xue committed
104
	{
w  
Qiang Xue committed
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
		$sql = 'SHOW COLUMNS FROM ' . $table->quotedName;
		try {
			$columns = $this->connection->createCommand($sql)->queryAll();
		}
		catch(\Exception $e) {
			return false;
		}
		foreach ($columns as $column) {
			$table->columns[$c->name] = $c = $this->createColumn($column);
			if ($c->isPrimaryKey) {
				if ($table->primaryKey === null) {
					$table->primaryKey = $c->name;
				}
				elseif (is_string($table->primaryKey)) {
					$table->primaryKey = array($table->primaryKey, $c->name);
				}
				else {
					$table->primaryKey[] = $c->name;
				}
				if ($c->autoIncrement) {
					$table->sequenceName = '';
				}
			}
		}
		return true;
w  
Qiang Xue committed
130 131 132 133 134 135 136 137
	}

	/**
	 * Collects the foreign key column details for the given table.
	 * @param CMysqlTableSchema $table the table metadata
	 */
	protected function findConstraints($table)
	{
w  
Qiang Xue committed
138
		$row = $this->connection->createCommand('SHOW CREATE TABLE ' . $table->quotedName)->queryRow();
w  
Qiang Xue committed
139 140
		$matches = array();
		$regexp = '/FOREIGN KEY\s+\(([^\)]+)\)\s+REFERENCES\s+([^\(^\s]+)\s*\(([^\)]+)\)/mi';
w  
Qiang Xue committed
141 142 143 144 145
		foreach ($row as $sql) {
			if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
				foreach ($matches as $match) {
					$fks = array_map('trim', explode(',', str_replace('`', '', $match[1])));
					$pks = array_map('trim', explode(',', str_replace('`', '', $match[3])));
Qiang Xue committed
146
					$constraint = array(str_replace('`', '', $match[2]));
w  
Qiang Xue committed
147 148 149 150 151
					foreach ($fks as $k => $name) {
						$constraint[$name] = $pks[$k];
					}
					$table->foreignKeys[] = $constraint;
				}
w  
Qiang Xue committed
152 153 154 155 156 157 158 159 160 161 162 163 164
				break;
			}
		}
	}

	/**
	 * 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.
	 * @return array all table names in the database.
	 */
	protected function findTableNames($schema = '')
	{
w  
Qiang Xue committed
165 166
		if ($schema === '') {
			return $this->connection->createCommand('SHOW TABLES')->queryColumn();
w  
Qiang Xue committed
167
		}
w  
Qiang Xue committed
168 169 170
		$names = $this->connection->createCommand('SHOW TABLES FROM ' . $this->quoteSimpleTableName($schema))->queryColumn();
		foreach ($names as &$name) {
			$name = $schema . '.' . $name;
w  
Qiang Xue committed
171
		}
w  
Qiang Xue committed
172
		return $names;
w  
Qiang Xue committed
173 174
	}
}