Passed
Branch master (f0583f)
by Wilmer
09:45 queued 05:54
created

Schema   F

Complexity

Total Complexity 71

Size/Duplication

Total Lines 781
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 12
Bugs 0 Features 1
Metric Value
eloc 333
c 12
b 0
f 1
dl 0
loc 781
ccs 239
cts 239
cp 1
rs 2.7199
wmc 71

23 Methods

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

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

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