Passed
Push — master ( 23465a...9abfe3 )
by Wilmer
03:30
created

Schema::findColumns()   B

Complexity

Conditions 10
Paths 29

Size

Total Lines 67
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 13.3855

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 10
eloc 33
c 2
b 0
f 0
nc 29
nop 1
dl 0
loc 67
ccs 23
cts 34
cp 0.6765
crap 13.3855
rs 7.6666

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

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