Test Failed
Pull Request — master (#303)
by Sergei
21:43 queued 18:16
created

Schema::loadTableChecks()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Mysql;
6
7
use Throwable;
8
use Yiisoft\Db\Constraint\Constraint;
9
use Yiisoft\Db\Constraint\ForeignKeyConstraint;
10
use Yiisoft\Db\Constraint\IndexConstraint;
11
use Yiisoft\Db\Driver\Pdo\AbstractPdoSchema;
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\DbArrayHelper;
17
use Yiisoft\Db\Schema\Builder\ColumnInterface;
18
use Yiisoft\Db\Schema\Column\ColumnSchemaInterface;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Schema\Column\ColumnSchemaInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

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

436
                $row = array_values(/** @scrutinizer ignore-type */ $row);
Loading history...
437
                $sql = $row[1];
438
            }
439
        } catch (Exception) {
440
            $sql = '';
441 162
        }
442
443 162
        return $sql;
444
    }
445
446
    /**
447 162
     * Loads the column information into a {@see ColumnSchemaInterface} object.
448 162
     *
449 162
     * @param array $info The column information.
450
     *
451 145
     * @return ColumnSchemaInterface The column schema object.
452 143
     *
453
     * @psalm-param ColumnInfoArray $info The column information.
454 4
     */
455 145
    private function loadColumnSchema(array $info): ColumnSchemaInterface
456
    {
457 36
        $dbType = $info['type'];
458 36
        $type = $this->getColumnType($dbType, $info);
459
        $isUnsigned = stripos($dbType, 'unsigned') !== false;
460
        /** @psalm-var ColumnInfoArray $info */
461 162
        $column = $this->createColumnSchema($type, $info['field'], unsigned: $isUnsigned);
0 ignored issues
show
Bug introduced by
The method createColumnSchema() does not exist on Yiisoft\Db\Mysql\Schema. Did you maybe mean createColumn()? ( Ignorable by Annotation )

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

461
        /** @scrutinizer ignore-call */ 
462
        $column = $this->createColumnSchema($type, $info['field'], unsigned: $isUnsigned);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
462
        $column->enumValues($info['enum_values'] ?? null);
463
        $column->size($info['size'] ?? null);
464
        $column->precision($info['precision'] ?? null);
465
        $column->scale($info['scale'] ?? null);
466
        $column->allowNull($info['null'] === 'YES');
467
        $column->primaryKey(str_contains($info['key'], 'PRI'));
468
        $column->autoIncrement(stripos($info['extra'], 'auto_increment') !== false);
469
        $column->comment($info['comment']);
470
        $column->dbType($dbType);
471
472
        // Chapter 2: crutches for MariaDB {@see https://github.com/yiisoft/yii2/issues/19747}
473
        $extra = $info['extra'];
474
        if (
475 147
            empty($extra)
476
            && !empty($info['extra_default_value'])
477 147
            && !str_starts_with($info['extra_default_value'], '\'')
478
            && in_array($type, [
479 147
                self::TYPE_CHAR, self::TYPE_STRING, self::TYPE_TEXT,
480
                self::TYPE_DATETIME, self::TYPE_TIMESTAMP, self::TYPE_TIME, self::TYPE_DATE,
481
            ], true)
482 147
        ) {
483 147
            $extra = 'DEFAULT_GENERATED';
484 147
        }
485 147
486 147
        $column->extra($extra);
487 147
        $column->phpType($this->getColumnPhpType($type));
0 ignored issues
show
Bug introduced by
$type of type string is incompatible with the type Yiisoft\Db\Schema\ColumnSchemaInterface expected by parameter $column of Yiisoft\Db\Schema\Abstra...ema::getColumnPhpType(). ( Ignorable by Annotation )

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

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