Completed
Push — fix-unique-exists-expressions ( b0719b...8467f4 )
by Alexander
07:52
created

Schema::loadColumnSchema()   C

Complexity

Conditions 17
Paths 100

Size

Total Lines 59
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 306

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 59
ccs 0
cts 39
cp 0
rs 6.3438
cc 17
eloc 41
nc 100
nop 1
crap 306

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db\mysql;
9
10
use yii\db\ColumnSchema;
11
use yii\db\Expression;
12
use yii\db\TableSchema;
13
14
/**
15
 * Schema is the class for retrieving metadata from a MySQL database (version 4.1.x and 5.x).
16
 *
17
 * @author Qiang Xue <[email protected]>
18
 * @since 2.0
19
 */
20
class Schema extends \yii\db\Schema
21
{
22
    /**
23
     * @var array mapping from physical column types (keys) to abstract column types (values)
24
     */
25
    public $typeMap = [
26
        'tinyint' => self::TYPE_SMALLINT,
27
        'bit' => self::TYPE_INTEGER,
28
        'smallint' => self::TYPE_SMALLINT,
29
        'mediumint' => self::TYPE_INTEGER,
30
        'int' => self::TYPE_INTEGER,
31
        'integer' => self::TYPE_INTEGER,
32
        'bigint' => self::TYPE_BIGINT,
33
        'float' => self::TYPE_FLOAT,
34
        'double' => self::TYPE_DOUBLE,
35
        'real' => self::TYPE_FLOAT,
36
        'decimal' => self::TYPE_DECIMAL,
37
        'numeric' => self::TYPE_DECIMAL,
38
        'tinytext' => self::TYPE_TEXT,
39
        'mediumtext' => self::TYPE_TEXT,
40
        'longtext' => self::TYPE_TEXT,
41
        'longblob' => self::TYPE_BINARY,
42
        'blob' => self::TYPE_BINARY,
43
        'text' => self::TYPE_TEXT,
44
        'varchar' => self::TYPE_STRING,
45
        'string' => self::TYPE_STRING,
46
        'char' => self::TYPE_CHAR,
47
        'datetime' => self::TYPE_DATETIME,
48
        'year' => self::TYPE_DATE,
49
        'date' => self::TYPE_DATE,
50
        'time' => self::TYPE_TIME,
51
        'timestamp' => self::TYPE_TIMESTAMP,
52
        'enum' => self::TYPE_STRING,
53
        'varbinary' => self::TYPE_BINARY,
54
    ];
55
56
57
    /**
58
     * Quotes a table name for use in a query.
59
     * A simple table name has no schema prefix.
60
     * @param string $name table name
61
     * @return string the properly quoted table name
62
     */
63 36
    public function quoteSimpleTableName($name)
64
    {
65 36
        return strpos($name, '`') !== false ? $name : "`$name`";
66
    }
67
68
    /**
69
     * Quotes a column name for use in a query.
70
     * A simple column name has no prefix.
71
     * @param string $name column name
72
     * @return string the properly quoted column name
73
     */
74 66
    public function quoteSimpleColumnName($name)
75
    {
76 66
        return strpos($name, '`') !== false || $name === '*' ? $name : "`$name`";
77
    }
78
79
    /**
80
     * Creates a query builder for the MySQL database.
81
     * @return QueryBuilder query builder instance
82
     */
83 1
    public function createQueryBuilder()
84
    {
85 1
        return new QueryBuilder($this->db);
86
    }
87
88
    /**
89
     * Loads the metadata for the specified table.
90
     * @param string $name table name
91
     * @return TableSchema driver dependent table metadata. Null if the table does not exist.
92
     */
93 8
    protected function loadTableSchema($name)
94
    {
95 8
        $table = new TableSchema();
96 8
        $this->resolveTableNames($table, $name);
97
98 8
        if ($this->findColumns($table)) {
99
            $this->findConstraints($table);
100
101
            return $table;
102
        } else {
103
            return null;
104
        }
105
    }
106
107
    /**
108
     * Resolves the table name and schema name (if any).
109
     * @param TableSchema $table the table metadata object
110
     * @param string $name the table name
111
     */
112 8
    protected function resolveTableNames($table, $name)
113
    {
114 8
        $parts = explode('.', str_replace('`', '', $name));
115 8
        if (isset($parts[1])) {
116
            $table->schemaName = $parts[0];
117
            $table->name = $parts[1];
118
            $table->fullName = $table->schemaName . '.' . $table->name;
119
        } else {
120 8
            $table->fullName = $table->name = $parts[0];
121
        }
122 8
    }
123
124
    /**
125
     * Loads the column information into a [[ColumnSchema]] object.
126
     * @param array $info column information
127
     * @return ColumnSchema the column schema object
128
     */
129
    protected function loadColumnSchema($info)
130
    {
131
        $column = $this->createColumnSchema();
132
133
        $column->name = $info['field'];
134
        $column->allowNull = $info['null'] === 'YES';
135
        $column->isPrimaryKey = strpos($info['key'], 'PRI') !== false;
136
        $column->autoIncrement = stripos($info['extra'], 'auto_increment') !== false;
137
        $column->comment = $info['comment'];
138
139
        $column->dbType = $info['type'];
140
        $column->unsigned = stripos($column->dbType, 'unsigned') !== false;
141
142
        $column->type = self::TYPE_STRING;
143
        if (preg_match('/^(\w+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) {
144
            $type = strtolower($matches[1]);
145
            if (isset($this->typeMap[$type])) {
146
                $column->type = $this->typeMap[$type];
147
            }
148
            if (!empty($matches[2])) {
149
                if ($type === 'enum') {
150
                    preg_match_all("/'[^']*'/", $matches[2], $values);
151
                    foreach ($values[0] as $i => $value) {
152
                        $values[$i] = trim($value, "'");
153
                    }
154
                    $column->enumValues = $values;
0 ignored issues
show
Documentation Bug introduced by
It seems like $values can be null. However, the property $enumValues is declared as array. Maybe change the type of the property to array|null or add a type check?

Our type inference engine has found an assignment of a scalar value (like a string, an integer or null) to a property which is an array.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property.

To type hint that a parameter can be either an array or null, you can set a type hint of array and a default value of null. The PHP interpreter will then accept both an array or null for that parameter.

function aContainsB(array $needle = null, array  $haystack) {
    if (!$needle) {
        return false;
    }

    return array_intersect($haystack, $needle) == $haystack;
}

The function can be called with either null or an array for the parameter $needle but will only accept an array as $haystack.

Loading history...
155
                } else {
156
                    $values = explode(',', $matches[2]);
157
                    $column->size = $column->precision = (int) $values[0];
158
                    if (isset($values[1])) {
159
                        $column->scale = (int) $values[1];
160
                    }
161
                    if ($column->size === 1 && $type === 'bit') {
162
                        $column->type = 'boolean';
163
                    } elseif ($type === 'bit') {
164
                        if ($column->size > 32) {
165
                            $column->type = 'bigint';
166
                        } elseif ($column->size === 32) {
167
                            $column->type = 'integer';
168
                        }
169
                    }
170
                }
171
            }
172
        }
173
174
        $column->phpType = $this->getColumnPhpType($column);
175
176
        if (!$column->isPrimaryKey) {
177
            if ($column->type === 'timestamp' && $info['default'] === 'CURRENT_TIMESTAMP') {
178
                $column->defaultValue = new Expression('CURRENT_TIMESTAMP');
179
            } elseif (isset($type) && $type === 'bit') {
180
                $column->defaultValue = bindec(trim($info['default'], 'b\''));
181
            } else {
182
                $column->defaultValue = $column->phpTypecast($info['default']);
183
            }
184
        }
185
186
        return $column;
187
    }
188
189
    /**
190
     * Collects the metadata of table columns.
191
     * @param TableSchema $table the table metadata
192
     * @return bool whether the table exists in the database
193
     * @throws \Exception if DB query fails
194
     */
195 8
    protected function findColumns($table)
196
    {
197 8
        $sql = 'SHOW FULL COLUMNS FROM ' . $this->quoteTableName($table->fullName);
198
        try {
199 8
            $columns = $this->db->createCommand($sql)->queryAll();
200 8
        } catch (\Exception $e) {
201 8
            $previous = $e->getPrevious();
202 8
            if ($previous instanceof \PDOException && strpos($previous->getMessage(), 'SQLSTATE[42S02') !== false) {
203
                // table does not exist
204
                // https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_bad_table_error
205
                return false;
206
            }
207 8
            throw $e;
208
        }
209
        foreach ($columns as $info) {
210
            if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) !== \PDO::CASE_LOWER) {
211
                $info = array_change_key_case($info, CASE_LOWER);
212
            }
213
            $column = $this->loadColumnSchema($info);
214
            $table->columns[$column->name] = $column;
215
            if ($column->isPrimaryKey) {
216
                $table->primaryKey[] = $column->name;
217
                if ($column->autoIncrement) {
218
                    $table->sequenceName = '';
219
                }
220
            }
221
        }
222
223
        return true;
224
    }
225
226
    /**
227
     * Gets the CREATE TABLE sql string.
228
     * @param TableSchema $table the table metadata
229
     * @return string $sql the result of 'SHOW CREATE TABLE'
230
     */
231
    protected function getCreateTableSql($table)
232
    {
233
        $row = $this->db->createCommand('SHOW CREATE TABLE ' . $this->quoteTableName($table->fullName))->queryOne();
234
        if (isset($row['Create Table'])) {
235
            $sql = $row['Create Table'];
236
        } else {
237
            $row = array_values($row);
238
            $sql = $row[1];
239
        }
240
241
        return $sql;
242
    }
243
244
    /**
245
     * Collects the foreign key column details for the given table.
246
     * @param TableSchema $table the table metadata
247
     * @throws \Exception
248
     */
249
    protected function findConstraints($table)
250
    {
251
        $sql = <<<SQL
252
SELECT
253
    kcu.constraint_name,
254
    kcu.column_name,
255
    kcu.referenced_table_name,
256
    kcu.referenced_column_name
257
FROM information_schema.referential_constraints AS rc
258
JOIN information_schema.key_column_usage AS kcu ON
259
    (
260
        kcu.constraint_catalog = rc.constraint_catalog OR
261
        (kcu.constraint_catalog IS NULL AND rc.constraint_catalog IS NULL)
262
    ) AND
263
    kcu.constraint_schema = rc.constraint_schema AND
264
    kcu.constraint_name = rc.constraint_name
265
WHERE rc.constraint_schema = database() AND kcu.table_schema = database()
266
AND rc.table_name = :tableName AND kcu.table_name = :tableName1
267
SQL;
268
269
        try {
270
            $rows = $this->db->createCommand($sql, [':tableName' => $table->name, ':tableName1' => $table->name])->queryAll();
271
            $constraints = [];
272
273
            foreach ($rows as $row) {
274
                $constraints[$row['constraint_name']]['referenced_table_name'] = $row['referenced_table_name'];
275
                $constraints[$row['constraint_name']]['columns'][$row['column_name']] = $row['referenced_column_name'];
276
            }
277
278
            $table->foreignKeys = [];
279
            foreach ($constraints as $name => $constraint) {
280
                $table->foreignKeys[$name] = array_merge(
281
                    [$constraint['referenced_table_name']],
282
                    $constraint['columns']
283
                );
284
            }
285
        } catch (\Exception $e) {
286
            $previous = $e->getPrevious();
287
            if (!$previous instanceof \PDOException || strpos($previous->getMessage(), 'SQLSTATE[42S02') === false) {
288
                throw $e;
289
            }
290
291
            // table does not exist, try to determine the foreign keys using the table creation sql
292
            $sql = $this->getCreateTableSql($table);
293
            $regexp = '/FOREIGN KEY\s+\(([^\)]+)\)\s+REFERENCES\s+([^\(^\s]+)\s*\(([^\)]+)\)/mi';
294
            if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
295
                foreach ($matches as $match) {
296
                    $fks = array_map('trim', explode(',', str_replace('`', '', $match[1])));
297
                    $pks = array_map('trim', explode(',', str_replace('`', '', $match[3])));
298
                    $constraint = [str_replace('`', '', $match[2])];
299
                    foreach ($fks as $k => $name) {
300
                        $constraint[$name] = $pks[$k];
301
                    }
302
                    $table->foreignKeys[md5(serialize($constraint))] = $constraint;
303
                }
304
                $table->foreignKeys = array_values($table->foreignKeys);
305
            }
306
        }
307
    }
308
309
    /**
310
     * Returns all unique indexes for the given table.
311
     * Each array element is of the following structure:
312
     *
313
     * ```php
314
     * [
315
     *     'IndexName1' => ['col1' [, ...]],
316
     *     'IndexName2' => ['col2' [, ...]],
317
     * ]
318
     * ```
319
     *
320
     * @param TableSchema $table the table metadata
321
     * @return array all unique indexes for the given table.
322
     */
323
    public function findUniqueIndexes($table)
324
    {
325
        $sql = $this->getCreateTableSql($table);
326
        $uniqueIndexes = [];
327
328
        $regexp = '/UNIQUE KEY\s+([^\(\s]+)\s*\(([^\(\)]+)\)/mi';
329
        if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
330
            foreach ($matches as $match) {
331
                $indexName = str_replace('`', '', $match[1]);
332
                $indexColumns = array_map('trim', explode(',', str_replace('`', '', $match[2])));
333
                $uniqueIndexes[$indexName] = $indexColumns;
334
            }
335
        }
336
337
        return $uniqueIndexes;
338
    }
339
340
    /**
341
     * Returns all table names in the database.
342
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
343
     * @return array all table names in the database. The names have NO schema name prefix.
344
     */
345
    protected function findTableNames($schema = '')
346
    {
347
        $sql = 'SHOW TABLES';
348
        if ($schema !== '') {
349
            $sql .= ' FROM ' . $this->quoteSimpleTableName($schema);
350
        }
351
352
        return $this->db->createCommand($sql)->queryColumn();
353
    }
354
355
    /**
356
     * @inheritdoc
357
     */
358 1
    public function createColumnSchemaBuilder($type, $length = null)
359
    {
360 1
        return new ColumnSchemaBuilder($type, $length, $this->db);
361
    }
362
}
363