Passed
Pull Request — master (#76)
by Wilmer
01:36
created

Schema::isOldMysql()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 9
ccs 2
cts 2
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Mysql;
6
7
use JsonException;
8
use PDO;
9
use PDOException;
10
use Throwable;
11
use Yiisoft\Arrays\ArrayHelper;
12
use Yiisoft\Db\Constraint\Constraint;
13
use Yiisoft\Db\Constraint\ConstraintFinderInterface;
14
use Yiisoft\Db\Constraint\ConstraintFinderTrait;
15
use Yiisoft\Db\Constraint\ForeignKeyConstraint;
16
use Yiisoft\Db\Constraint\IndexConstraint;
17
use Yiisoft\Db\Exception\Exception;
18
use Yiisoft\Db\Exception\InvalidConfigException;
19
use Yiisoft\Db\Exception\NotSupportedException;
20
use Yiisoft\Db\Expression\Expression;
21
use Yiisoft\Db\Schema\Schema as AbstractSchema;
22
23
use function array_change_key_case;
24
use function array_map;
25
use function array_merge;
26
use function array_values;
27
use function bindec;
28
use function explode;
29
use function preg_match;
30
use function preg_match_all;
31
use function str_replace;
32
use function stripos;
33
use function strpos;
34
use function strtolower;
35
use function trim;
36
37
/**
38
 * @psalm-type ColumnArray = array{
39
 *   table_schema: string,
40
 *   table_name: string,
41
 *   column_name: string,
42
 *   data_type: string,
43
 *   type_type: string|null,
44
 *   character_maximum_length: int,
45
 *   column_comment: string|null,
46
 *   modifier: int,
47
 *   is_nullable: bool,
48
 *   column_default: mixed,
49
 *   is_autoinc: bool,
50
 *   sequence_name: string|null,
51
 *   enum_values: array<array-key, float|int|string>|string|null,
52
 *   numeric_precision: int|null,
53
 *   numeric_scale: int|null,
54
 *   size: string|null,
55
 *   is_pkey: bool|null,
56
 *   dimension: int
57
 * }
58
 *
59
 * @psalm-type ColumnInfoArray = array{
60
 *   field: string,
61
 *   type: string,
62
 *   collation: string|null,
63
 *   null: string,
64
 *   key: string,
65
 *   default: string|null,
66
 *   extra: string,
67
 *   privileges: string,
68
 *   comment: string
69
 * }
70
 *
71
 * @psalm-type RowConstraint = array{
72
 *   constraint_name: string,
73
 *   column_name: string,
74
 *   referenced_table_name: string,
75
 *   referenced_column_name: string
76
 * }
77
 *
78
 * @psalm-type ConstraintArray = array<
79
 *   array-key,
80
 *   array {
81
 *     name: string,
82
 *     column_name: string,
83
 *     type: string,
84
 *     foreign_table_schema: string|null,
85
 *     foreign_table_name: string|null,
86
 *     foreign_column_name: string|null,
87
 *     on_update: string,
88
 *     on_delete: string,
89
 *     check_expr: string
90
 *   }
91
 * >
92
 */
93
final class Schema extends AbstractSchema implements ConstraintFinderInterface
94
{
95
    use ConstraintFinderTrait;
96 58
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 58
    private array $typeMap = [
99
        'tinyint' => self::TYPE_TINYINT,
100 58
        'bit' => self::TYPE_INTEGER,
101
        'smallint' => self::TYPE_SMALLINT,
102 58
        'mediumint' => self::TYPE_INTEGER,
103
        'int' => self::TYPE_INTEGER,
104
        'integer' => self::TYPE_INTEGER,
105
        'bigint' => self::TYPE_BIGINT,
106 58
        'float' => self::TYPE_FLOAT,
107 58
        'double' => self::TYPE_DOUBLE,
108
        'real' => self::TYPE_FLOAT,
109
        'decimal' => self::TYPE_DECIMAL,
110 58
        'numeric' => self::TYPE_DECIMAL,
111 58
        'tinytext' => self::TYPE_TEXT,
112
        'mediumtext' => self::TYPE_TEXT,
113 58
        '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 3
    /**
131
     * @var string|string[] character used to quote schema, table, etc. names. An array of 2 characters can be used in
132 3
     * case starting and ending characters are different.
133
     */
134 3
    protected $tableQuoteCharacter = '`';
135
136
    /**
137
     * @var string|string[] character used to quote column names. An array of 2 characters can be used in case starting
138 3
     * and ending characters are different.
139
     */
140
    protected $columnQuoteCharacter = '`';
141
142
    /**
143
     * Resolves the table name and schema name (if any).
144
     *
145
     * @param string $name the table name.
146
     *
147
     * @return TableSchema
148
     *
149
     * {@see TableSchema}
150 82
     */
151
    protected function resolveTableName(string $name): TableSchema
152 82
    {
153
        $resolvedName = new TableSchema();
154 82
155
        $parts = explode('.', str_replace('`', '', $name));
156 82
157 77
        if (isset($parts[1])) {
158
            $resolvedName->schemaName($parts[0]);
159 77
            $resolvedName->name($parts[1]);
160
        } else {
161
            $resolvedName->schemaName($this->defaultSchema);
162 13
            $resolvedName->name($name);
163
        }
164
165
        $resolvedName->fullName(($resolvedName->getSchemaName() !== $this->defaultSchema ?
166
            (string) $resolvedName->getSchemaName() . '.' : '') . (string) $resolvedName->getName());
167
168
        return $resolvedName;
169
    }
170
171
    /**
172
     * Returns all table names in the database.
173
     *
174
     * This method should be overridden by child classes in order to support this feature because the default
175
     * implementation simply throws an exception.
176 31
     *
177
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
178 31
     *
179
     * @throws Exception|InvalidConfigException|Throwable
180
     *
181
     * @return array all table names in the database. The names have NO schema name prefix.
182
     */
183
    protected function findTableNames(string $schema = ''): array
184
    {
185
        $sql = 'SHOW TABLES';
186
187
        if ($schema !== '') {
188
            $sql .= ' FROM ' . $this->quoteSimpleTableName($schema);
189
        }
190
191
        return $this->getDb()->createCommand($sql)->queryColumn();
192 4
    }
193
194 4
    /**
195
     * Loads the metadata for the specified table.
196
     *
197
     * @param string $name table name.
198
     *
199
     * @throws Exception|Throwable
200
     *
201
     * @return TableSchema|null DBMS-dependent table metadata, `null` if the table does not exist.
202
     */
203
    protected function loadTableSchema(string $name): ?TableSchema
204
    {
205
        $table = new TableSchema();
206
207
        $this->resolveTableNames($table, $name);
208 28
209
        if ($this->findColumns($table)) {
210 28
            $this->findConstraints($table);
211
212
            return $table;
213
        }
214
215
        return null;
216
    }
217
218
    /**
219
     * Loads a primary key for the given table.
220
     *
221 28
     * @param string $tableName table name.
222
     *
223 28
     * @throws Exception|InvalidConfigException|Throwable
224 28
     *
225 28
     * @return Constraint|null primary key for the given table, `null` if the table has no primary key.*
226 28
     */
227
    protected function loadTablePrimaryKey(string $tableName): ?Constraint
228 28
    {
229 28
        $tablePrimaryKey = $this->loadTableConstraints($tableName, 'primaryKey');
230 28
231
        return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
232 28
    }
233 28
234
    /**
235 28
     * Loads all foreign keys for the given table.
236 28
     *
237 28
     * @param string $tableName table name.
238 28
     *
239
     * @throws Exception|InvalidConfigException|Throwable
240 28
     *
241
     * @return array|ForeignKeyConstraint[] foreign keys for the given table.
242
     */
243 28
    protected function loadTableForeignKeys(string $tableName): array
244
    {
245
        $tableForeignKeys = $this->loadTableConstraints($tableName, 'foreignKeys');
246
247
        return is_array($tableForeignKeys) ? $tableForeignKeys : [];
248
    }
249
250
    /**
251
     * Loads all indexes for the given table.
252
     *
253
     * @param string $tableName table name.
254
     *
255
     * @throws Exception|InvalidConfigException|Throwable
256
     *
257 13
     * @return IndexConstraint[] indexes for the given table.
258
     */
259 13
    protected function loadTableIndexes(string $tableName): array
260
    {
261
        $sql = <<<'SQL'
262
SELECT
263
    `s`.`INDEX_NAME` AS `name`,
264
    `s`.`COLUMN_NAME` AS `column_name`,
265
    `s`.`NON_UNIQUE` ^ 1 AS `index_is_unique`,
266
    `s`.`INDEX_NAME` = 'PRIMARY' AS `index_is_primary`
267
FROM `information_schema`.`STATISTICS` AS `s`
268
WHERE `s`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND `s`.`INDEX_SCHEMA` = `s`.`TABLE_SCHEMA` AND `s`.`TABLE_NAME` = :tableName
269
ORDER BY `s`.`SEQ_IN_INDEX` ASC
270
SQL;
271 12
272
        $resolvedName = $this->resolveTableName($tableName);
273 12
274
        $indexes = $this->getDb()->createCommand($sql, [
275
            ':schemaName' => $resolvedName->getSchemaName(),
276
            ':tableName' => $resolvedName->getName(),
277
        ])->queryAll();
278
279
        /** @var array<array-key, array<array-key, mixed>> $indexes */
280
        $indexes = $this->normalizePdoRowKeyCase($indexes, true);
281
        $indexes = ArrayHelper::index($indexes, null, 'name');
282
        $result = [];
283
284
        /**
285 12
         * @psalm-var object|string|null $name
286
         * @psalm-var array<array-key, array<array-key, mixed>> $index
287 12
         */
288
        foreach ($indexes as $name => $index) {
289
            $ic = new IndexConstraint();
290
291
            $ic->primary((bool) $index[0]['index_is_primary']);
292
            $ic->unique((bool) $index[0]['index_is_unique']);
293
            $ic->name($name !== 'PRIMARY' ? $name : null);
294
            $ic->columnNames(ArrayHelper::getColumn($index, 'column_name'));
295 58
296
            $result[] = $ic;
297 58
        }
298
299
        return $result;
300
    }
301
302
    /**
303
     * Loads all unique constraints for the given table.
304
     *
305
     * @param string $tableName table name.
306 82
     *
307
     * @throws Exception|InvalidConfigException|Throwable
308 82
     *
309
     * @return array|Constraint[] unique constraints for the given table.
310 82
     */
311
    protected function loadTableUniques(string $tableName): array
312
    {
313
        $tableUniques = $this->loadTableConstraints($tableName, 'uniques');
314
315 82
        return is_array($tableUniques) ? $tableUniques : [];
316 82
    }
317
318 82
    /**
319
     * Loads all check constraints for the given table.
320
     *
321
     * @param string $tableName table name.
322
     *
323
     * @throws NotSupportedException
324
     *
325
     * @return array check constraints for the given table.
326
     */
327 78
    protected function loadTableChecks(string $tableName): array
0 ignored issues
show
Unused Code introduced by
The parameter $tableName is not used and could be removed. ( Ignorable by Annotation )

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

327
    protected function loadTableChecks(/** @scrutinizer ignore-unused */ string $tableName): array

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
328
    {
329 78
        throw new NotSupportedException('MySQL does not support check constraints.');
330
    }
331 78
332 78
    /**
333 78
     * Loads all default value constraints for the given table.
334 78
     *
335 78
     * @param string $tableName table name.
336 78
     *
337 78
     * @throws NotSupportedException
338 78
     *
339
     * @return array default value constraints for the given table.
340 78
     */
341 78
    protected function loadTableDefaultValues(string $tableName): array
0 ignored issues
show
Unused Code introduced by
The parameter $tableName is not used and could be removed. ( Ignorable by Annotation )

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

341
    protected function loadTableDefaultValues(/** @scrutinizer ignore-unused */ string $tableName): array

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
342
    {
343 78
        throw new NotSupportedException('MySQL does not support default value constraints.');
344 78
    }
345
346
    /**
347 78
     * Creates a query builder for the MySQL database.
348 77
     *
349 20
     * @return QueryBuilder query builder instance
350
     */
351 20
    public function createQueryBuilder(): QueryBuilder
352 20
    {
353
        return new QueryBuilder($this->getDb());
354
    }
355 20
356
    /**
357 77
     * Resolves the table name and schema name (if any).
358 77
     *
359 77
     * @param TableSchema $table the table metadata object.
360
     * @param string $name the table name.
361 77
     */
362 24
    protected function resolveTableNames(TableSchema $table, string $name): void
363
    {
364
        $parts = explode('.', str_replace('`', '', $name));
365 77
366 21
        if (isset($parts[1])) {
367 77
            $table->schemaName($parts[0]);
368 20
            $table->name($parts[1]);
369
            $table->fullName((string) $table->getSchemaName() . '.' . (string) $table->getName());
370 20
        } else {
371
            $table->name($parts[0]);
372
            $table->fullName($parts[0]);
373
        }
374
    }
375
376
    /**
377
     * Loads the column information into a {@see ColumnSchema} object.
378 78
     *
379
     * @var array $info column information.
380 78
     *
381
     * @throws JsonException
382
     *
383
     * @return ColumnSchema the column schema object.
384
     */
385
    protected function loadColumnSchema(array $info): ColumnSchema
386
    {
387
        $column = $this->createColumnSchema();
388 75
389 75
        /** @psalm-var ColumnInfoArray $info */
390
        $column->name($info['field']);
391 24
        $column->allowNull($info['null'] === 'YES');
392 24
        $column->primaryKey(strpos($info['key'], 'PRI') !== false);
393 72
        $column->autoIncrement(stripos($info['extra'], 'auto_increment') !== false);
394 20
        $column->comment($info['comment']);
395
        $column->dbType($info['type']);
396 72
        $column->unsigned(stripos($column->getDbType(), 'unsigned') !== false);
397
        $column->type(self::TYPE_STRING);
398
399
        if (preg_match('/^(\w+)(?:\(([^)]+)\))?/', $column->getDbType(), $matches)) {
400 78
            $type = strtolower($matches[1]);
401
402
            if (isset($this->typeMap[$type])) {
403
                $column->type($this->typeMap[$type]);
404
            }
405
406
            if (!empty($matches[2])) {
407
                if ($type === 'enum') {
408
                    preg_match_all("/'[^']*'/", $matches[2], $values);
409
410
                    foreach ($values[0] as $i => $value) {
411
                        $values[$i] = trim($value, "'");
412 82
                    }
413
414 82
                    $column->enumValues($values);
415
                } else {
416
                    $values = explode(',', $matches[2]);
417 82
                    $column->precision((int) $values[0]);
418 13
                    $column->size((int) $values[0]);
419 13
420
                    if (isset($values[1])) {
421 13
                        $column->scale((int) $values[1]);
422
                    }
423
424
                    if ($column->getSize() === 1 && $type === 'tinyint') {
425
                        $column->type('boolean');
426
                    } elseif ($type === 'bit') {
427 13
                        if ($column->getSize() > 32) {
428
                            $column->type('bigint');
429
                        } elseif ($column->getSize() === 32) {
430
                            $column->type('integer');
431
                        }
432
                    }
433 77
                }
434 77
            }
435 76
        }
436
437
        $column->phpType($this->getColumnPhpType($column));
438 77
439 77
        if (!$column->isPrimaryKey()) {
440
            /**
441 77
             * When displayed in the INFORMATION_SCHEMA.COLUMNS table, a default CURRENT TIMESTAMP is displayed
442 53
             * as CURRENT_TIMESTAMP up until MariaDB 10.2.2, and as current_timestamp() from MariaDB 10.2.3.
443 53
             *
444 51
             * See details here: https://mariadb.com/kb/en/library/now/#description
445
             */
446
            if (
447
                ($column->getType() === 'timestamp' || $column->getType() === 'datetime')
448
                && preg_match('/^current_timestamp(?:\((\d*)\))?$/i', (string) $info['default'], $matches)
449 77
            ) {
450
                $column->defaultValue(new Expression('CURRENT_TIMESTAMP' . (!empty($matches[1])
451
                    ? '(' . $matches[1] . ')' : '')));
452
            } elseif (isset($type) && $type === 'bit') {
453
                $column->defaultValue(bindec(trim((string) $info['default'], 'b\'')));
454
            } else {
455
                $column->defaultValue($column->phpTypecast($info['default']));
456
            }
457
        }
458
459
        return $column;
460
    }
461
462
    /**
463
     * Collects the metadata of table columns.
464
     *
465
     * @param TableSchema $table the table metadata.
466
     *
467
     * @throws Exception|Throwable if DB query fails.
468
     *
469
     * @return bool whether the table exists in the database.
470
     */
471
    protected function findColumns(TableSchema $table): bool
472
    {
473
        $tableName = $table->getFullName() ?? '';
474
475
        $sql = 'SHOW FULL COLUMNS FROM ' . $this->quoteTableName($tableName);
476
477
        try {
478
            $columns = $this->getDb()->createCommand($sql)->queryAll();
479
        } catch (Exception $e) {
480
            $previous = $e->getPrevious();
481
482
            if ($previous instanceof PDOException && strpos($previous->getMessage(), 'SQLSTATE[42S02') !== false) {
483
                /**
484
                 * table does not exist.
485
                 *
486 77
                 * https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_bad_table_error
487
                 */
488
                return false;
489 77
            }
490
491
            throw $e;
492
        }
493
494
        $slavePdo = $this->getDb()->getSlavePdo();
495
496
        /** @psalm-var ColumnInfoArray $info */
497
        foreach ($columns as $info) {
498
            if ($slavePdo !== null && $slavePdo->getAttribute(PDO::ATTR_CASE) !== PDO::CASE_LOWER) {
499
                $info = array_change_key_case($info, CASE_LOWER);
500
            }
501
502
            $column = $this->loadColumnSchema($info);
503
            $table->columns($column->getName(), $column);
504
505
            if ($column->isPrimaryKey()) {
506
                $table->primaryKey($column->getName());
507 77
                if ($column->isAutoIncrement()) {
508
                    $table->sequenceName('');
509 77
                }
510 77
            }
511
        }
512 77
513
        return true;
514 77
    }
515 24
516 24
    /**
517
     * Gets the CREATE TABLE sql string.
518
     *
519 77
     * @param TableSchema $table the table metadata.
520
     *
521 77
     * @throws Exception|InvalidConfigException|Throwable
522 24
     *
523 24
     * @return string $sql the result of 'SHOW CREATE TABLE'.
524 24
     */
525
    protected function getCreateTableSql(TableSchema $table): string
526
    {
527
        $tableName = $table->getFullName() ?? '';
528
529
        /** @var array<array-key, string> $row */
530
        $row = $this->getDb()->createCommand(
531
            'SHOW CREATE TABLE ' . $this->quoteTableName($tableName)
532
        )->queryOne();
533
534
        if (isset($row['Create Table'])) {
535
            $sql = $row['Create Table'];
536
        } else {
537
            $row = array_values($row);
0 ignored issues
show
Bug introduced by
$row of type false 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

537
            $row = array_values(/** @scrutinizer ignore-type */ $row);
Loading history...
538
            $sql = $row[1];
539
        }
540
541
        return $sql;
542
    }
543
544
    /**
545
     * Collects the foreign key column details for the given table.
546
     *
547
     * @param TableSchema $table the table metadata.
548
     *
549
     * @throws Exception|Throwable
550
     */
551
    protected function findConstraints(TableSchema $table): void
552
    {
553 77
        $sql = <<<'SQL'
554
SELECT
555
    `kcu`.`CONSTRAINT_NAME` AS `constraint_name`,
556
    `kcu`.`COLUMN_NAME` AS `column_name`,
557
    `kcu`.`REFERENCED_TABLE_NAME` AS `referenced_table_name`,
558
    `kcu`.`REFERENCED_COLUMN_NAME` AS `referenced_column_name`
559
FROM `information_schema`.`REFERENTIAL_CONSTRAINTS` AS `rc`
560
JOIN `information_schema`.`KEY_COLUMN_USAGE` AS `kcu` ON
561
    (
562
        `kcu`.`CONSTRAINT_CATALOG` = `rc`.`CONSTRAINT_CATALOG` OR
563
        (`kcu`.`CONSTRAINT_CATALOG` IS NULL AND `rc`.`CONSTRAINT_CATALOG` IS NULL)
564
    ) AND
565
    `kcu`.`CONSTRAINT_SCHEMA` = `rc`.`CONSTRAINT_SCHEMA` AND
566
    `kcu`.`CONSTRAINT_NAME` = `rc`.`CONSTRAINT_NAME`
567
WHERE `rc`.`CONSTRAINT_SCHEMA` = database() AND `kcu`.`TABLE_SCHEMA` = database()
568
AND `rc`.`TABLE_NAME` = :tableName AND `kcu`.`TABLE_NAME` = :tableName1
569
SQL;
570
571
        try {
572
            $rows = $this->getDb()->createCommand(
573
                $sql,
574
                [':tableName' => $table->getName(), ':tableName1' => $table->getName()]
575
            )->queryAll();
576
577
            $constraints = [];
578
579
            /**  @psalm-var RowConstraint $row */
580
            foreach ($rows as $row) {
581
                $constraints[$row['constraint_name']]['referenced_table_name'] = $row['referenced_table_name'];
582
                $constraints[$row['constraint_name']]['columns'][$row['column_name']] = $row['referenced_column_name'];
583
            }
584
585
            $table->foreignKeys([]);
586
587
            /**
588
             * @var string $name
589
             * @var array{referenced_table_name: string, columns: array} $constraint
590
             */
591
            foreach ($constraints as $name => $constraint) {
592
                $table->foreignKey($name, array_merge(
593
                    [$constraint['referenced_table_name']],
594
                    $constraint['columns']
595
                ));
596
            }
597
        } catch (Exception $e) {
598
            $previous = $e->getPrevious();
599
600
            if (!$previous instanceof PDOException || strpos($previous->getMessage(), 'SQLSTATE[42S02') === false) {
601
                throw $e;
602
            }
603
604 3
            // table does not exist, try to determine the foreign keys using the table creation sql
605
            $sql = $this->getCreateTableSql($table);
606 3
            $regexp = '/FOREIGN KEY\s+\(([^\)]+)\)\s+REFERENCES\s+([^\(^\s]+)\s*\(([^\)]+)\)/mi';
607
608
            if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
609
                foreach ($matches as $match) {
610
                    $fks = array_map('trim', explode(',', str_replace('`', '', $match[1])));
611
                    $pks = array_map('trim', explode(',', str_replace('`', '', $match[3])));
612
                    $constraint = [str_replace('`', '', $match[2])];
613
614
                    foreach ($fks as $k => $name) {
615
                        $constraint[$name] = $pks[$k];
616
                    }
617
618
                    $table->foreignKey(\md5(\serialize($constraint)), $constraint);
619
                }
620
                $table->foreignKeys(array_values($table->getForeignKeys()));
621
            }
622
        }
623
    }
624
625
    /**
626
     * Returns all unique indexes for the given table.
627
     *
628
     * Each array element is of the following structure:
629
     *
630
     * ```php
631
     * [
632
     *     'IndexName1' => ['col1' [, ...]],
633
     *     'IndexName2' => ['col2' [, ...]],
634
     * ]
635
     * ```
636
     *
637
     * @param TableSchema $table the table metadata.
638
     *
639
     * @throws Exception|InvalidConfigException|Throwable
640
     *
641 48
     * @return array all unique indexes for the given table.
642
     */
643 48
    public function findUniqueIndexes(TableSchema $table): array
644
    {
645
        $sql = $this->getCreateTableSql($table);
646
647
        $uniqueIndexes = [];
648
649
        $regexp = '/UNIQUE KEY\s+\`(.+)\`\s*\((\`.+\`)+\)/mi';
650
651
        if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
652
            foreach ($matches as $match) {
653
                $indexName = $match[1];
654
                $indexColumns = array_map('trim', explode('`,`', trim($match[2], '`')));
655
                $uniqueIndexes[$indexName] = $indexColumns;
656
            }
657
        }
658
659
        return $uniqueIndexes;
660
    }
661
662
    /**
663
     * Create a column schema builder instance giving the type and value precision.
664
     *
665
     * This method may be overridden by child classes to create a DBMS-specific column schema builder.
666
     *
667
     * @param string $type type of the column. See {@see ColumnSchemaBuilder::$type}.
668
     * @param array|int|string $length length or precision of the column. See {@see ColumnSchemaBuilder::$length}.
669
     *
670
     * @return ColumnSchemaBuilder column schema builder instance
671
     */
672
    public function createColumnSchemaBuilder(string $type, $length = null): ColumnSchemaBuilder
673
    {
674
        return new ColumnSchemaBuilder($type, $length, $this->getDb());
675
    }
676
677
    /**
678
     * Loads multiple types of constraints and returns the specified ones.
679
     *
680
     * @param string $tableName table name.
681
     * @param string $returnType return type:
682
     * - primaryKey
683
     * - foreignKeys
684
     * - uniques
685 48
     *
686
     * @throws Exception|InvalidConfigException|Throwable
687 48
     *
688
     * @return (Constraint|ForeignKeyConstraint)[]|Constraint|null constraints.
689
     *
690 48
     * @psalm-return Constraint|list<Constraint|ForeignKeyConstraint>|null
691 48
     */
692
    private function loadTableConstraints(string $tableName, string $returnType)
693 48
    {
694
        $sql = <<<'SQL'
695 48
SELECT
696 48
    `kcu`.`CONSTRAINT_NAME` AS `name`,
697
    `kcu`.`COLUMN_NAME` AS `column_name`,
698
    `tc`.`CONSTRAINT_TYPE` AS `type`,
699 48
    CASE
700
        WHEN :schemaName IS NULL AND `kcu`.`REFERENCED_TABLE_SCHEMA` = DATABASE() THEN NULL
701
        ELSE `kcu`.`REFERENCED_TABLE_SCHEMA`
702
    END AS `foreign_table_schema`,
703
    `kcu`.`REFERENCED_TABLE_NAME` AS `foreign_table_name`,
704 48
    `kcu`.`REFERENCED_COLUMN_NAME` AS `foreign_column_name`,
705 48
    `rc`.`UPDATE_RULE` AS `on_update`,
706
    `rc`.`DELETE_RULE` AS `on_delete`,
707 48
    `kcu`.`ORDINAL_POSITION` AS `position`
708 37
FROM
709 37
    `information_schema`.`KEY_COLUMN_USAGE` AS `kcu`,
710
    `information_schema`.`REFERENTIAL_CONSTRAINTS` AS `rc`,
711 37
    `information_schema`.`TABLE_CONSTRAINTS` AS `tc`
712
WHERE
713 37
    `kcu`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND `kcu`.`CONSTRAINT_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND `kcu`.`TABLE_NAME` = :tableName
714 46
    AND `rc`.`CONSTRAINT_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND `rc`.`TABLE_NAME` = :tableName AND `rc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME`
715 10
    AND `tc`.`TABLE_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND `tc`.`TABLE_NAME` = :tableName AND `tc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME` AND `tc`.`CONSTRAINT_TYPE` = 'FOREIGN KEY'
716 10
UNION
717 10
SELECT
718 10
    `kcu`.`CONSTRAINT_NAME` AS `name`,
719 10
    `kcu`.`COLUMN_NAME` AS `column_name`,
720 10
    `tc`.`CONSTRAINT_TYPE` AS `type`,
721 10
    NULL AS `foreign_table_schema`,
722 10
    NULL AS `foreign_table_name`,
723
    NULL AS `foreign_column_name`,
724 10
    NULL AS `on_update`,
725
    NULL AS `on_delete`,
726 10
    `kcu`.`ORDINAL_POSITION` AS `position`
727 37
FROM
728 37
    `information_schema`.`KEY_COLUMN_USAGE` AS `kcu`,
729 37
    `information_schema`.`TABLE_CONSTRAINTS` AS `tc`
730 37
WHERE
731
    `kcu`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND `kcu`.`TABLE_NAME` = :tableName
732 37
    AND `tc`.`TABLE_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND `tc`.`TABLE_NAME` = :tableName AND `tc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME` AND `tc`.`CONSTRAINT_TYPE` IN ('PRIMARY KEY', 'UNIQUE')
733
ORDER BY `position` ASC
734 37
SQL;
735
736
        $resolvedName = $this->resolveTableName($tableName);
737
738
        $constraints = $this->getDb()->createCommand(
739 48
            $sql,
740 48
            [
741
                ':schemaName' => $resolvedName->getSchemaName(),
742
                ':tableName' => $resolvedName->getName(),
743 48
            ]
744
        )->queryAll();
745
746
        /** @var array<array-key, array> $constraints */
747
        $constraints = $this->normalizePdoRowKeyCase($constraints, true);
748
        $constraints = ArrayHelper::index($constraints, null, ['type', 'name']);
749
750
        $result = [
751
            'primaryKey' => null,
752
            'foreignKeys' => [],
753 78
            'uniques' => [],
754
        ];
755 78
756
        /**
757
         * @var string $type
758
         * @var array $names
759
         */
760
        foreach ($constraints as $type => $names) {
761
            /**
762
             * @psalm-var object|string|null $name
763
             * @psalm-var ConstraintArray $constraint
764
             */
765
            foreach ($names as $name => $constraint) {
766
                switch ($type) {
767
                    case 'PRIMARY KEY':
768
                        $ct = (new Constraint())
769
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'));
770
771
                        $result['primaryKey'] = $ct;
772
773
                        break;
774
                    case 'FOREIGN KEY':
775
                        $fk = (new ForeignKeyConstraint())
776
                            ->foreignSchemaName($constraint[0]['foreign_table_schema'])
777
                            ->foreignTableName($constraint[0]['foreign_table_name'])
778
                            ->foreignColumnNames(ArrayHelper::getColumn($constraint, 'foreign_column_name'))
779
                            ->onDelete($constraint[0]['on_delete'])
780
                            ->onUpdate($constraint[0]['on_update'])
781
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
782
                            ->name($name);
783
784
                        $result['foreignKeys'][] = $fk;
785
786
                        break;
787
                    case 'UNIQUE':
788
                        $ct = (new Constraint())
789
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
790
                            ->name($name);
791
792
                        $result['uniques'][] = $ct;
793
794
                        break;
795
                }
796
            }
797
        }
798
799
        foreach ($result as $type => $data) {
800
            $this->setTableMetadata($tableName, $type, $data);
801
        }
802
803
        return $result[$returnType];
804
    }
805
806
    /**
807
     * Creates a column schema for the database.
808
     *
809
     * This method may be overridden by child classes to create a DBMS-specific column schema.
810
     *
811
     * @return ColumnSchema column schema instance.
812
     */
813
    private function createColumnSchema(): ColumnSchema
814
    {
815
        return new ColumnSchema();
816
    }
817
}
818