Passed
Pull Request — master (#180)
by Wilmer
03:53
created

Schema::findSchemaNames()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 0
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
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 145
    protected function findColumns(TableSchemaInterface $table): bool
198
    {
199 145
        $tableName = $table->getFullName() ?? '';
200 145
        $sql = 'SHOW FULL COLUMNS FROM ' . $this->db->getQuoter()->quoteTableName($tableName);
201
202
        try {
203 145
            $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 130
        foreach ($columns as $info) {
221 130
            $info = $this->normalizeRowKeyCase($info, false);
222
223 130
            $column = $this->loadColumnSchema($info);
224 130
            $table->columns($column->getName(), $column);
225
226 130
            if ($column->isPrimaryKey()) {
227 85
                $table->primaryKey($column->getName());
228 85
                if ($column->isAutoIncrement()) {
229 73
                    $table->sequenceName('');
230
                }
231
            }
232
        }
233
234 130
        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 130
    protected function findConstraints(TableSchemaInterface $table): void
243
    {
244 130
        $sql = <<<SQL
245
        SELECT
246
            `kcu`.`CONSTRAINT_NAME` AS `constraint_name`,
247
            `kcu`.`COLUMN_NAME` AS `column_name`,
248
            `kcu`.`REFERENCED_TABLE_NAME` AS `referenced_table_name`,
249
            `kcu`.`REFERENCED_COLUMN_NAME` AS `referenced_column_name`
250
        FROM `information_schema`.`REFERENTIAL_CONSTRAINTS` AS `rc`
251
        JOIN `information_schema`.`KEY_COLUMN_USAGE` AS `kcu` ON
252
            (
253
                `kcu`.`CONSTRAINT_CATALOG` = `rc`.`CONSTRAINT_CATALOG` OR
254
                (
255
                    `kcu`.`CONSTRAINT_CATALOG` IS NULL AND
256
                    `rc`.`CONSTRAINT_CATALOG` IS NULL
257
                )
258
            ) AND
259
            `kcu`.`CONSTRAINT_SCHEMA` = `rc`.`CONSTRAINT_SCHEMA` AND
260
            `kcu`.`CONSTRAINT_NAME` = `rc`.`CONSTRAINT_NAME` AND
261
            `kcu`.`TABLE_SCHEMA` = `rc`.`CONSTRAINT_SCHEMA` AND
262
            `kcu`.`TABLE_NAME` = `rc`.`TABLE_NAME`
263
        WHERE `rc`.`CONSTRAINT_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND `rc`.`TABLE_NAME` = :tableName
264 130
        SQL;
265
266 130
        $constraints = [];
267 130
        $rows = $this->db->createCommand($sql, [
268 130
            ':schemaName' => $table->getSchemaName(),
269 130
            ':tableName' => $table->getName(),
270 130
        ])->queryAll();
271
272
        /**  @psalm-var RowConstraint $row */
273 130
        foreach ($rows as $row) {
274 42
            $constraints[$row['constraint_name']]['referenced_table_name'] = $row['referenced_table_name'];
275 42
            $constraints[$row['constraint_name']]['columns'][$row['column_name']] = $row['referenced_column_name'];
276
        }
277
278 130
        $table->foreignKeys([]);
279
280
        /**
281
         * @var array{referenced_table_name: string, columns: array} $constraint
282
         */
283 130
        foreach ($constraints as $name => $constraint) {
284 42
            $table->foreignKey(
285 42
                $name,
286 42
                array_merge(
287 42
                    [$constraint['referenced_table_name']],
288 42
                    $constraint['columns']
289 42
                ),
290 42
            );
291
        }
292
    }
293
294
    /**
295
     * Returns all schema names in the database, including the default one but not system schemas.
296
     *
297
     * This method should be overridden by child classes in order to support this feature because the default
298
     * implementation simply throws an exception.
299
     *
300
     * @throws Exception
301
     * @throws InvalidConfigException
302
     * @throws Throwable
303
     *
304
     * @return array All schema names in the database, except system schemas.
305
     */
306 1
    protected function findSchemaNames(): array
307
    {
308 1
        $sql = <<<SQL
309
        SELECT schema_name FROM information_schema.schemata WHERE schema_name NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')
310 1
        SQL;
311
312 1
        return $this->db->createCommand($sql)->queryColumn();
313
    }
314
315 145
    protected function findTableComment(TableSchemaInterface $tableSchema): void
316
    {
317 145
        $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 145
        SQL;
324
325 145
        $comment = $this->db->createCommand($sql, [
326 145
            ':schemaName' => $tableSchema->getSchemaName(),
327 145
            ':tableName' => $tableSchema->getName(),
328 145
        ])->queryScalar();
329
330 145
        $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 1
    protected function findViewNames(string $schema = ''): array
359
    {
360 1
        $sql = match ($schema) {
361 1
            '' => <<<SQL
362
            SELECT table_name as view FROM information_schema.tables WHERE table_type LIKE 'VIEW' AND table_schema != 'sys'
363 1
            SQL,
364 1
            default => <<<SQL
365 1
            SELECT table_name as view FROM information_schema.tables WHERE table_type LIKE 'VIEW' AND table_schema = '$schema'
366 1
            SQL,
367 1
        };
368
369
        /** @psalm-var string[][] $views */
370 1
        $views = $this->db->createCommand($sql)->queryAll();
371
372 1
        foreach ($views as $key => $view) {
373 1
            $views[$key] = $view['view'];
374
        }
375
376 1
        return $views;
377
    }
378
379
    /**
380
     * Returns the cache key for the specified table name.
381
     *
382
     * @param string $name the table name.
383
     *
384
     * @return array the cache key.
385
     */
386 212
    protected function getCacheKey(string $name): array
387
    {
388 212
        return array_merge([self::class], $this->db->getCacheKey(), [$this->getRawTableName($name)]);
389
    }
390
391
    /**
392
     * Returns the cache tag name.
393
     *
394
     * This allows {@see refresh()} to invalidate all cached table schemas.
395
     *
396
     * @return string the cache tag name.
397
     */
398 213
    protected function getCacheTag(): string
399
    {
400 213
        return md5(serialize(array_merge([self::class], $this->db->getCacheKey())));
401
    }
402
403
    /**
404
     * Gets the CREATE TABLE sql string.
405
     *
406
     * @param TableSchemaInterface $table the table metadata.
407
     *
408
     * @throws Exception
409
     * @throws InvalidConfigException
410
     * @throws Throwable
411
     *
412
     * @return string $sql the result of 'SHOW CREATE TABLE'.
413
     */
414 145
    protected function getCreateTableSql(TableSchemaInterface $table): string
415
    {
416 145
        $tableName = $table->getFullName() ?? '';
417
418
        try {
419
            /** @var array<array-key, string> $row */
420 145
            $row = $this->db->createCommand(
421 145
                'SHOW CREATE TABLE ' . $this->db->getQuoter()->quoteTableName($tableName)
422 145
            )->queryOne();
423
424 130
            if (isset($row['Create Table'])) {
425 128
                $sql = $row['Create Table'];
426
            } else {
427 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

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