Passed
Pull Request — master (#247)
by Alexander
04:04
created

Schema::loadTableConstraints()   B

Complexity

Conditions 7
Paths 12

Size

Total Lines 109
Code Lines 86

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 39
CRAP Score 7

Importance

Changes 4
Bugs 1 Features 0
Metric Value
cc 7
eloc 86
nc 12
nop 2
dl 0
loc 109
ccs 39
cts 39
cp 1
crap 7
rs 7.3721
c 4
b 1
f 0

How to fix   Long Method   

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

432
                $row = array_values(/** @scrutinizer ignore-type */ $row);
Loading history...
433 140
                $sql = $row[1];
434
            }
435 33
        } catch (Exception) {
436 33
            $sql = '';
437
        }
438
439 157
        return $sql;
440
    }
441
442
    /**
443
     * Loads the column information into a {@see ColumnSchemaInterface} object.
444
     *
445
     * @param array $info column information.
446
     *
447
     * @throws JsonException
448
     *
449
     * @return ColumnSchemaInterface the column schema object.
450
     */
451 142
    protected function loadColumnSchema(array $info): ColumnSchemaInterface
452
    {
453 142
        $column = $this->createColumnSchema();
454
455
        /** @psalm-var ColumnInfoArray $info */
456 142
        $column->name($info['field']);
457 142
        $column->allowNull($info['null'] === 'YES');
458 142
        $column->primaryKey(str_contains($info['key'], 'PRI'));
459 142
        $column->autoIncrement(stripos($info['extra'], 'auto_increment') !== false);
460 142
        $column->comment($info['comment']);
461 142
        $column->dbType($info['type']);
462 142
        $column->unsigned(stripos($column->getDbType(), 'unsigned') !== false);
463 142
        $column->type(self::TYPE_STRING);
464
465 142
        $extra = $info['extra'];
466
467 142
        if (str_starts_with($extra, 'DEFAULT_GENERATED')) {
468 29
            $extra = strtoupper(substr($extra, 18));
469
        }
470 142
        $column->extra(trim($extra));
471
472 142
        if (preg_match('/^(\w+)(?:\(([^)]+)\))?/', $column->getDbType(), $matches)) {
473 142
            $type = strtolower($matches[1]);
474
475 142
            if (isset($this->typeMap[$type])) {
476 142
                $column->type($this->typeMap[$type]);
477
            }
478
479 142
            if (!empty($matches[2])) {
480 102
                if ($type === 'enum') {
481 26
                    preg_match_all("/'[^']*'/", $matches[2], $values);
482
483 26
                    foreach ($values[0] as $i => $value) {
484 26
                        $values[$i] = trim($value, "'");
485
                    }
486
487 26
                    $column->enumValues($values);
488
                } else {
489 102
                    $values = explode(',', $matches[2]);
490 102
                    $column->precision((int) $values[0]);
491 102
                    $column->size((int) $values[0]);
492
493 102
                    if (isset($values[1])) {
494 41
                        $column->scale((int) $values[1]);
495
                    }
496
497 102
                    if ($column->getSize() === 1 && $type === 'bit') {
498 29
                        $column->type(self::TYPE_BOOLEAN);
499 102
                    } elseif ($type === 'bit') {
500 27
                        if ($column->getSize() > 32) {
501 4
                            $column->type(self::TYPE_BIGINT);
502 27
                        } elseif ($column->getSize() === 32) {
503 4
                            $column->type(self::TYPE_INTEGER);
504
                        }
505
                    }
506
                }
507
            }
508
        }
509
510 142
        $column->phpType($this->getColumnPhpType($column));
511
512 142
        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 140
                in_array($column->getType(), [self::TYPE_TIMESTAMP, self::TYPE_DATETIME, self::TYPE_DATE, self::TYPE_TIME], true)
521 140
                && preg_match('/^current_timestamp(?:\((\d*)\))?$/i', (string) $info['default'], $matches)
522
            ) {
523 30
                $column->defaultValue(new Expression('CURRENT_TIMESTAMP' . (!empty($matches[1])
524 30
                    ? '(' . $matches[1] . ')' : '')));
525 137
            } elseif (isset($type) && $type === 'bit' && $column->getType() !== self::TYPE_BOOLEAN) {
526 27
                $column->defaultValue(bindec(trim((string) $info['default'], 'b\'')));
527
            } else {
528 140
                $column->defaultValue($column->phpTypecast($info['default']));
529
            }
530 91
        } elseif ($info['default'] !== null) {
531 3
            $column->defaultValue($column->phpTypecast($info['default']));
532
        }
533
534 142
        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 71
    private function loadTableConstraints(string $tableName, string $returnType): array|Constraint|null
567
    {
568 71
        $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 71
        SQL;
618
619 71
        $resolvedName = $this->resolveTableName($tableName);
620
621 71
        $constraints = $this->db->createCommand($sql, [
622 71
            ':schemaName' => $resolvedName->getSchemaName(),
623 71
            ':tableName' => $resolvedName->getName(),
624 71
        ])->queryAll();
625
626
        /** @var array<array-key, array> $constraints */
627 71
        $constraints = $this->normalizeRowKeyCase($constraints, true);
628 71
        $constraints = ArrayHelper::index($constraints, null, ['type', 'name']);
629
630 71
        $result = [
631 71
            self::PRIMARY_KEY => null,
632 71
            self::FOREIGN_KEYS => [],
633 71
            self::UNIQUES => [],
634 71
        ];
635
636
        /**
637
         * @var string $type
638
         * @var array $names
639
         */
640 71
        foreach ($constraints as $type => $names) {
641
            /**
642
             * @psalm-var object|string|null $name
643
             * @psalm-var ConstraintArray $constraint
644
             */
645 66
            foreach ($names as $name => $constraint) {
646
                switch ($type) {
647 66
                    case 'PRIMARY KEY':
648 47
                        $result[self::PRIMARY_KEY] = (new Constraint())
649 47
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'));
650 47
                        break;
651 58
                    case 'FOREIGN KEY':
652 16
                        $result[self::FOREIGN_KEYS][] = (new ForeignKeyConstraint())
653 16
                            ->foreignSchemaName($constraint[0]['foreign_table_schema'])
654 16
                            ->foreignTableName($constraint[0]['foreign_table_name'])
655 16
                            ->foreignColumnNames(ArrayHelper::getColumn($constraint, 'foreign_column_name'))
656 16
                            ->onDelete($constraint[0]['on_delete'])
657 16
                            ->onUpdate($constraint[0]['on_update'])
658 16
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
659 16
                            ->name($name);
660 16
                        break;
661 48
                    case 'UNIQUE':
662 48
                        $result[self::UNIQUES][] = (new Constraint())
663 48
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
664 48
                            ->name($name);
665 48
                        break;
666
                }
667
            }
668
        }
669
670 71
        foreach ($result as $type => $data) {
671 71
            $this->setTableMetadata($tableName, $type, $data);
672
        }
673
674 71
        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 38
    protected function loadTableIndexes(string $tableName): array
721
    {
722 38
        $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 38
        SQL;
735
736 38
        $resolvedName = $this->resolveTableName($tableName);
737
738 38
        $indexes = $this->db->createCommand($sql, [
739 38
            ':schemaName' => $resolvedName->getSchemaName(),
740 38
            ':tableName' => $resolvedName->getName(),
741 38
        ])->queryAll();
742
743
        /** @var array[] $indexes */
744 38
        $indexes = $this->normalizeRowKeyCase($indexes, true);
745 38
        $indexes = ArrayHelper::index($indexes, null, ['name']);
746 38
        $result = [];
747
748
        /**
749
         * @psalm-var object|string|null $name
750
         * @psalm-var array[] $index
751
         */
752 38
        foreach ($indexes as $name => $index) {
753 38
            $ic = new IndexConstraint();
754
755 38
            $ic->primary((bool) $index[0]['index_is_primary']);
756 38
            $ic->unique((bool) $index[0]['index_is_unique']);
757 38
            $ic->name($name !== 'PRIMARY' ? $name : null);
758 38
            $ic->columnNames(ArrayHelper::getColumn($index, 'column_name'));
759
760 38
            $result[] = $ic;
761
        }
762
763 38
        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 45
    protected function loadTablePrimaryKey(string $tableName): Constraint|null
778
    {
779 45
        $tablePrimaryKey = $this->loadTableConstraints($tableName, self::PRIMARY_KEY);
780
781 45
        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 157
    protected function loadTableSchema(string $name): TableSchemaInterface|null
795
    {
796 157
        $table = $this->resolveTableName($name);
797 157
        $this->resolveTableCreateSql($table);
798 157
        $this->findTableComment($table);
799
800 157
        if ($this->findColumns($table)) {
801 140
            $this->findConstraints($table);
802
803 140
            return $table;
804
        }
805
806 33
        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 201
    protected function resolveTableName(string $name): TableSchemaInterface
835
    {
836 201
        $resolvedName = new TableSchema();
837
838 201
        $parts = array_reverse(
839 201
            $this->db->getQuoter()->getTableNameParts($name)
840 201
        );
841
842 201
        $resolvedName->name($parts[0] ?? '');
843 201
        $resolvedName->schemaName($parts[1] ?? $this->defaultSchema);
844
845 201
        $resolvedName->fullName(
846 201
            $resolvedName->getSchemaName() !== $this->defaultSchema ?
847 201
            implode('.', array_reverse($parts)) : $resolvedName->getName()
848 201
        );
849
850 201
        return $resolvedName;
851
    }
852
853
    /**
854
     * @throws Exception
855
     * @throws InvalidConfigException
856
     * @throws Throwable
857
     */
858 157
    protected function resolveTableCreateSql(TableSchemaInterface $table): void
859
    {
860 157
        $sql = $this->getCreateTableSql($table);
861 157
        $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 142
    private function createColumnSchema(): ColumnSchema
872
    {
873 142
        return new ColumnSchema();
874
    }
875
876 140
    private function getJsonColumns(TableSchemaInterface $table): array
877
    {
878 140
        $sql = $this->getCreateTableSql($table);
879 140
        $result = [];
880
881 140
        $regexp = '/json_valid\([\`"](.+)[\`"]\s*\)/mi';
882
883 140
        if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
884
            foreach ($matches as $match) {
885
                $result[] = $match[1];
886
            }
887
        }
888
889 140
        return $result;
890
    }
891
}
892