Schema.php 10.2 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\mysql;
w  
Qiang Xue committed
9

10
use yii\db\Expression;
Qiang Xue committed
11 12
use yii\db\TableSchema;
use yii\db\ColumnSchema;
Qiang Xue committed
13

w  
Qiang Xue committed
14
/**
Qiang Xue committed
15
 * Schema is the class for retrieving metadata from a MySQL database (version 4.1.x and 5.x).
w  
Qiang Xue committed
16 17
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
18
 * @since 2.0
w  
Qiang Xue committed
19
 */
Qiang Xue committed
20
class Schema extends \yii\db\Schema
w  
Qiang Xue committed
21
{
22 23 24 25 26
    /**
     * @var array mapping from physical column types (keys) to abstract column types (values)
     */
    public $typeMap = [
        'tinyint' => self::TYPE_SMALLINT,
27
        'bit' => self::TYPE_INTEGER,
28 29 30 31 32 33 34 35 36 37 38 39 40
        'smallint' => self::TYPE_SMALLINT,
        'mediumint' => self::TYPE_INTEGER,
        'int' => self::TYPE_INTEGER,
        'integer' => self::TYPE_INTEGER,
        'bigint' => self::TYPE_BIGINT,
        'float' => self::TYPE_FLOAT,
        'double' => self::TYPE_FLOAT,
        'real' => self::TYPE_FLOAT,
        'decimal' => self::TYPE_DECIMAL,
        'numeric' => self::TYPE_DECIMAL,
        'tinytext' => self::TYPE_TEXT,
        'mediumtext' => self::TYPE_TEXT,
        'longtext' => self::TYPE_TEXT,
41 42
        'longblob' => self::TYPE_BINARY,
        'blob' => self::TYPE_BINARY,
43 44 45 46 47 48 49 50 51 52 53
        'text' => self::TYPE_TEXT,
        'varchar' => self::TYPE_STRING,
        'string' => self::TYPE_STRING,
        'char' => self::TYPE_STRING,
        'datetime' => self::TYPE_DATETIME,
        'year' => self::TYPE_DATE,
        'date' => self::TYPE_DATE,
        'time' => self::TYPE_TIME,
        'timestamp' => self::TYPE_TIMESTAMP,
        'enum' => self::TYPE_STRING,
    ];
Qiang Xue committed
54

55

56 57 58
    /**
     * Quotes a table name for use in a query.
     * A simple table name has no schema prefix.
59
     * @param string $name table name
60 61 62 63 64 65
     * @return string the properly quoted table name
     */
    public function quoteSimpleTableName($name)
    {
        return strpos($name, "`") !== false ? $name : "`" . $name . "`";
    }
w  
Qiang Xue committed
66

67 68 69
    /**
     * Quotes a column name for use in a query.
     * A simple column name has no prefix.
70
     * @param string $name column name
71 72 73 74 75 76
     * @return string the properly quoted column name
     */
    public function quoteSimpleColumnName($name)
    {
        return strpos($name, '`') !== false || $name === '*' ? $name : '`' . $name . '`';
    }
w  
Qiang Xue committed
77

78 79 80 81 82 83 84 85
    /**
     * Creates a query builder for the MySQL database.
     * @return QueryBuilder query builder instance
     */
    public function createQueryBuilder()
    {
        return new QueryBuilder($this->db);
    }
Qiang Xue committed
86

87 88
    /**
     * Loads the metadata for the specified table.
89
     * @param string $name table name
90 91 92 93 94 95
     * @return TableSchema driver dependent table metadata. Null if the table does not exist.
     */
    protected function loadTableSchema($name)
    {
        $table = new TableSchema;
        $this->resolveTableNames($table, $name);
w  
Qiang Xue committed
96

97 98
        if ($this->findColumns($table)) {
            $this->findConstraints($table);
w  
Qiang Xue committed
99

100 101 102 103 104
            return $table;
        } else {
            return null;
        }
    }
w  
Qiang Xue committed
105

106 107 108
    /**
     * Resolves the table name and schema name (if any).
     * @param TableSchema $table the table metadata object
109
     * @param string $name the table name
110 111 112 113 114 115 116 117 118 119 120 121
     */
    protected function resolveTableNames($table, $name)
    {
        $parts = explode('.', str_replace('`', '', $name));
        if (isset($parts[1])) {
            $table->schemaName = $parts[0];
            $table->name = $parts[1];
            $table->fullName = $table->schemaName . '.' . $table->name;
        } else {
            $table->fullName = $table->name = $parts[0];
        }
    }
w  
Qiang Xue committed
122

123 124
    /**
     * Loads the column information into a [[ColumnSchema]] object.
125
     * @param array $info column information
126 127 128 129 130
     * @return ColumnSchema the column schema object
     */
    protected function loadColumnSchema($info)
    {
        $column = new ColumnSchema;
Qiang Xue committed
131

132 133 134 135 136
        $column->name = $info['Field'];
        $column->allowNull = $info['Null'] === 'YES';
        $column->isPrimaryKey = strpos($info['Key'], 'PRI') !== false;
        $column->autoIncrement = stripos($info['Extra'], 'auto_increment') !== false;
        $column->comment = $info['Comment'];
Qiang Xue committed
137

138
        $column->dbType = $info['Type'];
139
        $column->unsigned = stripos($column->dbType, 'unsigned') !== false;
Qiang Xue committed
140

141 142
        $column->type = self::TYPE_STRING;
        if (preg_match('/^(\w+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) {
143
            $type = strtolower($matches[1]);
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
            if (isset($this->typeMap[$type])) {
                $column->type = $this->typeMap[$type];
            }
            if (!empty($matches[2])) {
                if ($type === 'enum') {
                    $values = explode(',', $matches[2]);
                    foreach ($values as $i => $value) {
                        $values[$i] = trim($value, "'");
                    }
                    $column->enumValues = $values;
                } else {
                    $values = explode(',', $matches[2]);
                    $column->size = $column->precision = (int) $values[0];
                    if (isset($values[1])) {
                        $column->scale = (int) $values[1];
                    }
                    if ($column->size === 1 && $type === 'bit') {
                        $column->type = 'boolean';
                    } elseif ($type === 'bit') {
                        if ($column->size > 32) {
                            $column->type = 'bigint';
                        } elseif ($column->size === 32) {
                            $column->type = 'integer';
                        }
                    }
                }
            }
        }
Qiang Xue committed
172

173
        $column->phpType = $this->getColumnPhpType($column);
Qiang Xue committed
174

175 176 177
        if (!$column->isPrimaryKey) {
            if ($column->type === 'timestamp' && $info['Default'] === 'CURRENT_TIMESTAMP') {
                $column->defaultValue = new Expression('CURRENT_TIMESTAMP');
178 179
            } elseif (isset($type) && $type === 'bit') {
                $column->defaultValue = bindec(trim($info['Default'],'b\''));
180
            } else {
181
                $column->defaultValue = $column->phpTypecast($info['Default']);
182
            }
183
        }
Qiang Xue committed
184

185 186
        return $column;
    }
Qiang Xue committed
187

188 189
    /**
     * Collects the metadata of table columns.
190 191 192
     * @param TableSchema $table the table metadata
     * @return boolean whether the table exists in the database
     * @throws \Exception if DB query fails
193 194 195
     */
    protected function findColumns($table)
    {
Qiang Xue committed
196
        $sql = 'SHOW FULL COLUMNS FROM ' . $this->quoteTableName($table->fullName);
197 198 199 200
        try {
            $columns = $this->db->createCommand($sql)->queryAll();
        } catch (\Exception $e) {
            $previous = $e->getPrevious();
201
            if ($previous instanceof \PDOException && strpos($previous->getMessage(), 'SQLSTATE[42S02') !== false) {
202
                // table does not exist
203
                // https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_bad_table_error
204 205 206 207 208 209 210 211 212 213 214 215 216 217
                return false;
            }
            throw $e;
        }
        foreach ($columns as $info) {
            $column = $this->loadColumnSchema($info);
            $table->columns[$column->name] = $column;
            if ($column->isPrimaryKey) {
                $table->primaryKey[] = $column->name;
                if ($column->autoIncrement) {
                    $table->sequenceName = '';
                }
            }
        }
w  
Qiang Xue committed
218

219 220
        return true;
    }
221

222 223
    /**
     * Gets the CREATE TABLE sql string.
224 225
     * @param TableSchema $table the table metadata
     * @return string $sql the result of 'SHOW CREATE TABLE'
226 227 228
     */
    protected function getCreateTableSql($table)
    {
Steve committed
229
        $row = $this->db->createCommand('SHOW CREATE TABLE ' . $this->quoteTableName($table->fullName))->queryOne();
230 231 232 233 234 235
        if (isset($row['Create Table'])) {
            $sql = $row['Create Table'];
        } else {
            $row = array_values($row);
            $sql = $row[1];
        }
Qiang Xue committed
236

237 238
        return $sql;
    }
w  
Qiang Xue committed
239

240 241 242 243 244 245 246
    /**
     * Collects the foreign key column details for the given table.
     * @param TableSchema $table the table metadata
     */
    protected function findConstraints($table)
    {
        $sql = $this->getCreateTableSql($table);
247

248 249 250 251 252 253 254 255 256 257 258 259 260
        $regexp = '/FOREIGN KEY\s+\(([^\)]+)\)\s+REFERENCES\s+([^\(^\s]+)\s*\(([^\)]+)\)/mi';
        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])));
                $constraint = [str_replace('`', '', $match[2])];
                foreach ($fks as $k => $name) {
                    $constraint[$name] = $pks[$k];
                }
                $table->foreignKeys[] = $constraint;
            }
        }
    }
261

262 263 264 265 266 267
    /**
     * Returns all unique indexes for the given table.
     * Each array element is of the following structure:
     *
     * ~~~
     * [
268 269
     *  'IndexName1' => ['col1' [, ...]],
     *  'IndexName2' => ['col2' [, ...]],
270 271 272
     * ]
     * ~~~
     *
273 274
     * @param TableSchema $table the table metadata
     * @return array all unique indexes for the given table.
275 276 277 278 279 280
     */
    public function findUniqueIndexes($table)
    {
        $sql = $this->getCreateTableSql($table);
        $uniqueIndexes = [];

Qiang Xue committed
281
        $regexp = '/UNIQUE KEY\s+([^\(\s]+)\s*\(([^\(\)]+)\)/mi';
282 283 284 285 286 287 288 289 290 291 292 293 294
        if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
            foreach ($matches as $match) {
                $indexName = str_replace('`', '', $match[1]);
                $indexColumns = array_map('trim', explode(',', str_replace('`', '', $match[2])));
                $uniqueIndexes[$indexName] = $indexColumns;
            }
        }

        return $uniqueIndexes;
    }

    /**
     * Returns all table names in the database.
295 296
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
     * @return array all table names in the database. The names have NO schema name prefix.
297 298 299 300 301 302 303 304 305 306
     */
    protected function findTableNames($schema = '')
    {
        $sql = 'SHOW TABLES';
        if ($schema !== '') {
            $sql .= ' FROM ' . $this->quoteSimpleTableName($schema);
        }

        return $this->db->createCommand($sql)->queryColumn();
    }
w  
Qiang Xue committed
307
}