Passed
Push — master ( 05c121...11a82d )
by Def
09:00 queued 05:15
created

Schema::loadColumnSchema()   F

Complexity

Conditions 27
Paths 500

Size

Total Lines 106
Code Lines 66

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 62
CRAP Score 27.0029

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 27
eloc 66
c 1
b 0
f 0
nc 500
nop 1
dl 0
loc 106
ccs 62
cts 63
cp 0.9841
crap 27.0029
rs 0.6944

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

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