Passed
Pull Request — master (#180)
by Wilmer
19:13 queued 15:29
created

Schema::loadTableChecks()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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

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