Test Failed
Pull Request — master (#205)
by Alexander
07:13 queued 03:37
created

Schema::getJsonColumns()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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

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