Completed
Push — prepare-travis-for-js ( a7ee60 )
by Carsten
08:12 queued 01:33
created

Schema::createQueryBuilder()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
cc 1
eloc 2
nc 1
nop 0
crap 1
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\Expression;
11
use yii\db\TableSchema;
12
use yii\db\ColumnSchema;
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 26
    public function quoteSimpleTableName($name)
64
    {
65 26
        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 64
    public function quoteSimpleColumnName($name)
75
    {
76 64
        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 1
    protected function loadTableSchema($name)
94
    {
95 1
        $table = new TableSchema;
96 1
        $this->resolveTableNames($table, $name);
97
98 1
        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 1
    protected function resolveTableNames($table, $name)
113
    {
114 1
        $parts = explode('.', str_replace('`', '', $name));
115 1
        if (isset($parts[1])) {
116
            $table->schemaName = $parts[0];
117
            $table->name = $parts[1];
118
            $table->fullName = $table->schemaName . '.' . $table->name;
119
        } else {
120 1
            $table->fullName = $table->name = $parts[0];
121
        }
122 1
    }
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 1
    protected function findColumns($table)
196
    {
197 1
        $sql = 'SHOW FULL COLUMNS FROM ' . $this->quoteTableName($table->fullName);
198
        try {
199 1
            $columns = $this->db->createCommand($sql)->queryAll();
200 1
        } catch (\Exception $e) {
201 1
            $previous = $e->getPrevious();
202 1
            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 1
            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
            foreach ($rows as $row) {
273
                $constraints[$row['constraint_name']]['referenced_table_name'] = $row['referenced_table_name'];
274
                $constraints[$row['constraint_name']]['columns'][$row['column_name']] = $row['referenced_column_name'];
275
            }
276
            $table->foreignKeys = [];
277
            foreach ($constraints as $constraint) {
278
                $table->foreignKeys[] = array_merge(
279
                    [$constraint['referenced_table_name']],
280
                    $constraint['columns']
281
                );
282
            }
283
        } catch (\Exception $e) {
284
            $previous = $e->getPrevious();
285
            if (!$previous instanceof \PDOException || strpos($previous->getMessage(), 'SQLSTATE[42S02') === false) {
286
                throw $e;
287
            }
288
289
            // table does not exist, try to determine the foreign keys using the table creation sql
290
            $sql = $this->getCreateTableSql($table);
291
            $regexp = '/FOREIGN KEY\s+\(([^\)]+)\)\s+REFERENCES\s+([^\(^\s]+)\s*\(([^\)]+)\)/mi';
292
            if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
293
                foreach ($matches as $match) {
294
                    $fks = array_map('trim', explode(',', str_replace('`', '', $match[1])));
295
                    $pks = array_map('trim', explode(',', str_replace('`', '', $match[3])));
296
                    $constraint = [str_replace('`', '', $match[2])];
297
                    foreach ($fks as $k => $name) {
298
                        $constraint[$name] = $pks[$k];
299
                    }
300
                    $table->foreignKeys[md5(serialize($constraint))] = $constraint;
301
                }
302
                $table->foreignKeys = array_values($table->foreignKeys);
303
            }
304
        }
305
    }
306
307
    /**
308
     * Returns all unique indexes for the given table.
309
     * Each array element is of the following structure:
310
     *
311
     * ```php
312
     * [
313
     *     'IndexName1' => ['col1' [, ...]],
314
     *     'IndexName2' => ['col2' [, ...]],
315
     * ]
316
     * ```
317
     *
318
     * @param TableSchema $table the table metadata
319
     * @return array all unique indexes for the given table.
320
     */
321
    public function findUniqueIndexes($table)
322
    {
323
        $sql = $this->getCreateTableSql($table);
324
        $uniqueIndexes = [];
325
326
        $regexp = '/UNIQUE KEY\s+([^\(\s]+)\s*\(([^\(\)]+)\)/mi';
327
        if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
328
            foreach ($matches as $match) {
329
                $indexName = str_replace('`', '', $match[1]);
330
                $indexColumns = array_map('trim', explode(',', str_replace('`', '', $match[2])));
331
                $uniqueIndexes[$indexName] = $indexColumns;
332
            }
333
        }
334
335
        return $uniqueIndexes;
336
    }
337
338
    /**
339
     * Returns all table names in the database.
340
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
341
     * @return array all table names in the database. The names have NO schema name prefix.
342
     */
343
    protected function findTableNames($schema = '')
344
    {
345
        $sql = 'SHOW TABLES';
346
        if ($schema !== '') {
347
            $sql .= ' FROM ' . $this->quoteSimpleTableName($schema);
348
        }
349
350
        return $this->db->createCommand($sql)->queryColumn();
351
    }
352
353
    /**
354
     * @inheritdoc
355
     */
356 1
    public function createColumnSchemaBuilder($type, $length = null)
357
    {
358 1
        return new ColumnSchemaBuilder($type, $length, $this->db);
359
    }
360
}
361