Test Failed
Pull Request — master (#143)
by Def
10:29 queued 08:10
created

Schema::findConstraints()   B

Complexity

Conditions 9
Paths 43

Size

Total Lines 75
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 9

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 52
c 2
b 0
f 0
dl 0
loc 75
ccs 24
cts 24
cp 1
rs 7.4917
cc 9
nc 43
nop 1
crap 9

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Mysql;
6
7
use JsonException;
8
use Throwable;
9
use Yiisoft\Arrays\ArrayHelper;
10
use Yiisoft\Db\Cache\SchemaCache;
11
use Yiisoft\Db\Connection\ConnectionInterface;
12
use Yiisoft\Db\Constraint\Constraint;
13
use Yiisoft\Db\Constraint\ForeignKeyConstraint;
14
use Yiisoft\Db\Constraint\IndexConstraint;
15
use Yiisoft\Db\Exception\Exception;
16
use Yiisoft\Db\Exception\InvalidConfigException;
17
use Yiisoft\Db\Exception\NotSupportedException;
18
use Yiisoft\Db\Expression\Expression;
19
use Yiisoft\Db\Schema\ColumnSchemaInterface;
20
use Yiisoft\Db\Schema\Schema as AbstractSchema;
21
use Yiisoft\Db\Schema\TableSchemaInterface;
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 md5;
30
use function preg_match;
31
use function preg_match_all;
32
use function serialize;
33
use function str_replace;
34
use function stripos;
35
use function strtolower;
36
use function trim;
37
38
/**
39
 * The class Schema is the class for retrieving metadata from a Mysql database (version 5.7 and above).
40
 *
41
 * @psalm-type ColumnArray = array{
42
 *   table_schema: string,
43
 *   table_name: string,
44
 *   column_name: string,
45
 *   data_type: string,
46
 *   type_type: string|null,
47
 *   character_maximum_length: int,
48
 *   column_comment: string|null,
49
 *   modifier: int,
50
 *   is_nullable: bool,
51
 *   column_default: mixed,
52
 *   is_autoinc: bool,
53
 *   sequence_name: string|null,
54
 *   enum_values: array<array-key, float|int|string>|string|null,
55
 *   numeric_precision: int|null,
56
 *   numeric_scale: int|null,
57
 *   size: string|null,
58
 *   is_pkey: bool|null,
59
 *   dimension: int
60
 * }
61
 *
62
 * @psalm-type ColumnInfoArray = array{
63
 *   field: string,
64
 *   type: string,
65
 *   collation: string|null,
66
 *   null: string,
67
 *   key: string,
68
 *   default: string|null,
69
 *   extra: string,
70
 *   privileges: string,
71
 *   comment: string
72
 * }
73
 *
74
 * @psalm-type RowConstraint = array{
75
 *   constraint_name: string,
76
 *   column_name: string,
77
 *   referenced_table_name: string,
78
 *   referenced_column_name: string
79
 * }
80
 *
81
 * @psalm-type ConstraintArray = array<
82
 *   array-key,
83
 *   array {
84
 *     name: string,
85
 *     column_name: string,
86
 *     type: string,
87
 *     foreign_table_schema: string|null,
88
 *     foreign_table_name: string|null,
89
 *     foreign_column_name: string|null,
90
 *     on_update: string,
91
 *     on_delete: string,
92
 *     check_expr: string
93
 *   }
94
 * >
95
 */
96
final class Schema extends AbstractSchema
97
{
98
    /** @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...
99
    private array $typeMap = [
100
        'tinyint' => self::TYPE_TINYINT,
101
        'bit' => self::TYPE_INTEGER,
102
        'smallint' => self::TYPE_SMALLINT,
103
        'mediumint' => self::TYPE_INTEGER,
104
        'int' => self::TYPE_INTEGER,
105
        'integer' => self::TYPE_INTEGER,
106
        'bigint' => self::TYPE_BIGINT,
107
        'float' => self::TYPE_FLOAT,
108
        'double' => self::TYPE_DOUBLE,
109
        'real' => self::TYPE_FLOAT,
110
        'decimal' => self::TYPE_DECIMAL,
111
        'numeric' => self::TYPE_DECIMAL,
112
        'tinytext' => self::TYPE_TEXT,
113
        'mediumtext' => self::TYPE_TEXT,
114
        'longtext' => self::TYPE_TEXT,
115
        'longblob' => self::TYPE_BINARY,
116
        'blob' => self::TYPE_BINARY,
117
        'text' => self::TYPE_TEXT,
118
        'varchar' => self::TYPE_STRING,
119
        'string' => self::TYPE_STRING,
120
        'char' => self::TYPE_CHAR,
121
        'datetime' => self::TYPE_DATETIME,
122
        'year' => self::TYPE_DATE,
123
        'date' => self::TYPE_DATE,
124
        'time' => self::TYPE_TIME,
125
        'timestamp' => self::TYPE_TIMESTAMP,
126
        'enum' => self::TYPE_STRING,
127
        'varbinary' => self::TYPE_BINARY,
128
        'json' => self::TYPE_JSON,
129
    ];
130
131 385
    /**
132
     * Create a column schema builder instance giving the type and value precision.
133 385
     *
134
     * This method may be overridden by child classes to create a DBMS-specific column schema builder.
135
     *
136
     * @param string $type type of the column. See {@see ColumnSchemaBuilder::$type}.
137
     * @param array|int|string|null $length length or precision of the column. See {@see ColumnSchemaBuilder::$length}.
138
     *
139
     * @return ColumnSchemaBuilder column schema builder instance
140
     *
141
     * @psalm-param string[]|int|string|null $length
142
     */
143
    public function createColumnSchemaBuilder(string $type, array|int|string $length = null): ColumnSchemaBuilder
144
    {
145
        return new ColumnSchemaBuilder($type, $length, $this->db->getQuoter());
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Mysql\Schema. Did you maybe forget to declare it?
Loading history...
146
    }
147
148 3
    /**
149
     * Returns all unique indexes for the given table.
150 3
     *
151
     * Each array element is of the following structure:
152
     *
153
     * ```php
154
     * [
155
     *     'IndexName1' => ['col1' [, ...]],
156
     *     'IndexName2' => ['col2' [, ...]],
157
     * ]
158
     * ```
159
     *
160
     * @param TableSchemaInterface $table the table metadata.
161
     *
162
     * @throws Exception|InvalidConfigException|Throwable
163
     *
164
     * @return array all unique indexes for the given table.
165
     */
166
    public function findUniqueIndexes(TableSchemaInterface $table): array
167
    {
168
        $sql = $this->getCreateTableSql($table);
169
170
        $uniqueIndexes = [];
171 1
172
        $regexp = '/UNIQUE KEY\s+`(.+)`\s*\((`.+`)+\)/mi';
173 1
174
        if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
175 1
            foreach ($matches as $match) {
176
                $indexName = $match[1];
177 1
                $indexColumns = array_map('trim', explode('`,`', trim($match[2], '`')));
178
                $uniqueIndexes[$indexName] = $indexColumns;
179 1
            }
180 1
        }
181 1
182 1
        return $uniqueIndexes;
183 1
    }
184
185
    /**
186
     * @inheritDoc
187 1
     */
188
    public function getLastInsertID(?string $sequenceName = null): string
189
    {
190
        return $this->db->getLastInsertID($sequenceName);
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Mysql\Schema. Did you maybe forget to declare it?
Loading history...
191
    }
192
193
    public function supportsSavepoint(): bool
194
    {
195
        return $this->db->isSavepointEnabled();
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Mysql\Schema. Did you maybe forget to declare it?
Loading history...
196
    }
197
198
    /**
199
     * Collects the metadata of table columns.
200
     *
201
     * @param TableSchemaInterface $table the table metadata.
202
     *
203
     * @throws Exception|Throwable if DB query fails.
204
     *
205
     * @return bool whether the table exists in the database.
206
     */
207
    protected function findColumns(TableSchemaInterface $table): bool
208 166
    {
209
        $tableName = $table->getFullName() ?? '';
210 166
        $sql = 'SHOW FULL COLUMNS FROM ' . $this->db->getQuoter()->quoteTableName($tableName);
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Mysql\Schema. Did you maybe forget to declare it?
Loading history...
211 23
212
        try {
213 23
            $columns = $this->db->createCommand($sql)->queryAll();
214
        } catch (Exception $e) {
215
            $previous = $e->getPrevious();
216 166
217
            if ($previous && str_contains($previous->getMessage(), 'SQLSTATE[42S02')) {
218
                /**
219 5
                 * table does not exist.
220
                 *
221 5
                 * https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_bad_table_error
222
                 */
223
                return false;
224
            }
225
226
            throw $e;
227
        }
228
229
        /** @psalm-var ColumnInfoArray $info */
230
        foreach ($columns as $info) {
231
            $info = $this->normalizeRowKeyCase($info, false);
232
233 102
            $column = $this->loadColumnSchema($info);
234
            $table->columns($column->getName(), $column);
235 102
236 102
            if ($column->isPrimaryKey()) {
237
                $table->primaryKey($column->getName());
238
                if ($column->isAutoIncrement()) {
239 102
                    $table->sequenceName('');
240 15
                }
241 15
            }
242
        }
243 15
244
        return true;
245
    }
246
247
    /**
248
     * Collects the foreign key column details for the given table.
249 15
     *
250
     * @param TableSchemaInterface $table the table metadata.
251
     *
252
     * @throws Exception|Throwable
253
     */
254
    protected function findConstraints(TableSchemaInterface $table): void
255
    {
256 96
        $sql = <<<SQL
257 96
        SELECT
258
            `kcu`.`CONSTRAINT_NAME` AS `constraint_name`,
259 96
            `kcu`.`COLUMN_NAME` AS `column_name`,
260 96
            `kcu`.`REFERENCED_TABLE_NAME` AS `referenced_table_name`,
261
            `kcu`.`REFERENCED_COLUMN_NAME` AS `referenced_column_name`
262 96
        FROM `information_schema`.`REFERENTIAL_CONSTRAINTS` AS `rc`
263 61
        JOIN `information_schema`.`KEY_COLUMN_USAGE` AS `kcu` ON
264 61
            (
265 59
                `kcu`.`CONSTRAINT_CATALOG` = `rc`.`CONSTRAINT_CATALOG` OR
266
                (
267
                    `kcu`.`CONSTRAINT_CATALOG` IS NULL AND
268
                    `rc`.`CONSTRAINT_CATALOG` IS NULL
269
                )
270 96
            ) AND
271
            `kcu`.`CONSTRAINT_SCHEMA` = `rc`.`CONSTRAINT_SCHEMA` AND
272
            `kcu`.`CONSTRAINT_NAME` = `rc`.`CONSTRAINT_NAME` AND
273
            `kcu`.`TABLE_SCHEMA` = `rc`.`CONSTRAINT_SCHEMA` AND
274
            `kcu`.`TABLE_NAME` = `rc`.`TABLE_NAME`
275
        WHERE
276
            `rc`.`CONSTRAINT_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND
277
            `rc`.`TABLE_NAME` = :tableName
278
        SQL;
279
280 96
        try {
281
            $rows = $this->db->createCommand($sql, [
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Mysql\Schema. Did you maybe forget to declare it?
Loading history...
282 96
                ':schemaName' => $table->getSchemaName(),
283
                ':tableName' => $table->getName(),
284
            ])->queryAll();
285
286
            $constraints = [];
287
288
            /**  @psalm-var RowConstraint $row */
289
            foreach ($rows as $row) {
290
                $constraints[$row['constraint_name']]['referenced_table_name'] = $row['referenced_table_name'];
291
                $constraints[$row['constraint_name']]['columns'][$row['column_name']] = $row['referenced_column_name'];
292
            }
293
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($name, array_merge(
301
                    [$constraint['referenced_table_name']],
302
                    $constraint['columns']
303
                ));
304
            }
305
        } catch (Exception $e) {
306
            $previous = $e->getPrevious();
307 96
308 96
            if ($previous === null || !str_contains($previous->getMessage(), 'SQLSTATE[42S02')) {
309 96
                throw $e;
310 96
            }
311
312 96
            // table does not exist, try to determine the foreign keys using the table creation sql
313
            $sql = $this->getCreateTableSql($table);
314
            $regexp = '/FOREIGN KEY\s+\(([^)]+)\)\s+REFERENCES\s+([^(^\s]+)\s*\(([^)]+)\)/mi';
315 96
316 23
            if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
317 23
                foreach ($matches as $match) {
318
                    $fks = array_map('trim', explode(',', str_replace('`', '', $match[1])));
319
                    $pks = array_map('trim', explode(',', str_replace('`', '', $match[3])));
320 96
                    $constraint = [str_replace('`', '', $match[2])];
321
322
                    foreach ($fks as $k => $name) {
323
                        $constraint[$name] = $pks[$k];
324
                    }
325 96
326 23
                    $table->foreignKey(md5(serialize($constraint)), $constraint);
327 23
                }
328 23
                $table->foreignKeys(array_values($table->getForeignKeys()));
329
            }
330
        }
331
    }
332
333
    /**
334
     * Returns all table names in the database.
335
     *
336
     * This method should be overridden by child classes in order to support this feature because the default
337
     * implementation simply throws an exception.
338
     *
339
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
340
     *
341
     * @throws Exception|InvalidConfigException|Throwable
342
     *
343
     * @return array All table names in the database. The names have NO schema name prefix.
344
     */
345
    protected function findTableNames(string $schema = ''): array
346
    {
347
        $sql = 'SHOW TABLES';
348
349
        if ($schema !== '') {
350
            $sql .= ' FROM ' . $this->db->getQuoter()->quoteSimpleTableName($schema);
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Mysql\Schema. Did you maybe forget to declare it?
Loading history...
351
        }
352
353
        return $this->db->createCommand($sql)->queryColumn();
354
    }
355
356
    /**
357
     * Returns the cache key for the specified table name.
358
     *
359
     * @param string $name the table name.
360
     *
361
     * @return array the cache key.
362
     */
363
    protected function getCacheKey(string $name): array
364
    {
365
        return array_merge([__CLASS__], $this->db->getCacheKey(), [$this->getRawTableName($name)]);
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Mysql\Schema. Did you maybe forget to declare it?
Loading history...
366
    }
367
368
    /**
369
     * Returns the cache tag name.
370
     *
371 7
     * This allows {@see refresh()} to invalidate all cached table schemas.
372
     *
373 7
     * @return string the cache tag name.
374
     */
375 7
    protected function getCacheTag(): string
376
    {
377
        return md5(serialize(array_merge([__CLASS__], $this->db->getCacheKey())));
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Mysql\Schema. Did you maybe forget to declare it?
Loading history...
378
    }
379 7
380
    /**
381
     * Gets the CREATE TABLE sql string.
382
     *
383
     * @param TableSchemaInterface $table the table metadata.
384
     *
385
     * @throws Exception|InvalidConfigException|Throwable
386
     *
387
     * @return string $sql the result of 'SHOW CREATE TABLE'.
388
     */
389 166
    protected function getCreateTableSql(TableSchemaInterface $table): string
390
    {
391 166
        $tableName = $table->getFullName() ?? '';
392
393
        try {
394
            /** @var array<array-key, string> $row */
395
            $row = $this->db->createCommand(
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Mysql\Schema. Did you maybe forget to declare it?
Loading history...
396
                'SHOW CREATE TABLE ' . $this->db->getQuoter()->quoteTableName($tableName)
397
            )->queryOne();
398
399
            if (isset($row['Create Table'])) {
400
                $sql = $row['Create Table'];
401 166
            } else {
402
                $row = array_values($row);
403 166
                $sql = $row[1];
404
            }
405
        } catch (Exception) {
406
            $sql = '';
407
        }
408
409
        return $sql;
410
    }
411
412
    /**
413
     * Loads the column information into a {@see ColumnSchemaInterface} object.
414
     *
415 102
     * @param array $info column information.
416
     *
417 102
     * @throws JsonException
418
     *
419
     * @return ColumnSchemaInterface the column schema object.
420
     */
421 102
    protected function loadColumnSchema(array $info): ColumnSchemaInterface
422 102
    {
423 102
        $column = $this->createColumnSchema();
424
425 96
        /** @psalm-var ColumnInfoArray $info */
426 94
        $column->name($info['field']);
427
        $column->allowNull($info['null'] === 'YES');
428 2
        $column->primaryKey(str_contains($info['key'], 'PRI'));
429 96
        $column->autoIncrement(stripos($info['extra'], 'auto_increment') !== false);
430
        $column->comment($info['comment']);
431 15
        $column->dbType($info['type']);
432 15
        $column->unsigned(stripos($column->getDbType(), 'unsigned') !== false);
433
        $column->type(self::TYPE_STRING);
434
435 102
        $extra = $info['extra'];
436
        if (str_starts_with($extra, 'DEFAULT_GENERATED')) {
437
            $extra = strtoupper(substr($extra, 18));
438
        }
439
        $column->extra(trim($extra));
440
441
        if (preg_match('/^(\w+)(?:\(([^)]+)\))?/', $column->getDbType(), $matches)) {
442
            $type = strtolower($matches[1]);
443
444
            if (isset($this->typeMap[$type])) {
445
                $column->type($this->typeMap[$type]);
446
            }
447 97
448
            if (!empty($matches[2])) {
449 97
                if ($type === 'enum') {
450
                    preg_match_all("/'[^']*'/", $matches[2], $values);
451
452 97
                    foreach ($values[0] as $i => $value) {
453 97
                        $values[$i] = trim($value, "'");
454 97
                    }
455 97
456 97
                    $column->enumValues($values);
457 97
                } else {
458 97
                    $values = explode(',', $matches[2]);
459 97
                    $column->precision((int) $values[0]);
460
                    $column->size((int) $values[0]);
461 97
462 97
                    if (isset($values[1])) {
463 23
                        $column->scale((int) $values[1]);
464
                    }
465 97
466
                    if ($column->getSize() === 1 && $type === 'tinyint') {
467 97
                        $column->type(self::TYPE_BOOLEAN);
468 97
                    } elseif ($type === 'bit') {
469
                        if ($column->getSize() > 32) {
470 97
                            $column->type(self::TYPE_BIGINT);
471 97
                        } elseif ($column->getSize() === 32) {
472
                            $column->type(self::TYPE_INTEGER);
473
                        }
474 97
                    }
475 89
                }
476 21
            }
477
        }
478 21
479 21
        $column->phpType($this->getColumnPhpType($column));
480
481
        if (!$column->isPrimaryKey()) {
482 21
            /**
483
             * When displayed in the INFORMATION_SCHEMA.COLUMNS table, a default CURRENT TIMESTAMP is displayed
484 89
             * as CURRENT_TIMESTAMP up until MariaDB 10.2.2, and as current_timestamp() from MariaDB 10.2.3.
485 89
             *
486 89
             * See details here: https://mariadb.com/kb/en/library/now/#description
487
             */
488 89
            if (
489 33
                ($column->getType() === 'timestamp' || $column->getType() === 'datetime')
490
                && preg_match('/^current_timestamp(?:\((\d*)\))?$/i', (string) $info['default'], $matches)
491
            ) {
492 89
                $column->defaultValue(new Expression('CURRENT_TIMESTAMP' . (!empty($matches[1])
493 22
                    ? '(' . $matches[1] . ')' : '')));
494 89
            } elseif (isset($type) && $type === 'bit') {
495 21
                $column->defaultValue(bindec(trim((string) $info['default'], 'b\'')));
496
            } else {
497 21
                $column->defaultValue($column->phpTypecast($info['default']));
498
            }
499
        } elseif ($info['default'] !== null) {
500
            $column->defaultValue($column->phpTypecast($info['default']));
501
        }
502
503
        return $column;
504
    }
505 97
506
    /**
507 97
     * Loads all check constraints for the given table.
508
     *
509
     * @param string $tableName table name.
510
     *
511
     * @throws NotSupportedException
512
     *
513
     * @return array check constraints for the given table.
514
     */
515 94
    protected function loadTableChecks(string $tableName): array
516 94
    {
517
        throw new NotSupportedException('MySQL does not support check constraints.');
518 24
    }
519 24
520 91
    /**
521 21
     * Loads multiple types of constraints and returns the specified ones.
522
     *
523 94
     * @param string $tableName table name.
524
     * @param string $returnType return type:
525 61
     * - primaryKey
526 1
     * - foreignKeys
527
     * - uniques
528
     *
529 97
     * @throws Exception|InvalidConfigException|Throwable
530
     *
531
     * @return array|Constraint|null (Constraint|ForeignKeyConstraint)[]|Constraint|null constraints.
532
     */
533
    private function loadTableConstraints(string $tableName, string $returnType): array|Constraint|null
534
    {
535
        $sql = <<<SQL
536
        SELECT
537
            `kcu`.`CONSTRAINT_NAME` AS `name`,
538
            `kcu`.`COLUMN_NAME` AS `column_name`,
539
            `tc`.`CONSTRAINT_TYPE` AS `type`,
540
        CASE
541 12
            WHEN :schemaName IS NULL AND `kcu`.`REFERENCED_TABLE_SCHEMA` = DATABASE() THEN NULL
542
        ELSE `kcu`.`REFERENCED_TABLE_SCHEMA`
543 12
        END AS `foreign_table_schema`,
544
            `kcu`.`REFERENCED_TABLE_NAME` AS `foreign_table_name`,
545
            `kcu`.`REFERENCED_COLUMN_NAME` AS `foreign_column_name`,
546
            `rc`.`UPDATE_RULE` AS `on_update`,
547
            `rc`.`DELETE_RULE` AS `on_delete`,
548
            `kcu`.`ORDINAL_POSITION` AS `position`
549
        FROM `information_schema`.`KEY_COLUMN_USAGE` AS `kcu`
550
        JOIN `information_schema`.`REFERENTIAL_CONSTRAINTS` AS `rc` ON
551
            `rc`.`CONSTRAINT_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND
552
            `rc`.`TABLE_NAME` = `kcu`.`TABLE_NAME` AND
553
            `rc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME`
554
        JOIN `information_schema`.`TABLE_CONSTRAINTS` AS `tc` ON
555
            `tc`.`TABLE_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND
556
            `tc`.`TABLE_NAME` = `kcu`.`TABLE_NAME` AND
557
            `tc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME` AND
558
            `tc`.`CONSTRAINT_TYPE` = 'FOREIGN KEY'
559 51
        WHERE
560
            `kcu`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND
561 51
            `kcu`.`CONSTRAINT_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND
562
            `kcu`.`TABLE_NAME` = :tableName
563
        UNION
564
        SELECT
565
            `kcu`.`CONSTRAINT_NAME` AS `name`,
566
            `kcu`.`COLUMN_NAME` AS `column_name`,
567
            `tc`.`CONSTRAINT_TYPE` AS `type`,
568
        NULL AS `foreign_table_schema`,
569
        NULL AS `foreign_table_name`,
570
        NULL AS `foreign_column_name`,
571
        NULL AS `on_update`,
572
        NULL AS `on_delete`,
573
            `kcu`.`ORDINAL_POSITION` AS `position`
574
        FROM `information_schema`.`KEY_COLUMN_USAGE` AS `kcu`
575
        JOIN `information_schema`.`TABLE_CONSTRAINTS` AS `tc` ON
576
            `tc`.`TABLE_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND
577
            `tc`.`TABLE_NAME` = `kcu`.`TABLE_NAME` AND
578
            `tc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME` AND
579
            `tc`.`CONSTRAINT_TYPE` IN ('PRIMARY KEY', 'UNIQUE')
580
        WHERE
581
            `kcu`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND
582
            `kcu`.`TABLE_NAME` = :tableName
583
        ORDER BY `position` ASC
584
        SQL;
585
586
        $resolvedName = $this->resolveTableName($tableName);
587
588
        $constraints = $this->db->createCommand($sql, [
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Mysql\Schema. Did you maybe forget to declare it?
Loading history...
589
            ':schemaName' => $resolvedName->getSchemaName(),
590
            ':tableName' => $resolvedName->getName(),
591
        ])->queryAll();
592
593
        /** @var array<array-key, array> $constraints */
594
        $constraints = $this->normalizeRowKeyCase($constraints, true);
595
        $constraints = ArrayHelper::index($constraints, null, ['type', 'name']);
596
597
        $result = [
598
            self::PRIMARY_KEY => null,
599
            self::FOREIGN_KEYS => [],
600
            self::UNIQUES => [],
601
        ];
602
603
        /**
604
         * @var string $type
605
         * @var array $names
606
         */
607
        foreach ($constraints as $type => $names) {
608
            /**
609
             * @psalm-var object|string|null $name
610
             * @psalm-var ConstraintArray $constraint
611
             */
612 51
            foreach ($names as $name => $constraint) {
613
                switch ($type) {
614 51
                    case 'PRIMARY KEY':
615 51
                        $result[self::PRIMARY_KEY] = (new Constraint())
616 51
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'));
617 51
                        break;
618
                    case 'FOREIGN KEY':
619
                        $result[self::FOREIGN_KEYS][] = (new ForeignKeyConstraint())
620 51
                            ->foreignSchemaName($constraint[0]['foreign_table_schema'])
621 51
                            ->foreignTableName($constraint[0]['foreign_table_name'])
622
                            ->foreignColumnNames(ArrayHelper::getColumn($constraint, 'foreign_column_name'))
623 51
                            ->onDelete($constraint[0]['on_delete'])
624
                            ->onUpdate($constraint[0]['on_update'])
625 51
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
626 51
                            ->name($name);
627
                        break;
628
                    case 'UNIQUE':
629
                        $result[self::UNIQUES][] = (new Constraint())
630
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
631
                            ->name($name);
632
                        break;
633 51
                }
634
            }
635
        }
636
637
        foreach ($result as $type => $data) {
638 51
            $this->setTableMetadata($tableName, $type, $data);
639 51
        }
640 51
641 40
        return $result[$returnType];
642 40
    }
643 40
644 49
    /**
645 13
     * Loads all default value constraints for the given table.
646 13
     *
647 13
     * @param string $tableName table name.
648 13
     *
649 13
     * @throws NotSupportedException
650 13
     *
651 13
     * @return array default value constraints for the given table.
652 13
     */
653 13
    protected function loadTableDefaultValues(string $tableName): array
654 40
    {
655 40
        throw new NotSupportedException('MySQL does not support default value constraints.');
656 40
    }
657 40
658 40
    /**
659
     * Loads all foreign keys for the given table.
660
     *
661
     * @param string $tableName table name.
662
     *
663 51
     * @throws Exception|InvalidConfigException|Throwable
664 51
     *
665
     * @return array foreign keys for the given table.
666
     */
667 51
    protected function loadTableForeignKeys(string $tableName): array
668
    {
669
        $tableForeignKeys = $this->loadTableConstraints($tableName, self::FOREIGN_KEYS);
670
671
        return is_array($tableForeignKeys) ? $tableForeignKeys : [];
672
    }
673
674
    /**
675
     * Loads all indexes for the given table.
676
     *
677
     * @param string $tableName table name.
678
     *
679 12
     * @throws Exception|InvalidConfigException|Throwable
680
     *
681 12
     * @return IndexConstraint[] indexes for the given table.
682
     */
683
    protected function loadTableIndexes(string $tableName): array
684
    {
685
        $sql = <<<SQL
686
        SELECT
687
            `s`.`INDEX_NAME` AS `name`,
688
            `s`.`COLUMN_NAME` AS `column_name`,
689
            `s`.`NON_UNIQUE` ^ 1 AS `index_is_unique`,
690
            `s`.`INDEX_NAME` = 'PRIMARY' AS `index_is_primary`
691
        FROM `information_schema`.`STATISTICS` AS `s`
692
        WHERE
693 5
            `s`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND
694
            `s`.`INDEX_SCHEMA` = `s`.`TABLE_SCHEMA` AND
695 5
            `s`.`TABLE_NAME` = :tableName
696
        ORDER BY `s`.`SEQ_IN_INDEX` ASC
697 5
        SQL;
698
699
        $resolvedName = $this->resolveTableName($tableName);
700
701
        $indexes = $this->db->createCommand($sql, [
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Mysql\Schema. Did you maybe forget to declare it?
Loading history...
702
            ':schemaName' => $resolvedName->getSchemaName(),
703
            ':tableName' => $resolvedName->getName(),
704
        ])->queryAll();
705
706
        /** @var array[] $indexes */
707
        $indexes = $this->normalizeRowKeyCase($indexes, true);
708
        $indexes = ArrayHelper::index($indexes, null, 'name');
709 29
        $result = [];
710
711 29
        /**
712
         * @psalm-var object|string|null $name
713
         * @psalm-var array[] $index
714
         */
715
        foreach ($indexes as $name => $index) {
716
            $ic = new IndexConstraint();
717
718
            $ic->primary((bool) $index[0]['index_is_primary']);
719
            $ic->unique((bool) $index[0]['index_is_unique']);
720
            $ic->name($name !== 'PRIMARY' ? $name : null);
721
            $ic->columnNames(ArrayHelper::getColumn($index, 'column_name'));
722
723
            $result[] = $ic;
724
        }
725 29
726
        return $result;
727 29
    }
728 29
729 29
    /**
730 29
     * Loads a primary key for the given table.
731
     *
732
     * @param string $tableName table name.
733 29
     *
734 29
     * @throws Exception|InvalidConfigException|Throwable
735 29
     *
736
     * @return Constraint|null primary key for the given table, `null` if the table has no primary key.*
737
     */
738
    protected function loadTablePrimaryKey(string $tableName): ?Constraint
739
    {
740
        $tablePrimaryKey = $this->loadTableConstraints($tableName, self::PRIMARY_KEY);
741 29
742 29
        return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
743
    }
744 29
745 29
    /**
746 29
     * Loads the metadata for the specified table.
747 29
     *
748
     * @param string $name table name.
749 29
     *
750
     * @throws Exception|Throwable
751
     *
752 29
     * @return TableSchemaInterface|null DBMS-dependent table metadata, `null` if the table does not exist.
753
     */
754
    protected function loadTableSchema(string $name): ?TableSchemaInterface
755
    {
756
        $table = $this->resolveTableName($name);
757
        $this->resolveTableCreateSql($table);
758
759
        if ($this->findColumns($table)) {
760
            $this->findConstraints($table);
761
762
            return $table;
763
        }
764 32
765
        return null;
766 32
    }
767
768 32
    /**
769
     * Loads all unique constraints for the given table.
770
     *
771
     * @param string $tableName table name.
772
     *
773
     * @throws Exception|InvalidConfigException|Throwable
774
     *
775
     * @return array unique constraints for the given table.
776
     */
777
    protected function loadTableUniques(string $tableName): array
778
    {
779
        $tableUniques = $this->loadTableConstraints($tableName, self::UNIQUES);
780 102
781
        return is_array($tableUniques) ? $tableUniques : [];
782 102
    }
783 102
784
    /**
785 102
     * Changes row's array key case to lower.
786 96
     *
787
     * @param array $row row's array or an array of row's arrays.
788 96
     * @param bool $multiple whether multiple rows or a single row passed.
789
     *
790
     * @return array normalized row or rows.
791 15
     */
792
    protected function normalizeRowKeyCase(array $row, bool $multiple): array
793
    {
794
        if ($multiple) {
795
            return array_map(static function (array $row) {
796
                return array_change_key_case($row, CASE_LOWER);
797
            }, $row);
798
        }
799
800
        return array_change_key_case($row, CASE_LOWER);
801
    }
802
803 14
    /**
804
     * Resolves the table name and schema name (if any).
805 14
     *
806
     * @param string $name the table name.
807 14
     *
808
     * @return TableSchemaInterface
809
     *
810
     * {@see TableSchemaInterface}
811
     */
812
    protected function resolveTableName(string $name): TableSchemaInterface
813
    {
814
        $resolvedName = new TableSchema();
815
816
        $parts = array_reverse(
817
            $this->db->getQuoter()->getTableNameParts($name)
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Mysql\Schema. Did you maybe forget to declare it?
Loading history...
818 140
        );
819
820 140
        $resolvedName->name($parts[0] ?? '');
821 62
        $resolvedName->schemaName($parts[1] ?? $this->defaultSchema);
822 62
823
        $resolvedName->fullName($resolvedName->getSchemaName() !== $this->defaultSchema ?
824
            implode('.', array_reverse($parts)) : $resolvedName->getName()
825
        );
826 96
827
        return $resolvedName;
828
    }
829
830
    /**
831
     * @throws Exception|InvalidConfigException|Throwable
832
     */
833
    protected function resolveTableCreateSql(TableSchemaInterface $table): void
834
    {
835
        $sql = $this->getCreateTableSql($table);
836
        $table->createSql($sql);
837
    }
838 142
839
    /**
840 142
     * Creates a column schema for the database.
841
     *
842 142
     * This method may be overridden by child classes to create a DBMS-specific column schema.
843
     *
844 142
     * @return ColumnSchema column schema instance.
845
     */
846
    private function createColumnSchema(): ColumnSchema
847
    {
848 142
        return new ColumnSchema();
849 142
    }
850
}
851