Passed
Pull Request — master (#180)
by Alexander
07:12 queued 03:27
created

Schema::findColumns()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 38
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 7

Importance

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

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