Passed
Pull Request — master (#295)
by
unknown
03:47
created

Schema::resolveTableName()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

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

455
                $row = array_values(/** @scrutinizer ignore-type */ $row);
Loading history...
456 144
                $sql = $row[1];
457
            }
458 35
        } catch (Exception) {
459 35
            $sql = '';
460
        }
461
462 161
        return $sql;
463
    }
464
465
    /**
466
     * Loads the column information into a {@see ColumnSchemaInterface} object.
467
     *
468
     * @param array $info The column information.
469
     *
470
     * @throws JsonException
471
     *
472
     * @return ColumnSchemaInterface The column schema object.
473
     *
474
     * @psalm-param ColumnInfoArray $info The column information.
475
     */
476 146
    protected function loadColumnSchema(array $info): ColumnSchemaInterface
477
    {
478 146
        $dbType = $info['type'];
479
480 146
        $column = $this->createColumnSchema($info['field']);
481
482
        /** @psalm-var ColumnInfoArray $info */
483 146
        $column->allowNull($info['null'] === 'YES');
484 146
        $column->primaryKey(str_contains($info['key'], 'PRI'));
485 146
        $column->autoIncrement(stripos($info['extra'], 'auto_increment') !== false);
486 146
        $column->comment($info['comment']);
487 146
        $column->dbType($dbType);
488 146
        $column->unsigned(stripos($dbType, 'unsigned') !== false);
489 146
        $column->type(self::TYPE_STRING);
490
491 146
        if (preg_match('/^(\w+)(?:\(([^)]+)\))?/', $dbType, $matches)) {
492 146
            $type = strtolower($matches[1]);
493
494 146
            if (isset($this->typeMap[$type])) {
495 141
                $column->type($this->typeMap[$type]);
496
            }
497
498 146
            if (!empty($matches[2])) {
499 110
                if ($type === 'enum') {
500 26
                    preg_match_all("/'[^']*'/", $matches[2], $values);
501
502 26
                    foreach ($values[0] as $i => $value) {
503 26
                        $values[$i] = trim($value, "'");
504
                    }
505
506 26
                    $column->enumValues($values);
507
                } else {
508 110
                    $values = explode(',', $matches[2]);
509 110
                    $column->precision((int) $values[0]);
510 110
                    $column->size((int) $values[0]);
511
512 110
                    if (isset($values[1])) {
513 41
                        $column->scale((int) $values[1]);
514
                    }
515
516 110
                    if ($type === 'bit') {
517 29
                        if ($column->getSize() === 1) {
518 29
                            $column->type(self::TYPE_BOOLEAN);
519 27
                        } elseif ($column->getSize() > 32) {
520 4
                            $column->type(self::TYPE_BIGINT);
521 27
                        } elseif ($column->getSize() === 32) {
522 4
                            $column->type(self::TYPE_INTEGER);
523
                        }
524
                    }
525
                }
526
            }
527
        }
528
529
        // Chapter 2: crutches for MariaDB {@see https://github.com/yiisoft/yii2/issues/19747}
530 146
        $extra = $info['extra'];
531
        if (
532 146
            empty($extra)
533 146
            && !empty($info['extra_default_value'])
534 146
            && !str_starts_with($info['extra_default_value'], '\'')
535 146
            && in_array($column->getType(), [
536 146
                self::TYPE_CHAR, self::TYPE_STRING, self::TYPE_TEXT,
537 146
                self::TYPE_DATETIME, self::TYPE_TIMESTAMP, self::TYPE_TIME, self::TYPE_DATE,
538 146
            ], true)
539
        ) {
540 1
            $extra = 'DEFAULT_GENERATED';
541
        }
542
543 146
        $column->extra($extra);
544 146
        $column->phpType($this->getColumnPhpType($column));
545 146
        $column->defaultValue($this->normalizeDefaultValue($info['default'], $column));
546
547 146
        if (str_starts_with($extra, 'DEFAULT_GENERATED')) {
548 33
            $column->extra(trim(strtoupper(substr($extra, 18))));
549
        }
550
551 146
        return $column;
552
    }
553
554
    /**
555
     * Converts column's default value according to {@see ColumnSchema::phpType} after retrieval from the database.
556
     *
557
     * @param string|null $defaultValue The default value retrieved from the database.
558
     * @param ColumnSchemaInterface $column The column schema object.
559
     *
560
     * @return mixed The normalized default value.
561
     */
562 146
    private function normalizeDefaultValue(?string $defaultValue, ColumnSchemaInterface $column): mixed
563
    {
564 146
        return match (true) {
565 146
            $defaultValue === null
566 146
                => null,
567 146
            $column->isPrimaryKey()
568 146
                => $column->phpTypecast($defaultValue),
569 146
            in_array($column->getType(), [
570 146
                self::TYPE_TIMESTAMP,
571 146
                self::TYPE_DATETIME,
572 146
                self::TYPE_DATE,
573 146
                self::TYPE_TIME,
574 146
            ], true)
575 146
                && preg_match('/^current_timestamp(?:\((\d*)\))?$/i', $defaultValue, $matches) === 1
0 ignored issues
show
Bug introduced by
It seems like $defaultValue can also be of type null; however, parameter $subject of preg_match() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

575
                && preg_match('/^current_timestamp(?:\((\d*)\))?$/i', /** @scrutinizer ignore-type */ $defaultValue, $matches) === 1
Loading history...
576 146
                    => new Expression('CURRENT_TIMESTAMP' . (!empty($matches[1]) ? '(' . $matches[1] . ')' : '')),
577 146
            !empty($column->getExtra())
578 146
                && !empty($defaultValue)
579 146
                    => new Expression($defaultValue),
0 ignored issues
show
Bug introduced by
It seems like $defaultValue can also be of type null; however, parameter $expression of Yiisoft\Db\Expression\Expression::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

579
                    => new Expression(/** @scrutinizer ignore-type */ $defaultValue),
Loading history...
580 146
            str_starts_with(strtolower((string) $column->getDbType()), 'bit')
581 146
                => $column->phpTypecast(bindec(trim($defaultValue, "b'"))),
0 ignored issues
show
Bug introduced by
It seems like $defaultValue can also be of type null; however, parameter $string of trim() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

581
                => $column->phpTypecast(bindec(trim(/** @scrutinizer ignore-type */ $defaultValue, "b'"))),
Loading history...
582 146
            default
583 146
            => $column->phpTypecast($defaultValue),
584 146
        };
585
    }
586
587
    /**
588
     * Loads all check constraints for the given table.
589
     *
590
     * @param string $tableName The table name.
591
     *
592
     * @throws NotSupportedException
593
     *
594
     * @return array Check constraints for the given table.
595
     */
596 16
    protected function loadTableChecks(string $tableName): array
597
    {
598 16
        throw new NotSupportedException(__METHOD__ . ' is not supported by MySQL.');
599
    }
600
601
    /**
602
     * Loads multiple types of constraints and returns the specified ones.
603
     *
604
     * @param string $tableName table name.
605
     * @param string $returnType return type:
606
     * - primaryKey
607
     * - foreignKeys
608
     * - uniques
609
     *
610
     * @throws Exception
611
     * @throws InvalidConfigException
612
     * @throws Throwable
613
     *
614
     * @psalm-return Constraint[]|ForeignKeyConstraint[]|Constraint|null
615
     */
616 71
    private function loadTableConstraints(string $tableName, string $returnType): array|Constraint|null
617
    {
618 71
        $sql = <<<SQL
619
        SELECT
620
            `kcu`.`CONSTRAINT_NAME` AS `name`,
621
            `kcu`.`COLUMN_NAME` AS `column_name`,
622
            `tc`.`CONSTRAINT_TYPE` AS `type`,
623
        CASE
624
            WHEN :schemaName IS NULL AND `kcu`.`REFERENCED_TABLE_SCHEMA` = DATABASE() THEN NULL
625
        ELSE `kcu`.`REFERENCED_TABLE_SCHEMA`
626
        END AS `foreign_table_schema`,
627
            `kcu`.`REFERENCED_TABLE_NAME` AS `foreign_table_name`,
628
            `kcu`.`REFERENCED_COLUMN_NAME` AS `foreign_column_name`,
629
            `rc`.`UPDATE_RULE` AS `on_update`,
630
            `rc`.`DELETE_RULE` AS `on_delete`,
631
            `kcu`.`ORDINAL_POSITION` AS `position`
632
        FROM `information_schema`.`KEY_COLUMN_USAGE` AS `kcu`
633
        JOIN `information_schema`.`REFERENTIAL_CONSTRAINTS` AS `rc` ON
634
            `rc`.`CONSTRAINT_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND
635
            `rc`.`TABLE_NAME` = `kcu`.`TABLE_NAME` AND
636
            `rc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME`
637
        JOIN `information_schema`.`TABLE_CONSTRAINTS` AS `tc` ON
638
            `tc`.`TABLE_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND
639
            `tc`.`TABLE_NAME` = `kcu`.`TABLE_NAME` AND
640
            `tc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME` AND
641
            `tc`.`CONSTRAINT_TYPE` = 'FOREIGN KEY'
642
        WHERE
643
            `kcu`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND
644
            `kcu`.`CONSTRAINT_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND
645
            `kcu`.`TABLE_NAME` = :tableName
646
        UNION
647
        SELECT
648
            `kcu`.`CONSTRAINT_NAME` AS `name`,
649
            `kcu`.`COLUMN_NAME` AS `column_name`,
650
            `tc`.`CONSTRAINT_TYPE` AS `type`,
651
        NULL AS `foreign_table_schema`,
652
        NULL AS `foreign_table_name`,
653
        NULL AS `foreign_column_name`,
654
        NULL AS `on_update`,
655
        NULL AS `on_delete`,
656
            `kcu`.`ORDINAL_POSITION` AS `position`
657
        FROM `information_schema`.`KEY_COLUMN_USAGE` AS `kcu`
658
        JOIN `information_schema`.`TABLE_CONSTRAINTS` AS `tc` ON
659
            `tc`.`TABLE_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND
660
            `tc`.`TABLE_NAME` = `kcu`.`TABLE_NAME` AND
661
            `tc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME` AND
662
            `tc`.`CONSTRAINT_TYPE` IN ('PRIMARY KEY', 'UNIQUE')
663
        WHERE
664
            `kcu`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND
665
            `kcu`.`TABLE_NAME` = :tableName
666
        ORDER BY `position` ASC
667 71
        SQL;
668
669 71
        $resolvedName = $this->resolveTableName($tableName);
670 71
        $constraints = $this->db->createCommand($sql, [
671 71
            ':schemaName' => $resolvedName->getSchemaName(),
672 71
            ':tableName' => $resolvedName->getName(),
673 71
        ])->queryAll();
674
675
        /** @psalm-var array[][] $constraints */
676 71
        $constraints = $this->normalizeRowKeyCase($constraints, true);
677 71
        $constraints = DbArrayHelper::index($constraints, null, ['type', 'name']);
678
679 71
        $result = [
680 71
            self::PRIMARY_KEY => null,
681 71
            self::FOREIGN_KEYS => [],
682 71
            self::UNIQUES => [],
683 71
        ];
684
685
        /**
686
         * @psalm-var string $type
687
         * @psalm-var array $names
688
         */
689 71
        foreach ($constraints as $type => $names) {
690
            /**
691
             * @psalm-var object|string|null $name
692
             * @psalm-var ConstraintArray $constraint
693
             */
694 66
            foreach ($names as $name => $constraint) {
695
                switch ($type) {
696 66
                    case 'PRIMARY KEY':
697 47
                        $result[self::PRIMARY_KEY] = (new Constraint())
698 47
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'));
699 47
                        break;
700 58
                    case 'FOREIGN KEY':
701 16
                        $result[self::FOREIGN_KEYS][] = (new ForeignKeyConstraint())
702 16
                            ->foreignSchemaName($constraint[0]['foreign_table_schema'])
703 16
                            ->foreignTableName($constraint[0]['foreign_table_name'])
704 16
                            ->foreignColumnNames(DbArrayHelper::getColumn($constraint, 'foreign_column_name'))
705 16
                            ->onDelete($constraint[0]['on_delete'])
706 16
                            ->onUpdate($constraint[0]['on_update'])
707 16
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'))
708 16
                            ->name($name);
709 16
                        break;
710 48
                    case 'UNIQUE':
711 48
                        $result[self::UNIQUES][] = (new Constraint())
712 48
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'))
713 48
                            ->name($name);
714 48
                        break;
715
                }
716
            }
717
        }
718
719 71
        foreach ($result as $type => $data) {
720 71
            $this->setTableMetadata($tableName, $type, $data);
721
        }
722
723 71
        return $result[$returnType];
724
    }
725
726
    /**
727
     * Loads all default value constraints for the given table.
728
     *
729
     * @param string $tableName The table name.
730
     *
731
     * @throws NotSupportedException
732
     *
733
     * @return array Default value constraints for the given table.
734
     */
735 15
    protected function loadTableDefaultValues(string $tableName): array
736
    {
737 15
        throw new NotSupportedException(__METHOD__ . ' is not supported by MySQL.');
738
    }
739
740
    /**
741
     * Loads all foreign keys for the given table.
742
     *
743
     * @param string $tableName The table name.
744
     *
745
     * @throws Exception
746
     * @throws InvalidConfigException
747
     * @throws Throwable
748
     *
749
     * @return array Foreign keys for the given table.
750
     */
751 9
    protected function loadTableForeignKeys(string $tableName): array
752
    {
753 9
        $tableForeignKeys = $this->loadTableConstraints($tableName, self::FOREIGN_KEYS);
754 9
        return is_array($tableForeignKeys) ? $tableForeignKeys : [];
755
    }
756
757
    /**
758
     * Loads all indexes for the given table.
759
     *
760
     * @param string $tableName The table name.
761
     *
762
     * @throws Exception
763
     * @throws InvalidConfigException
764
     * @throws Throwable
765
     *
766
     * @return IndexConstraint[] Indexes for the given table.
767
     */
768 38
    protected function loadTableIndexes(string $tableName): array
769
    {
770 38
        $sql = <<<SQL
771
        SELECT
772
            `s`.`INDEX_NAME` AS `name`,
773
            `s`.`COLUMN_NAME` AS `column_name`,
774
            `s`.`NON_UNIQUE` ^ 1 AS `index_is_unique`,
775
            `s`.`INDEX_NAME` = 'PRIMARY' AS `index_is_primary`
776
        FROM `information_schema`.`STATISTICS` AS `s`
777
        WHERE
778
            `s`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND
779
            `s`.`INDEX_SCHEMA` = `s`.`TABLE_SCHEMA` AND
780
            `s`.`TABLE_NAME` = :tableName
781
        ORDER BY `s`.`SEQ_IN_INDEX` ASC
782 38
        SQL;
783
784 38
        $resolvedName = $this->resolveTableName($tableName);
785 38
        $indexes = $this->db->createCommand($sql, [
786 38
            ':schemaName' => $resolvedName->getSchemaName(),
787 38
            ':tableName' => $resolvedName->getName(),
788 38
        ])->queryAll();
789
790
        /** @psalm-var array[] $indexes */
791 38
        $indexes = $this->normalizeRowKeyCase($indexes, true);
792 38
        $indexes = DbArrayHelper::index($indexes, null, ['name']);
793 38
        $result = [];
794
795
        /**
796
         * @psalm-var object|string|null $name
797
         * @psalm-var array[] $index
798
         */
799 38
        foreach ($indexes as $name => $index) {
800 38
            $ic = new IndexConstraint();
801
802 38
            $ic->primary((bool) $index[0]['index_is_primary']);
803 38
            $ic->unique((bool) $index[0]['index_is_unique']);
804 38
            $ic->name($name !== 'PRIMARY' ? $name : null);
805 38
            $ic->columnNames(DbArrayHelper::getColumn($index, 'column_name'));
806
807 38
            $result[] = $ic;
808
        }
809
810 38
        return $result;
811
    }
812
813
    /**
814
     * Loads a primary key for the given table.
815
     *
816
     * @param string $tableName The table name.
817
     *
818
     * @throws Exception
819
     * @throws InvalidConfigException
820
     * @throws Throwable
821
     *
822
     * @return Constraint|null Primary key for the given table, `null` if the table has no primary key.*
823
     */
824 45
    protected function loadTablePrimaryKey(string $tableName): Constraint|null
825
    {
826 45
        $tablePrimaryKey = $this->loadTableConstraints($tableName, self::PRIMARY_KEY);
827 45
        return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
828
    }
829
830
    /**
831
     * Loads the metadata for the specified table.
832
     *
833
     * @param string $name The table name.
834
     *
835
     * @throws Exception
836
     * @throws Throwable
837
     *
838
     * @return TableSchemaInterface|null DBMS-dependent table metadata, `null` if the table doesn't exist.
839
     */
840 161
    protected function loadTableSchema(string $name): TableSchemaInterface|null
841
    {
842 161
        $table = $this->resolveTableName($name);
843 161
        $this->resolveTableCreateSql($table);
844 161
        $this->findTableComment($table);
845
846 161
        if ($this->findColumns($table)) {
847 144
            $this->findConstraints($table);
848
849 144
            return $table;
850
        }
851
852 35
        return null;
853
    }
854
855
    /**
856
     * Loads all unique constraints for the given table.
857
     *
858
     * @param string $tableName The table name.
859
     *
860
     * @throws Exception
861
     * @throws InvalidConfigException
862
     * @throws Throwable
863
     *
864
     * @return array Unique constraints for the given table.
865
     */
866 17
    protected function loadTableUniques(string $tableName): array
867
    {
868 17
        $tableUniques = $this->loadTableConstraints($tableName, self::UNIQUES);
869 17
        return is_array($tableUniques) ? $tableUniques : [];
870
    }
871
872
    /**
873
     * Resolves the table name and schema name (if any).
874
     *
875
     * @param string $name The table name.
876
     *
877
     * @see TableSchemaInterface
878
     */
879 205
    protected function resolveTableName(string $name): TableSchemaInterface
880
    {
881 205
        $resolvedName = new TableSchema();
882
883 205
        $parts = array_reverse($this->db->getQuoter()->getTableNameParts($name));
884 205
        $resolvedName->name($parts[0] ?? '');
885 205
        $resolvedName->schemaName($parts[1] ?? $this->defaultSchema);
886 205
        $resolvedName->fullName(
887 205
            $resolvedName->getSchemaName() !== $this->defaultSchema ?
888 205
            implode('.', array_reverse($parts)) : $resolvedName->getName()
889 205
        );
890
891 205
        return $resolvedName;
892
    }
893
894
    /**
895
     * @throws Exception
896
     * @throws InvalidConfigException
897
     * @throws Throwable
898
     */
899 161
    protected function resolveTableCreateSql(TableSchemaInterface $table): void
900
    {
901 161
        $sql = $this->getCreateTableSql($table);
902 161
        $table->createSql($sql);
903
    }
904
905
    /**
906
     * Creates a column schema for the database.
907
     *
908
     * This method may be overridden by child classes to create a DBMS-specific column schema.
909
     *
910
     * @param string $name Name of the column.
911
     */
912 146
    private function createColumnSchema(string $name): ColumnSchema
913
    {
914 146
        return new ColumnSchema($name);
915
    }
916
917
    /**
918
     * @throws Exception
919
     * @throws InvalidConfigException
920
     * @throws Throwable
921
     */
922 144
    private function getJsonColumns(TableSchemaInterface $table): array
923
    {
924 144
        $sql = $this->getCreateTableSql($table);
925 144
        $result = [];
926 144
        $regexp = '/json_valid\([\`"](.+)[\`"]\s*\)/mi';
927
928 144
        if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
929
            foreach ($matches as $match) {
930
                $result[] = $match[1];
931
            }
932
        }
933
934 144
        return $result;
935
    }
936
}
937