Test Failed
Pull Request — master (#206)
by Alexander
04:04
created

Schema   F

Complexity

Total Complexity 75

Size/Duplication

Total Lines 804
Duplicated Lines 0 %

Test Coverage

Coverage 99.58%

Importance

Changes 15
Bugs 1 Features 1
Metric Value
eloc 343
c 15
b 1
f 1
dl 0
loc 804
ccs 239
cts 240
cp 0.9958
rs 2.4
wmc 75

24 Methods

Rating   Name   Duplication   Size   Complexity  
F loadColumnSchema() 0 84 21
A findViewNames() 0 19 2
A loadTableUniques() 0 5 2
A findTableNames() 0 9 2
B findColumns() 0 44 8
B loadTableConstraints() 0 109 7
A resolveTableName() 0 17 2
A findConstraints() 0 47 3
A findSchemaNames() 0 7 1
A findTableComment() 0 16 2
A getCreateTableSql() 0 21 3
A createColumnSchema() 0 3 1
A getCacheTag() 0 3 1
A loadTableForeignKeys() 0 5 2
A resolveTableCreateSql() 0 4 1
A getCacheKey() 0 3 1
A loadTableChecks() 0 3 1
A loadTableSchema() 0 13 2
A loadTableDefaultValues() 0 3 1
A loadTableIndexes() 0 44 3
A createColumnSchemaBuilder() 0 3 1
A findUniqueIndexes() 0 19 3
A getJsonColumns() 0 14 3
A loadTablePrimaryKey() 0 5 2

How to fix   Complexity   

Complex Class

Complex classes like Schema often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Schema, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Mysql;
6
7
use JsonException;
8
use Throwable;
9
use Yiisoft\Arrays\ArrayHelper;
10
use Yiisoft\Db\Constraint\Constraint;
11
use Yiisoft\Db\Constraint\ForeignKeyConstraint;
12
use Yiisoft\Db\Constraint\IndexConstraint;
13
use Yiisoft\Db\Exception\Exception;
14
use Yiisoft\Db\Exception\InvalidConfigException;
15
use Yiisoft\Db\Exception\NotSupportedException;
16
use Yiisoft\Db\Expression\Expression;
17
use Yiisoft\Db\Schema\ColumnSchemaInterface;
18
use Yiisoft\Db\Schema\Schema as AbstractSchema;
19
use Yiisoft\Db\Schema\TableSchemaInterface;
20
21
use function array_map;
22
use function array_merge;
23
use function array_values;
24
use function bindec;
25
use function explode;
26
use function in_array;
27
use function is_string;
28
use function ksort;
29
use function md5;
30
use function preg_match_all;
31
use function preg_match;
32
use function serialize;
33
use function stripos;
34
use function strtolower;
35
use function trim;
36
37
/**
38
 * The class Schema is the class for retrieving metadata from a Mysql database (version 5.7 and above).
39
 *
40
 * @psalm-type ColumnArray = array{
41
 *   table_schema: string,
42
 *   table_name: string,
43
 *   column_name: string,
44
 *   data_type: string,
45
 *   type_type: string|null,
46
 *   character_maximum_length: int,
47
 *   column_comment: string|null,
48
 *   modifier: int,
49
 *   is_nullable: bool,
50
 *   column_default: mixed,
51
 *   is_autoinc: bool,
52
 *   sequence_name: string|null,
53
 *   enum_values: array<array-key, float|int|string>|string|null,
54
 *   numeric_precision: int|null,
55
 *   numeric_scale: int|null,
56
 *   size: string|null,
57
 *   is_pkey: bool|null,
58
 *   dimension: int
59
 * }
60
 *
61
 * @psalm-type ColumnInfoArray = array{
62
 *   field: string,
63
 *   type: string,
64
 *   collation: string|null,
65
 *   null: string,
66
 *   key: string,
67
 *   default: string|null,
68
 *   extra: string,
69
 *   privileges: string,
70
 *   comment: string
71
 * }
72
 *
73
 * @psalm-type RowConstraint = array{
74
 *   constraint_name: string,
75
 *   column_name: string,
76
 *   referenced_table_name: string,
77
 *   referenced_column_name: string
78
 * }
79
 *
80
 * @psalm-type ConstraintArray = array<
81
 *   array-key,
82
 *   array {
83
 *     name: string,
84
 *     column_name: string,
85
 *     type: string,
86
 *     foreign_table_schema: string|null,
87
 *     foreign_table_name: string|null,
88
 *     foreign_column_name: string|null,
89
 *     on_update: string,
90
 *     on_delete: string,
91
 *     check_expr: string
92
 *   }
93
 * >
94
 */
95
final class Schema extends AbstractSchema
96
{
97
    /** @var array<array-key, string> $typeMap */
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<array-key, string> at position 2 could not be parsed: Unknown type name 'array-key' at position 2 in array<array-key, string>.
Loading history...
98
    private array $typeMap = [
99
        'tinyint' => self::TYPE_TINYINT,
100
        'bit' => self::TYPE_INTEGER,
101
        'smallint' => self::TYPE_SMALLINT,
102
        'mediumint' => self::TYPE_INTEGER,
103
        'int' => self::TYPE_INTEGER,
104
        'integer' => self::TYPE_INTEGER,
105
        'bigint' => self::TYPE_BIGINT,
106
        'float' => self::TYPE_FLOAT,
107
        'double' => self::TYPE_DOUBLE,
108
        'real' => self::TYPE_FLOAT,
109
        'decimal' => self::TYPE_DECIMAL,
110
        'numeric' => self::TYPE_DECIMAL,
111
        'tinytext' => self::TYPE_TEXT,
112
        'mediumtext' => self::TYPE_TEXT,
113
        'longtext' => self::TYPE_TEXT,
114
        'longblob' => self::TYPE_BINARY,
115
        'blob' => self::TYPE_BINARY,
116
        'text' => self::TYPE_TEXT,
117
        'varchar' => self::TYPE_STRING,
118
        'string' => self::TYPE_STRING,
119
        'char' => self::TYPE_CHAR,
120
        'datetime' => self::TYPE_DATETIME,
121
        'year' => self::TYPE_DATE,
122
        'date' => self::TYPE_DATE,
123
        'time' => self::TYPE_TIME,
124
        'timestamp' => self::TYPE_TIMESTAMP,
125
        'enum' => self::TYPE_STRING,
126
        'varbinary' => self::TYPE_BINARY,
127
        'json' => self::TYPE_JSON,
128
    ];
129
130
    /**
131
     * Create a column schema builder instance giving the type and value precision.
132
     *
133
     * This method may be overridden by child classes to create a DBMS-specific column schema builder.
134
     *
135
     * @param string $type type of the column. See {@see ColumnSchemaBuilder::$type}.
136
     * @param array|int|string|null $length length or precision of the column. See {@see ColumnSchemaBuilder::$length}.
137
     *
138
     * @return ColumnSchemaBuilder column schema builder instance
139
     *
140 10
     * @psalm-param string[]|int[]|int|string|null $length
141
     */
142 10
    public function createColumnSchemaBuilder(string $type, array|int|string $length = null): ColumnSchemaBuilder
143
    {
144
        return new ColumnSchemaBuilder($type, $length, $this->db->getQuoter());
145
    }
146
147
    /**
148
     * Returns all unique indexes for the given table.
149
     *
150
     * Each array element is of the following structure:
151
     *
152
     * ```php
153
     * [
154
     *     'IndexName1' => ['col1' [, ...]],
155
     *     'IndexName2' => ['col2' [, ...]],
156
     * ]
157
     * ```
158
     *
159
     * @param TableSchemaInterface $table the table metadata.
160
     *
161
     * @throws Exception
162
     * @throws InvalidConfigException
163
     * @throws Throwable
164
     *
165 1
     * @return array all unique indexes for the given table.
166
     */
167 1
    public function findUniqueIndexes(TableSchemaInterface $table): array
168
    {
169 1
        $sql = $this->getCreateTableSql($table);
170
171 1
        $uniqueIndexes = [];
172
173 1
        $regexp = '/UNIQUE KEY\s+`(.+)`\s*\((`.+`)+\)/mi';
174 1
175 1
        if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
176 1
            foreach ($matches as $match) {
177 1
                $indexName = $match[1];
178
                $indexColumns = array_map('trim', explode('`,`', trim($match[2], '`')));
179
                $uniqueIndexes[$indexName] = $indexColumns;
180
            }
181 1
        }
182
183 1
        ksort($uniqueIndexes);
184
185
        return $uniqueIndexes;
186
    }
187
188
    /**
189
     * Collects the metadata of table columns.
190
     *
191
     * @param TableSchemaInterface $table the table metadata.
192
     *
193
     * @throws Exception
194
     * @throws Throwable if DB query fails.
195
     *
196 147
     * @return bool whether the table exists in the database.
197
     */
198 147
    protected function findColumns(TableSchemaInterface $table): bool
199 147
    {
200
        $tableName = $table->getFullName() ?? '';
201
        $sql = 'SHOW FULL COLUMNS FROM ' . $this->db->getQuoter()->quoteTableName($tableName);
202 147
203 30
        try {
204 30
            $columns = $this->db->createCommand($sql)->queryAll();
205
        } catch (Exception $e) {
206 30
            $previous = $e->getPrevious();
207
208
            if ($previous && str_contains($previous->getMessage(), 'SQLSTATE[42S02')) {
209
                /**
210
                 * table does not exist.
211
                 *
212 30
                 * https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_bad_table_error
213
                 */
214
                return false;
215
            }
216
217
            throw $e;
218
        }
219 130
220 130
        $jsonColumns = $this->getJsonColumns($table);
221
222 130
        /** @psalm-var ColumnInfoArray $info */
223 130
        foreach ($columns as $info) {
224
            $info = $this->normalizeRowKeyCase($info, false);
225 130
226 82
            if (in_array($info['field'], $jsonColumns, true)) {
227 82
                $info['type'] = self::TYPE_JSON;
228 68
            }
229
230
            $column = $this->loadColumnSchema($info);
231
            $table->columns($column->getName(), $column);
232
233 130
            if ($column->isPrimaryKey()) {
234
                $table->primaryKey($column->getName());
235
                if ($column->isAutoIncrement()) {
236
                    $table->sequenceName('');
237
                }
238
            }
239
        }
240
241
        return true;
242
    }
243
244
    /**
245 130
     * Collects the foreign key column details for the given table.
246
     *
247 130
     * @param TableSchemaInterface $table the table metadata.
248
     *
249
     * @throws Exception
250
     * @throws InvalidConfigException
251
     * @throws Throwable
252
     */
253
    protected function findConstraints(TableSchemaInterface $table): void
254
    {
255
        $sql = <<<SQL
256
        SELECT
257
            `kcu`.`CONSTRAINT_NAME` AS `constraint_name`,
258
            `kcu`.`COLUMN_NAME` AS `column_name`,
259
            `kcu`.`REFERENCED_TABLE_NAME` AS `referenced_table_name`,
260
            `kcu`.`REFERENCED_COLUMN_NAME` AS `referenced_column_name`
261
        FROM `information_schema`.`REFERENTIAL_CONSTRAINTS` AS `rc`
262
        JOIN `information_schema`.`KEY_COLUMN_USAGE` AS `kcu` ON
263
            (
264
                `kcu`.`CONSTRAINT_CATALOG` = `rc`.`CONSTRAINT_CATALOG` OR
265
                (
266
                    `kcu`.`CONSTRAINT_CATALOG` IS NULL AND
267 130
                    `rc`.`CONSTRAINT_CATALOG` IS NULL
268
                )
269 130
            ) AND
270 130
            `kcu`.`CONSTRAINT_SCHEMA` = `rc`.`CONSTRAINT_SCHEMA` AND
271 130
            `kcu`.`CONSTRAINT_NAME` = `rc`.`CONSTRAINT_NAME` AND
272 130
            `kcu`.`TABLE_SCHEMA` = `rc`.`CONSTRAINT_SCHEMA` AND
273 130
            `kcu`.`TABLE_NAME` = `rc`.`TABLE_NAME`
274
        WHERE `rc`.`CONSTRAINT_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND `rc`.`TABLE_NAME` = :tableName
275
        SQL;
276 130
277 34
        $constraints = [];
278 34
        $rows = $this->db->createCommand($sql, [
279
            ':schemaName' => $table->getSchemaName(),
280
            ':tableName' => $table->getName(),
281 130
        ])->queryAll();
282
283
        /**  @psalm-var RowConstraint $row */
284
        foreach ($rows as $row) {
285
            $constraints[$row['constraint_name']]['referenced_table_name'] = $row['referenced_table_name'];
286 130
            $constraints[$row['constraint_name']]['columns'][$row['column_name']] = $row['referenced_column_name'];
287 34
        }
288 34
289 34
        $table->foreignKeys([]);
290 34
291 34
        /**
292 34
         * @var array{referenced_table_name: string, columns: array} $constraint
293 34
         */
294
        foreach ($constraints as $name => $constraint) {
295
            $table->foreignKey(
296
                $name,
297
                array_merge(
298
                    [$constraint['referenced_table_name']],
299
                    $constraint['columns']
300
                ),
301
            );
302 1
        }
303
    }
304 1
305
    /**
306 1
     * @throws Exception
307
     * @throws InvalidConfigException
308 1
     * @throws Throwable
309
     */
310
    protected function findSchemaNames(): array
311
    {
312
        $sql = <<<SQL
313
        SELECT schema_name FROM information_schema.schemata WHERE schema_name NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')
314
        SQL;
315
316 147
        return $this->db->createCommand($sql)->queryColumn();
317
    }
318 147
319
    /**
320
     * @throws Exception
321
     * @throws InvalidConfigException
322
     * @throws Throwable
323
     */
324 147
    protected function findTableComment(TableSchemaInterface $tableSchema): void
325
    {
326 147
        $sql = <<<SQL
327 147
        SELECT `TABLE_COMMENT`
328 147
        FROM `INFORMATION_SCHEMA`.`TABLES`
329 147
        WHERE
330
              `TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND
331 147
              `TABLE_NAME` = :tableName;
332
        SQL;
333
334
        $comment = $this->db->createCommand($sql, [
335
            ':schemaName' => $tableSchema->getSchemaName(),
336
            ':tableName' => $tableSchema->getName(),
337
        ])->queryScalar();
338
339
        $tableSchema->comment(is_string($comment) ? $comment : null);
340
    }
341
342
    /**
343
     * Returns all table names in the database.
344
     *
345
     * This method should be overridden by child classes in order to support this feature because the default
346
     * implementation simply throws an exception.
347
     *
348 12
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
349
     *
350 12
     * @throws Exception
351
     * @throws InvalidConfigException
352 12
     * @throws Throwable
353 1
     *
354
     * @return array All table names in the database. The names have NO schema name prefix.
355
     */
356 12
    protected function findTableNames(string $schema = ''): array
357
    {
358
        $sql = 'SHOW TABLES';
359
360
        if ($schema !== '') {
361
            $sql .= ' FROM ' . $this->db->getQuoter()->quoteSimpleTableName($schema);
362
        }
363
364 1
        return $this->db->createCommand($sql)->queryColumn();
365
    }
366 1
367 1
    /**
368
     * @throws Exception
369 1
     * @throws InvalidConfigException
370 1
     * @throws Throwable
371 1
     */
372 1
    protected function findViewNames(string $schema = ''): array
373 1
    {
374
        $sql = match ($schema) {
375
            '' => <<<SQL
376 1
            SELECT table_name as view FROM information_schema.tables WHERE table_type LIKE 'VIEW' AND table_schema != 'sys'
377
            SQL,
378 1
            default => <<<SQL
379 1
            SELECT table_name as view FROM information_schema.tables WHERE table_type LIKE 'VIEW' AND table_schema = '$schema'
380
            SQL,
381
        };
382 1
383
        /** @psalm-var string[][] $views */
384
        $views = $this->db->createCommand($sql)->queryAll();
385
386
        foreach ($views as $key => $view) {
387
            $views[$key] = $view['view'];
388
        }
389
390
        return $views;
391
    }
392 243
393
    /**
394 243
     * Returns the cache key for the specified table name.
395
     *
396
     * @param string $name the table name.
397
     *
398
     * @return array the cache key.
399
     */
400
    protected function getCacheKey(string $name): array
401
    {
402
        return array_merge([self::class], $this->db->getCacheKey(), [$this->getRawTableName($name)]);
403
    }
404 244
405
    /**
406 244
     * Returns the cache tag name.
407
     *
408
     * This allows {@see refresh()} to invalidate all cached table schemas.
409
     *
410
     * @return string the cache tag name.
411
     */
412
    protected function getCacheTag(): string
413
    {
414
        return md5(serialize(array_merge([self::class], $this->db->getCacheKey())));
415
    }
416
417
    /**
418
     * Gets the CREATE TABLE sql string.
419
     *
420 147
     * @param TableSchemaInterface $table the table metadata.
421
     *
422 147
     * @throws Exception
423
     * @throws InvalidConfigException
424
     * @throws Throwable
425
     *
426 147
     * @return string $sql the result of 'SHOW CREATE TABLE'.
427 147
     */
428 147
    protected function getCreateTableSql(TableSchemaInterface $table): string
429
    {
430 130
        $tableName = $table->getFullName() ?? '';
431 128
432
        try {
433 4
            /** @var array<array-key, string> $row */
434 130
            $row = $this->db->createCommand(
435
                'SHOW CREATE TABLE ' . $this->db->getQuoter()->quoteTableName($tableName)
436 30
            )->queryOne();
437 30
438
            if (isset($row['Create Table'])) {
439
                $sql = $row['Create Table'];
440 147
            } else {
441
                $row = array_values($row);
0 ignored issues
show
Bug introduced by
$row of type null is incompatible with the type array expected by parameter $array of array_values(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

441
                $row = array_values(/** @scrutinizer ignore-type */ $row);
Loading history...
442
                $sql = $row[1];
443
            }
444
        } catch (Exception) {
445
            $sql = '';
446
        }
447
448
        return $sql;
449
    }
450
451
    /**
452 131
     * Loads the column information into a {@see ColumnSchemaInterface} object.
453
     *
454 131
     * @param array $info column information.
455
     *
456
     * @throws JsonException
457 131
     *
458 131
     * @return ColumnSchemaInterface the column schema object.
459 131
     */
460 131
    protected function loadColumnSchema(array $info): ColumnSchemaInterface
461 131
    {
462 131
        $column = $this->createColumnSchema();
463 131
464 131
        /** @psalm-var ColumnInfoArray $info */
465
        $column->name($info['field']);
466 131
        $column->allowNull($info['null'] === 'YES');
467 131
        $column->primaryKey(str_contains($info['key'], 'PRI'));
468 28
        $column->autoIncrement(stripos($info['extra'], 'auto_increment') !== false);
469
        $column->comment($info['comment']);
470 131
        $column->dbType($info['type']);
471
        $column->unsigned(stripos($column->getDbType(), 'unsigned') !== false);
472 131
        $column->type(self::TYPE_STRING);
473 131
474
        $extra = $info['extra'];
475 131
476 131
        if (str_starts_with($extra, 'DEFAULT_GENERATED')) {
477
            $extra = strtoupper(substr($extra, 18));
478
        }
479 131
        $column->extra(trim($extra));
480 102
481 26
        if (preg_match('/^(\w+)(?:\(([^)]+)\))?/', $column->getDbType(), $matches)) {
482
            $type = strtolower($matches[1]);
483 26
484 26
            if (isset($this->typeMap[$type])) {
485
                $column->type($this->typeMap[$type]);
486
            }
487 26
488
            if (!empty($matches[2])) {
489 102
                if ($type === 'enum') {
490 102
                    preg_match_all("/'[^']*'/", $matches[2], $values);
491 102
492
                    foreach ($values[0] as $i => $value) {
493 102
                        $values[$i] = trim($value, "'");
494 40
                    }
495
496
                    $column->enumValues($values);
497 102
                } else {
498 27
                    $values = explode(',', $matches[2]);
499 102
                    $column->precision((int) $values[0]);
500 27
                    $column->size((int) $values[0]);
501 4
502 27
                    if (isset($values[1])) {
503 4
                        $column->scale((int) $values[1]);
504
                    }
505
506
                    if ($column->getSize() === 1 && $type === 'tinyint') {
507
                        $column->type(self::TYPE_BOOLEAN);
508
                    } elseif ($type === 'bit') {
509
                        if ($column->getSize() > 32) {
510 131
                            $column->type(self::TYPE_BIGINT);
511
                        } elseif ($column->getSize() === 32) {
512 131
                            $column->type(self::TYPE_INTEGER);
513
                        }
514
                    }
515
                }
516
            }
517
        }
518
519
        $column->phpType($this->getColumnPhpType($column));
520 129
521 129
        if (!$column->isPrimaryKey()) {
522
            /**
523 29
             * When displayed in the INFORMATION_SCHEMA.COLUMNS table, a default CURRENT TIMESTAMP is displayed
524 29
             * as CURRENT_TIMESTAMP up until MariaDB 10.2.2, and as current_timestamp() from MariaDB 10.2.3.
525 126
             *
526 27
             * See details here: https://mariadb.com/kb/en/library/now/#description
527
             */
528 129
            if (
529
                ($column->getType() === 'timestamp' || $column->getType() === 'datetime')
530 82
                && preg_match('/^current_timestamp(?:\((\d*)\))?$/i', (string) $info['default'], $matches)
531 3
            ) {
532
                $column->defaultValue(new Expression('CURRENT_TIMESTAMP' . (!empty($matches[1])
533
                    ? '(' . $matches[1] . ')' : '')));
534 131
            } elseif (isset($type) && $type === 'bit') {
535
                $column->defaultValue(bindec(trim((string) $info['default'], 'b\'')));
536
            } else {
537
                $column->defaultValue($column->phpTypecast($info['default']));
538
            }
539
        } elseif ($info['default'] !== null) {
540
            $column->defaultValue($column->phpTypecast($info['default']));
541
        }
542
543
        return $column;
544
    }
545
546 16
    /**
547
     * Loads all check constraints for the given table.
548 16
     *
549
     * @param string $tableName table name.
550
     *
551
     * @throws NotSupportedException
552
     *
553
     * @return array check constraints for the given table.
554
     */
555
    protected function loadTableChecks(string $tableName): array
556
    {
557
        throw new NotSupportedException(__METHOD__ . ' is not supported by MySQL.');
558
    }
559
560
    /**
561
     * Loads multiple types of constraints and returns the specified ones.
562
     *
563
     * @param string $tableName table name.
564
     * @param string $returnType return type:
565
     * - primaryKey
566 71
     * - foreignKeys
567
     * - uniques
568 71
     *
569
     * @throws Exception
570
     * @throws InvalidConfigException
571
     * @throws Throwable
572
     *
573
     * @return array|Constraint|null (Constraint|ForeignKeyConstraint)[]|Constraint|null constraints.
574
     */
575
    private function loadTableConstraints(string $tableName, string $returnType): array|Constraint|null
576
    {
577
        $sql = <<<SQL
578
        SELECT
579
            `kcu`.`CONSTRAINT_NAME` AS `name`,
580
            `kcu`.`COLUMN_NAME` AS `column_name`,
581
            `tc`.`CONSTRAINT_TYPE` AS `type`,
582
        CASE
583
            WHEN :schemaName IS NULL AND `kcu`.`REFERENCED_TABLE_SCHEMA` = DATABASE() THEN NULL
584
        ELSE `kcu`.`REFERENCED_TABLE_SCHEMA`
585
        END AS `foreign_table_schema`,
586
            `kcu`.`REFERENCED_TABLE_NAME` AS `foreign_table_name`,
587
            `kcu`.`REFERENCED_COLUMN_NAME` AS `foreign_column_name`,
588
            `rc`.`UPDATE_RULE` AS `on_update`,
589
            `rc`.`DELETE_RULE` AS `on_delete`,
590
            `kcu`.`ORDINAL_POSITION` AS `position`
591
        FROM `information_schema`.`KEY_COLUMN_USAGE` AS `kcu`
592
        JOIN `information_schema`.`REFERENTIAL_CONSTRAINTS` AS `rc` ON
593
            `rc`.`CONSTRAINT_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND
594
            `rc`.`TABLE_NAME` = `kcu`.`TABLE_NAME` AND
595
            `rc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME`
596
        JOIN `information_schema`.`TABLE_CONSTRAINTS` AS `tc` ON
597
            `tc`.`TABLE_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND
598
            `tc`.`TABLE_NAME` = `kcu`.`TABLE_NAME` AND
599
            `tc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME` AND
600
            `tc`.`CONSTRAINT_TYPE` = 'FOREIGN KEY'
601
        WHERE
602
            `kcu`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND
603
            `kcu`.`CONSTRAINT_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND
604
            `kcu`.`TABLE_NAME` = :tableName
605
        UNION
606
        SELECT
607
            `kcu`.`CONSTRAINT_NAME` AS `name`,
608
            `kcu`.`COLUMN_NAME` AS `column_name`,
609
            `tc`.`CONSTRAINT_TYPE` AS `type`,
610
        NULL AS `foreign_table_schema`,
611
        NULL AS `foreign_table_name`,
612
        NULL AS `foreign_column_name`,
613
        NULL AS `on_update`,
614
        NULL AS `on_delete`,
615
            `kcu`.`ORDINAL_POSITION` AS `position`
616
        FROM `information_schema`.`KEY_COLUMN_USAGE` AS `kcu`
617 71
        JOIN `information_schema`.`TABLE_CONSTRAINTS` AS `tc` ON
618
            `tc`.`TABLE_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND
619 71
            `tc`.`TABLE_NAME` = `kcu`.`TABLE_NAME` AND
620
            `tc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME` AND
621 71
            `tc`.`CONSTRAINT_TYPE` IN ('PRIMARY KEY', 'UNIQUE')
622 71
        WHERE
623 71
            `kcu`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND
624 71
            `kcu`.`TABLE_NAME` = :tableName
625
        ORDER BY `position` ASC
626
        SQL;
627 71
628 71
        $resolvedName = $this->resolveTableName($tableName);
629
630 71
        $constraints = $this->db->createCommand($sql, [
631 71
            ':schemaName' => $resolvedName->getSchemaName(),
632 71
            ':tableName' => $resolvedName->getName(),
633 71
        ])->queryAll();
634 71
635
        /** @var array<array-key, array> $constraints */
636
        $constraints = $this->normalizeRowKeyCase($constraints, true);
637
        $constraints = ArrayHelper::index($constraints, null, ['type', 'name']);
638
639
        $result = [
640 71
            self::PRIMARY_KEY => null,
641
            self::FOREIGN_KEYS => [],
642
            self::UNIQUES => [],
643
        ];
644
645 66
        /**
646
         * @var string $type
647 66
         * @var array $names
648 47
         */
649 47
        foreach ($constraints as $type => $names) {
650 47
            /**
651 58
             * @psalm-var object|string|null $name
652 16
             * @psalm-var ConstraintArray $constraint
653 16
             */
654 16
            foreach ($names as $name => $constraint) {
655 16
                switch ($type) {
656 16
                    case 'PRIMARY KEY':
657 16
                        $result[self::PRIMARY_KEY] = (new Constraint())
658 16
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'));
659 16
                        break;
660 16
                    case 'FOREIGN KEY':
661 48
                        $result[self::FOREIGN_KEYS][] = (new ForeignKeyConstraint())
662 48
                            ->foreignSchemaName($constraint[0]['foreign_table_schema'])
663 48
                            ->foreignTableName($constraint[0]['foreign_table_name'])
664 48
                            ->foreignColumnNames(ArrayHelper::getColumn($constraint, 'foreign_column_name'))
665 48
                            ->onDelete($constraint[0]['on_delete'])
666
                            ->onUpdate($constraint[0]['on_update'])
667
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
668
                            ->name($name);
669
                        break;
670 71
                    case 'UNIQUE':
671 71
                        $result[self::UNIQUES][] = (new Constraint())
672
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
673
                            ->name($name);
674 71
                        break;
675
                }
676
            }
677
        }
678
679
        foreach ($result as $type => $data) {
680
            $this->setTableMetadata($tableName, $type, $data);
681
        }
682
683
        return $result[$returnType];
684
    }
685
686 15
    /**
687
     * Loads all default value constraints for the given table.
688 15
     *
689
     * @param string $tableName table name.
690
     *
691
     * @throws NotSupportedException
692
     *
693
     * @return array default value constraints for the given table.
694
     */
695
    protected function loadTableDefaultValues(string $tableName): array
696
    {
697
        throw new NotSupportedException(__METHOD__ . ' is not supported by MySQL.');
698
    }
699
700
    /**
701
     * Loads all foreign keys for the given table.
702 9
     *
703
     * @param string $tableName table name.
704 9
     *
705
     * @throws Exception
706 9
     * @throws InvalidConfigException
707
     * @throws Throwable
708
     *
709
     * @return array foreign keys for the given table.
710
     */
711
    protected function loadTableForeignKeys(string $tableName): array
712
    {
713
        $tableForeignKeys = $this->loadTableConstraints($tableName, self::FOREIGN_KEYS);
714
715
        return is_array($tableForeignKeys) ? $tableForeignKeys : [];
716
    }
717
718
    /**
719
     * Loads all indexes for the given table.
720 38
     *
721
     * @param string $tableName table name.
722 38
     *
723
     * @throws Exception
724
     * @throws InvalidConfigException
725
     * @throws Throwable
726
     *
727
     * @return IndexConstraint[] indexes for the given table.
728
     */
729
    protected function loadTableIndexes(string $tableName): array
730
    {
731
        $sql = <<<SQL
732
        SELECT
733
            `s`.`INDEX_NAME` AS `name`,
734 38
            `s`.`COLUMN_NAME` AS `column_name`,
735
            `s`.`NON_UNIQUE` ^ 1 AS `index_is_unique`,
736 38
            `s`.`INDEX_NAME` = 'PRIMARY' AS `index_is_primary`
737
        FROM `information_schema`.`STATISTICS` AS `s`
738 38
        WHERE
739 38
            `s`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND
740 38
            `s`.`INDEX_SCHEMA` = `s`.`TABLE_SCHEMA` AND
741 38
            `s`.`TABLE_NAME` = :tableName
742
        ORDER BY `s`.`SEQ_IN_INDEX` ASC
743
        SQL;
744 38
745 38
        $resolvedName = $this->resolveTableName($tableName);
746 38
747
        $indexes = $this->db->createCommand($sql, [
748
            ':schemaName' => $resolvedName->getSchemaName(),
749
            ':tableName' => $resolvedName->getName(),
750
        ])->queryAll();
751
752 38
        /** @var array[] $indexes */
753 38
        $indexes = $this->normalizeRowKeyCase($indexes, true);
754
        $indexes = ArrayHelper::index($indexes, null, 'name');
755 38
        $result = [];
756 38
757 38
        /**
758 38
         * @psalm-var object|string|null $name
759
         * @psalm-var array[] $index
760 38
         */
761
        foreach ($indexes as $name => $index) {
762
            $ic = new IndexConstraint();
763 38
764
            $ic->primary((bool) $index[0]['index_is_primary']);
765
            $ic->unique((bool) $index[0]['index_is_unique']);
766
            $ic->name($name !== 'PRIMARY' ? $name : null);
767
            $ic->columnNames(ArrayHelper::getColumn($index, 'column_name'));
768
769
            $result[] = $ic;
770
        }
771
772
        return $result;
773
    }
774
775
    /**
776
     * Loads a primary key for the given table.
777 45
     *
778
     * @param string $tableName table name.
779 45
     *
780
     * @throws Exception
781 45
     * @throws InvalidConfigException
782
     * @throws Throwable
783
     *
784
     * @return Constraint|null primary key for the given table, `null` if the table has no primary key.*
785
     */
786
    protected function loadTablePrimaryKey(string $tableName): Constraint|null
787
    {
788
        $tablePrimaryKey = $this->loadTableConstraints($tableName, self::PRIMARY_KEY);
789
790
        return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
791
    }
792
793
    /**
794 147
     * Loads the metadata for the specified table.
795
     *
796 147
     * @param string $name table name.
797 147
     *
798 147
     * @throws Exception
799
     * @throws Throwable
800 147
     *
801 130
     * @return TableSchemaInterface|null DBMS-dependent table metadata, `null` if the table does not exist.
802
     */
803 130
    protected function loadTableSchema(string $name): TableSchemaInterface|null
804
    {
805
        $table = $this->resolveTableName($name);
806 30
        $this->resolveTableCreateSql($table);
807
        $this->findTableComment($table);
808
809
        if ($this->findColumns($table)) {
810
            $this->findConstraints($table);
811
812
            return $table;
813
        }
814
815
        return null;
816
    }
817
818
    /**
819
     * Loads all unique constraints for the given table.
820 17
     *
821
     * @param string $tableName table name.
822 17
     *
823
     * @throws Exception
824 17
     * @throws InvalidConfigException
825
     * @throws Throwable
826
     *
827
     * @return array unique constraints for the given table.
828
     */
829
    protected function loadTableUniques(string $tableName): array
830
    {
831
        $tableUniques = $this->loadTableConstraints($tableName, self::UNIQUES);
832
833
        return is_array($tableUniques) ? $tableUniques : [];
834 191
    }
835
836 191
    /**
837
     * Resolves the table name and schema name (if any).
838 191
     *
839 191
     * @param string $name the table name.
840 191
     *
841
     * {@see TableSchemaInterface}
842 191
     */
843 191
    protected function resolveTableName(string $name): TableSchemaInterface
844
    {
845 191
        $resolvedName = new TableSchema();
846 191
847 191
        $parts = array_reverse(
848 191
            $this->db->getQuoter()->getTableNameParts($name)
849
        );
850 191
851
        $resolvedName->name($parts[0] ?? '');
852
        $resolvedName->schemaName($parts[1] ?? $this->defaultSchema);
853
854
        $resolvedName->fullName(
855
            $resolvedName->getSchemaName() !== $this->defaultSchema ?
856
            implode('.', array_reverse($parts)) : $resolvedName->getName()
857
        );
858 147
859
        return $resolvedName;
860 147
    }
861 147
862
    /**
863
     * @throws Exception
864
     * @throws InvalidConfigException
865
     * @throws Throwable
866
     */
867
    protected function resolveTableCreateSql(TableSchemaInterface $table): void
868
    {
869
        $sql = $this->getCreateTableSql($table);
870
        $table->createSql($sql);
871 131
    }
872
873 131
    /**
874
     * Creates a column schema for the database.
875
     *
876
     * This method may be overridden by child classes to create a DBMS-specific column schema.
877
     *
878
     * @return ColumnSchema column schema instance.
879
     */
880
    private function createColumnSchema(): ColumnSchema
881
    {
882
        return new ColumnSchema();
883
    }
884
885
    private function getJsonColumns(TableSchemaInterface $table): array
886
    {
887
        $sql = $this->getCreateTableSql($table);
888
        $result = [];
889
890
        $regexp = '/json_valid\([\`"](.+)[\`"]\s*\)/mi';
891
892
        if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
893
            foreach ($matches as $match) {
894
                $result[] = $match[1];
895
            }
896
        }
897
898
        return $result;
899
    }
900
}
901