Test Setup Failed
Pull Request — master (#225)
by
unknown
02:47
created

Schema::loadTableConstraints()   B

Complexity

Conditions 8
Paths 14

Size

Total Lines 86
Code Lines 64

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 47
CRAP Score 8

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 64
c 1
b 0
f 0
nc 14
nop 2
dl 0
loc 86
ccs 47
cts 47
cp 1
crap 8
rs 7.541

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\Oracle;
6
7
use Throwable;
8
use Yiisoft\Db\Cache\SchemaCache;
9
use Yiisoft\Db\Connection\ConnectionInterface;
10
use Yiisoft\Db\Constraint\CheckConstraint;
11
use Yiisoft\Db\Constraint\Constraint;
12
use Yiisoft\Db\Constraint\ForeignKeyConstraint;
13
use Yiisoft\Db\Constraint\IndexConstraint;
14
use Yiisoft\Db\Driver\Pdo\AbstractPdoSchema;
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\Helper\DbArrayHelper;
20
use Yiisoft\Db\Schema\Builder\ColumnInterface;
21
use Yiisoft\Db\Schema\ColumnSchemaInterface;
22
use Yiisoft\Db\Schema\TableSchemaInterface;
23
24
use function array_merge;
25
use function array_reverse;
26
use function implode;
27
use function is_array;
28
use function md5;
29
use function serialize;
30
use function str_contains;
31
use function strlen;
32
use function substr;
33
use function trim;
34
35
/**
36
 * Implements the Oracle Server specific schema, supporting Oracle Server 11C and above.
37
 *
38
 * @psalm-type ConstraintArray = array<
39
 *   array-key,
40
 *   array {
41
 *     name: string,
42
 *     column_name: string,
43
 *     type: string,
44
 *     foreign_table_schema: string|null,
45
 *     foreign_table_name: string|null,
46
 *     foreign_column_name: string|null,
47
 *     on_update: string,
48
 *     on_delete: string,
49
 *     check_expr: string
50
 *   }
51
 * >
52
 */
53
final class Schema extends AbstractPdoSchema
54
{
55 543
    public function __construct(protected ConnectionInterface $db, SchemaCache $schemaCache, string $defaultSchema)
56
    {
57 543
        $this->defaultSchema = $defaultSchema;
58 543
        parent::__construct($db, $schemaCache);
59
    }
60
61 15
    public function createColumn(string $type, array|int|string $length = null): ColumnInterface
62
    {
63 15
        return new Column($type, $length);
64
    }
65
66 205
    protected function resolveTableName(string $name): TableSchemaInterface
67
    {
68 205
        $resolvedName = new TableSchema();
69
70 205
        $parts = array_reverse(
71 205
            $this->db->getQuoter()->getTableNameParts($name)
72 205
        );
73
74 205
        $resolvedName->name($parts[0] ?? '');
75 205
        $resolvedName->schemaName($parts[1] ?? $this->defaultSchema);
76
77 205
        $resolvedName->fullName(
78 205
            $resolvedName->getSchemaName() !== $this->defaultSchema ?
79 205
            implode('.', array_reverse($parts)) : $resolvedName->getName()
80 205
        );
81
82 205
        return $resolvedName;
83
    }
84
85
    /**
86
     * @link https://docs.oracle.com/cd/B28359_01/server.111/b28337/tdpsg_user_accounts.htm
87
     *
88
     * @throws Exception
89
     * @throws InvalidConfigException
90
     * @throws NotSupportedException
91
     * @throws Throwable
92
     */
93 1
    protected function findSchemaNames(): array
94
    {
95 1
        $sql = <<<SQL
96
        SELECT "u"."USERNAME"
97
        FROM "DBA_USERS" "u"
98
        WHERE "u"."DEFAULT_TABLESPACE" NOT IN ('SYSTEM', 'SYSAUX')
99
        ORDER BY "u"."USERNAME" ASC
100 1
        SQL;
101
102 1
        return $this->db->createCommand($sql)->queryColumn();
103
    }
104
105
    /**
106
     * @throws Exception
107
     * @throws InvalidConfigException
108
     * @throws Throwable
109
     */
110 146
    protected function findTableComment(TableSchemaInterface $tableSchema): void
111
    {
112 146
        $sql = <<<SQL
113
        SELECT "COMMENTS"
114
        FROM ALL_TAB_COMMENTS
115
        WHERE
116
              "OWNER" = :schemaName AND
117
              "TABLE_NAME" = :tableName
118 146
        SQL;
119
120 146
        $comment = $this->db->createCommand($sql, [
121 146
            ':schemaName' => $tableSchema->getSchemaName(),
122 146
            ':tableName' => $tableSchema->getName(),
123 146
        ])->queryScalar();
124
125 146
        $tableSchema->comment(is_string($comment) ? $comment : null);
126
    }
127
128
    /**
129
     * @throws Exception
130
     * @throws InvalidConfigException
131
     * @throws Throwable
132
     */
133 12
    protected function findTableNames(string $schema = ''): array
134
    {
135 12
        if ($schema === '') {
136 11
            $sql = <<<SQL
137
            SELECT TABLE_NAME
138
            FROM USER_TABLES
139
            UNION ALL
140
            SELECT VIEW_NAME AS TABLE_NAME
141
            FROM USER_VIEWS
142
            UNION ALL
143
            SELECT MVIEW_NAME AS TABLE_NAME
144
            FROM USER_MVIEWS
145
            ORDER BY TABLE_NAME
146 11
            SQL;
147
148 11
            $command = $this->db->createCommand($sql);
149
        } else {
150 1
            $sql = <<<SQL
151
            SELECT OBJECT_NAME AS TABLE_NAME
152
            FROM ALL_OBJECTS
153
            WHERE OBJECT_TYPE IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW') AND OWNER = :schema
154
            ORDER BY OBJECT_NAME
155 1
            SQL;
156 1
            $command = $this->db->createCommand($sql, [':schema' => $schema]);
157
        }
158
159 12
        $rows = $command->queryAll();
160 12
        $names = [];
161
162
        /** @psalm-var string[][] $rows */
163 12
        foreach ($rows as $row) {
164
            /** @psalm-var string[] $row */
165 12
            $row = $this->normalizeRowKeyCase($row, false);
166 12
            $names[] = $row['table_name'];
167
        }
168
169 12
        return $names;
170
    }
171
172
    /**
173
     * @throws Exception
174
     * @throws InvalidConfigException
175
     * @throws Throwable
176
     */
177 146
    protected function loadTableSchema(string $name): TableSchemaInterface|null
178
    {
179 146
        $table = $this->resolveTableName($name);
180 146
        $this->findTableComment($table);
181
182 146
        if ($this->findColumns($table)) {
183 129
            $this->findConstraints($table);
184 129
            return $table;
185
        }
186
187 33
        return null;
188
    }
189
190
    /**
191
     * @throws Exception
192
     * @throws InvalidConfigException
193
     * @throws NotSupportedException
194
     * @throws Throwable
195
     */
196 47
    protected function loadTablePrimaryKey(string $tableName): Constraint|null
197
    {
198
        /** @psalm-var mixed $tablePrimaryKey */
199 47
        $tablePrimaryKey = $this->loadTableConstraints($tableName, self::PRIMARY_KEY);
200 47
        return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
201
    }
202
203
    /**
204
     * @throws Exception
205
     * @throws InvalidConfigException
206
     * @throws NotSupportedException
207
     * @throws Throwable
208
     */
209 8
    protected function loadTableForeignKeys(string $tableName): array
210
    {
211
        /** @psalm-var mixed $tableForeignKeys */
212 8
        $tableForeignKeys = $this->loadTableConstraints($tableName, self::FOREIGN_KEYS);
213 8
        return is_array($tableForeignKeys) ? $tableForeignKeys : [];
214
    }
215
216
    /**
217
     * @throws Exception
218
     * @throws InvalidConfigException
219
     * @throws NotSupportedException
220
     * @throws Throwable
221
     */
222 38
    protected function loadTableIndexes(string $tableName): array
223
    {
224 38
        $sql = <<<SQL
225
        SELECT "ui"."INDEX_NAME" AS "name", "uicol"."COLUMN_NAME" AS "column_name",
226
        CASE "ui"."UNIQUENESS" WHEN 'UNIQUE' THEN 1 ELSE 0 END AS "index_is_unique",
227
        CASE WHEN "uc"."CONSTRAINT_NAME" IS NOT NULL THEN 1 ELSE 0 END AS "index_is_primary"
228
        FROM "SYS"."USER_INDEXES" "ui"
229
        LEFT JOIN "SYS"."USER_IND_COLUMNS" "uicol"
230
        ON "uicol"."INDEX_NAME" = "ui"."INDEX_NAME"
231
        LEFT JOIN "SYS"."USER_CONSTRAINTS" "uc"
232
        ON "uc"."OWNER" = "ui"."TABLE_OWNER" AND "uc"."CONSTRAINT_NAME" = "ui"."INDEX_NAME" AND "uc"."CONSTRAINT_TYPE" = 'P'
233
        WHERE "ui"."TABLE_OWNER" = :schemaName AND "ui"."TABLE_NAME" = :tableName
234
        ORDER BY "uicol"."COLUMN_POSITION" ASC
235 38
        SQL;
236
237 38
        $resolvedName = $this->resolveTableName($tableName);
238 38
        $indexes = $this->db->createCommand($sql, [
239 38
            ':schemaName' => $resolvedName->getSchemaName(),
240 38
            ':tableName' => $resolvedName->getName(),
241 38
        ])->queryAll();
242
243
        /** @psalm-var array[] $indexes */
244 38
        $indexes = $this->normalizeRowKeyCase($indexes, true);
245 38
        $indexes = DbArrayHelper::index($indexes, null, ['name']);
246
247 38
        $result = [];
248
249
        /**
250
         * @psalm-var object|string|null $name
251
         * @psalm-var array[] $index
252
         */
253 38
        foreach ($indexes as $name => $index) {
254 35
            $columnNames = DbArrayHelper::getColumn($index, 'column_name');
255
256 35
            if ($columnNames[0] === null) {
257 20
                $columnNames[0] = '';
258
            }
259
260 35
            $result[] = (new IndexConstraint())
261 35
                ->primary((bool) $index[0]['index_is_primary'])
262 35
                ->unique((bool) $index[0]['index_is_unique'])
263 35
                ->name($name)
264 35
                ->columnNames($columnNames);
265
        }
266
267 38
        return $result;
268
    }
269
270
    /**
271
     * @throws Exception
272
     * @throws InvalidConfigException
273
     * @throws NotSupportedException
274
     * @throws Throwable
275
     */
276 17
    protected function loadTableUniques(string $tableName): array
277
    {
278
        /** @psalm-var mixed $tableUniques */
279 17
        $tableUniques = $this->loadTableConstraints($tableName, self::UNIQUES);
280 17
        return is_array($tableUniques) ? $tableUniques : [];
281
    }
282
283
    /**
284
     * @throws Exception
285
     * @throws InvalidConfigException
286
     * @throws NotSupportedException
287
     * @throws Throwable
288
     */
289 17
    protected function loadTableChecks(string $tableName): array
290
    {
291
        /** @psalm-var mixed $tableCheck */
292 17
        $tableCheck = $this->loadTableConstraints($tableName, self::CHECKS);
293 17
        return is_array($tableCheck) ? $tableCheck : [];
294
    }
295
296
    /**
297
     * @throws NotSupportedException If this method is called.
298
     */
299 13
    protected function loadTableDefaultValues(string $tableName): array
300
    {
301 13
        throw new NotSupportedException(__METHOD__ . ' is not supported by Oracle.');
302
    }
303
304
    /**
305
     * Collects the table column metadata.
306
     *
307
     * @param TableSchemaInterface $table The table schema.
308
     *
309
     * @throws Exception
310
     * @throws Throwable
311
     *
312
     * @return bool Whether the table exists.
313
     */
314 146
    protected function findColumns(TableSchemaInterface $table): bool
315
    {
316 146
        $sql = <<<SQL
317
        SELECT
318
            A.COLUMN_NAME,
319
            A.DATA_TYPE,
320
            A.DATA_PRECISION,
321
            A.DATA_SCALE,
322
            (
323
            CASE A.CHAR_USED WHEN 'C' THEN A.CHAR_LENGTH
324
                ELSE A.DATA_LENGTH
325
            END
326
            ) AS DATA_LENGTH,
327
            A.NULLABLE,
328
            A.DATA_DEFAULT,
329
            (
330
                SELECT COUNT(*)
331
                FROM ALL_CONSTRAINTS AC
332
                INNER JOIN ALL_CONS_COLUMNS ACC ON ACC.CONSTRAINT_NAME=AC.CONSTRAINT_NAME
333
                WHERE
334
                     AC.OWNER = A.OWNER
335
                   AND AC.TABLE_NAME = B.OBJECT_NAME
336
                   AND ACC.COLUMN_NAME = A.COLUMN_NAME
337
                   AND AC.CONSTRAINT_TYPE = 'P'
338
            ) AS IS_PK,
339
            COM.COMMENTS AS COLUMN_COMMENT
340
        FROM ALL_TAB_COLUMNS A
341
            INNER JOIN ALL_OBJECTS B ON B.OWNER = A.OWNER AND LTRIM(B.OBJECT_NAME) = LTRIM(A.TABLE_NAME)
342
            LEFT JOIN ALL_COL_COMMENTS COM ON (A.OWNER = COM.OWNER AND A.TABLE_NAME = COM.TABLE_NAME AND A.COLUMN_NAME = COM.COLUMN_NAME)
343
        WHERE
344
            A.OWNER = :schemaName
345
            AND B.OBJECT_TYPE IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW')
346
            AND B.OBJECT_NAME = :tableName
347
        ORDER BY A.COLUMN_ID
348 146
        SQL;
349
350 146
        $columns = $this->db->createCommand($sql, [
351 146
            ':tableName' => $table->getName(),
352 146
            ':schemaName' => $table->getSchemaName(),
353 146
        ])->queryAll();
354
355 146
        if ($columns === []) {
356 33
            return false;
357
        }
358
359
        /** @psalm-var string[][] $columns */
360 129
        foreach ($columns as $column) {
361 129
            $column = $this->normalizeRowKeyCase($column, false);
362
363
            /**
364
             * @psalm-var array{
365
             *   column_name: string,
366
             *   data_type: string,
367
             *   data_precision: string,
368
             *   data_scale: string,
369
             *   data_length: string,
370
             *   nullable: string,
371
             *   data_default: string|null,
372
             *   is_pk: string|null,
373
             *   column_comment: string|null
374
             * } $column $column
375
             */
376 129
            $c = $this->createColumnSchema($column);
377
378 129
            $table->column($c->getName(), $c);
379
        }
380
381 129
        return true;
382
    }
383
384
    /**
385
     * Sequence name of table.
386
     *
387
     * @throws Exception
388
     * @throws InvalidConfigException
389
     * @throws Throwable
390
     *
391
     * @return bool|float|int|string|null Whether the sequence exists.
392
     *
393
     * @internal TableSchemaInterface `$table->getName()` The table schema.
394
     */
395 79
    protected function getTableSequenceName(string $tableName): bool|float|int|string|null
396
    {
397 79
        $sequenceNameSql = <<<SQL
398
        SELECT
399
            UD.REFERENCED_NAME AS SEQUENCE_NAME
400
        FROM USER_DEPENDENCIES UD
401
            JOIN USER_TRIGGERS UT ON (UT.TRIGGER_NAME = UD.NAME)
402
        WHERE
403
            UT.TABLE_NAME = :tableName
404
            AND UD.TYPE = 'TRIGGER'
405
            AND UD.REFERENCED_TYPE = 'SEQUENCE'
406 79
        SQL;
407 79
        $sequenceName = $this->db->createCommand($sequenceNameSql, [':tableName' => $tableName])->queryScalar();
408
409 79
        return $sequenceName === false ? null : $sequenceName;
410
    }
411
412
    /**
413
     * Creates ColumnSchema instance.
414
     *
415
     * @psalm-param array{
416
     *   column_name: string,
417
     *   data_type: string,
418
     *   data_precision: string|null,
419
     *   data_scale: string|null,
420
     *   data_length: string,
421
     *   nullable: string,
422
     *   data_default: string|null,
423
     *   is_pk: string|null,
424
     *   column_comment: string|null
425
     * } $column
426
     */
427 129
    protected function createColumnSchema(array $column): ColumnSchemaInterface
428
    {
429 129
        $columnSchema = new ColumnSchema($column['column_name']);
430 129
        $columnSchema->allowNull($column['nullable'] === 'Y');
431 129
        $columnSchema->comment($column['column_comment']);
432 129
        $columnSchema->primaryKey((bool) $column['is_pk']);
433
        $columnSchema->size((int) $column['data_length']);
434 129
        $columnSchema->precision($column['data_precision'] !== null ? (int) $column['data_precision'] : null);
435 129
        $columnSchema->scale($column['data_scale'] !== null ? (int) $column['data_scale'] : null);
436 129
        $columnSchema->dbType($column['data_type']);
437 129
        $columnSchema->type($this->extractColumnType($columnSchema));
438 129
        $columnSchema->phpType($this->getColumnPhpType($columnSchema));
439 129
        $columnSchema->defaultValue($this->normalizeDefaultValue($column['data_default'], $columnSchema));
440 129
441
        return $columnSchema;
442 129
    }
443 129
444 129
    /**
445 129
     * Converts column's default value according to {@see ColumnSchema::phpType} after retrieval from the database.
446 129
     *
447 129
     * @param string|null $defaultValue The default value retrieved from the database.
448 129
     * @param ColumnSchemaInterface $columnSchema The column schema object.
449
     *
450 129
     * @return mixed The normalized default value.
451
     *
452 129
     * @psalm-suppress PossiblyNullArgument
453 125
     */
454 121
    private function normalizeDefaultValue(?string $defaultValue, ColumnSchemaInterface $columnSchema): mixed
455
    {
456 71
        return match (true) {
457
            $defaultValue === null,
458 71
            $columnSchema->isPrimaryKey()
459
                => null,
460
            $defaultValue === 'CURRENT_TIMESTAMP'
461
                && $columnSchema->getType() === self::TYPE_TIMESTAMP
462 71
                    => new Expression($defaultValue),
463 71
            /** @psalm-var string $defaultValue */
464 71
            strlen($defaultValue) > 2
465
                && str_starts_with($defaultValue, "'")
466 25
                && str_ends_with($defaultValue, "'")
467
                    => $columnSchema->phpTypecast(substr($defaultValue, 1, -1)),
468 71
            default
469
            => $columnSchema->phpTypecast(trim($defaultValue)),
470
        };
471 71
    }
472
473
    /**
474
     * Finds constraints and fills them into TableSchemaInterface object passed.
475
     *
476 129
     * @throws Exception
477
     * @throws InvalidConfigException
478
     * @throws Throwable
479
     *
480
     * @psalm-suppress PossiblyNullArrayOffset
481
     */
482
    protected function findConstraints(TableSchemaInterface $table): void
483
    {
484
        $sql = <<<SQL
485
        SELECT
486
            /*+ PUSH_PRED(C) PUSH_PRED(D) PUSH_PRED(E) */
487
            D.CONSTRAINT_NAME,
488 129
            D.CONSTRAINT_TYPE,
489
            C.COLUMN_NAME,
490 129
            C.POSITION,
491
            D.R_CONSTRAINT_NAME,
492
            E.TABLE_NAME AS TABLE_REF,
493
            F.COLUMN_NAME AS COLUMN_REF,
494
            C.TABLE_NAME
495
        FROM ALL_CONS_COLUMNS C
496
            INNER JOIN ALL_CONSTRAINTS D ON D.OWNER = C.OWNER AND D.CONSTRAINT_NAME = C.CONSTRAINT_NAME
497
            LEFT JOIN ALL_CONSTRAINTS E ON E.OWNER = D.R_OWNER AND E.CONSTRAINT_NAME = D.R_CONSTRAINT_NAME
498
            LEFT JOIN ALL_CONS_COLUMNS F ON F.OWNER = E.OWNER AND F.CONSTRAINT_NAME = E.CONSTRAINT_NAME AND F.POSITION = C.POSITION
499
        WHERE
500
            C.OWNER = :schemaName
501
            AND C.TABLE_NAME = :tableName
502
            ORDER BY D.CONSTRAINT_NAME, C.POSITION
503
        SQL;
504
505
        /**
506
         * @psalm-var array{
507
         *   array{
508
         *     constraint_name: string,
509 129
         *     constraint_type: string,
510
         *     column_name: string,
511
         *     position: string|null,
512
         *     r_constraint_name: string|null,
513
         *     table_ref: string|null,
514
         *     column_ref: string|null,
515
         *     table_name: string
516
         *   }
517
         * } $rows
518
         */
519
        $rows = $this->db->createCommand(
520
            $sql,
521
            [':tableName' => $table->getName(), ':schemaName' => $table->getSchemaName()]
522
        )->queryAll();
523
524
        $constraints = [];
525 129
526 129
        foreach ($rows as $row) {
527 129
            /** @psalm-var string[] $row */
528 129
            $row = $this->normalizeRowKeyCase($row, false);
529
530 129
            if ($row['constraint_type'] === 'P') {
531
                $table->getColumns()[$row['column_name']]->primaryKey(true);
532 129
                $table->primaryKey($row['column_name']);
533
534 118
                if (empty($table->getSequenceName())) {
535
                    $table->sequenceName((string) $this->getTableSequenceName($table->getName()));
536 118
                }
537 79
            }
538 79
539
            if ($row['constraint_type'] !== 'R') {
540 79
                /**
541 79
                 * This condition isn't checked in `WHERE` because of an Oracle Bug:
542
                 *
543
                 * @link https://github.com/yiisoft/yii2/pull/8844
544
                 */
545 118
                continue;
546
            }
547
548
            $name = $row['constraint_name'];
549
550
            if (!isset($constraints[$name])) {
551 118
                $constraints[$name] = [
552
                    'tableName' => $row['table_ref'],
553
                    'columns' => [],
554 14
                ];
555
            }
556 14
557 14
            $constraints[$name]['columns'][$row['column_name']] = $row['column_ref'];
558 14
        }
559 14
560 14
        foreach ($constraints as $index => $constraint) {
561
            $table->foreignKey($index, array_merge([$constraint['tableName']], $constraint['columns']));
562
        }
563 14
    }
564
565
    /**
566 129
     * Returns all unique indexes for the given table.
567 14
     *
568
     * Each array element is of the following structure:.
569
     *
570
     * ```php
571
     * [
572
     *     'IndexName1' => ['col1' [, ...]],
573
     *     'IndexName2' => ['col2' [, ...]],
574
     * ]
575
     * ```
576
     *
577
     * @param TableSchemaInterface $table The table metadata.
578
     *
579
     * @throws Exception
580
     * @throws InvalidConfigException
581
     * @throws Throwable
582
     *
583
     * @return array All unique indexes for the given table.
584
     */
585
    public function findUniqueIndexes(TableSchemaInterface $table): array
586
    {
587
        $query = <<<SQL
588
        SELECT
589
            DIC.INDEX_NAME,
590
            DIC.COLUMN_NAME
591 1
        FROM ALL_INDEXES DI
592
            INNER JOIN ALL_IND_COLUMNS DIC ON DI.TABLE_NAME = DIC.TABLE_NAME AND DI.INDEX_NAME = DIC.INDEX_NAME
593 1
        WHERE
594
            DI.UNIQUENESS = 'UNIQUE'
595
            AND DIC.TABLE_OWNER = :schemaName
596
            AND DIC.TABLE_NAME = :tableName
597
        ORDER BY DIC.TABLE_NAME, DIC.INDEX_NAME, DIC.COLUMN_POSITION
598
        SQL;
599
        $result = [];
600
601
        $rows = $this->db->createCommand(
602
            $query,
603
            [':tableName' => $table->getName(), ':schemaName' => $table->getschemaName()]
604 1
        )->queryAll();
605 1
606
        /** @psalm-var array<array{INDEX_NAME: string, COLUMN_NAME: string}> $rows */
607 1
        foreach ($rows as $row) {
608 1
            $result[$row['INDEX_NAME']][] = $row['COLUMN_NAME'];
609 1
        }
610 1
611
        return $result;
612
    }
613 1
614 1
    /**
615
     * Extracts the data type for the given column.
616
     *
617 1
     * @param ColumnSchemaInterface $columnSchema The column schema object.
618
     *
619
     * @return string The abstract column type.
620
     */
621
    private function extractColumnType(ColumnSchemaInterface $columnSchema): string
622
    {
623
        $dbType = (string) $columnSchema->getDbType();
624
625
        return match (true) {
626
            str_contains($dbType, 'FLOAT') || str_contains($dbType, 'DOUBLE')
627
                => self::TYPE_DOUBLE,
628 129
            str_contains($dbType, 'NUMBER')
629
                => $columnSchema->getScale() === null || $columnSchema->getScale() > 0
630
                    ? self::TYPE_DECIMAL
631
                    : self::TYPE_INTEGER,
632
            str_contains($dbType, 'BLOB')
633
                => self::TYPE_BINARY,
634
            str_contains($dbType, 'CLOB')
635 129
                => self::TYPE_TEXT,
636
            str_contains($dbType, 'TIMESTAMP')
637 129
                => self::TYPE_TIMESTAMP,
638 28
            default
639 129
            => self::TYPE_STRING,
640 121
        };
641 31
    }
642
643 121
    /**
644
     * Loads multiple types of constraints and returns the specified ones.
645 97
     *
646 30
     * @param string $tableName The table name.
647 93
     * @param string $returnType The return type:
648 24
     * - primaryKey
649 92
     * - foreignKeys
650 26
     * - uniques
651
     * - checks
652 92
     *
653
     * @throws Exception
654
     * @throws InvalidConfigException
655
     * @throws NotSupportedException
656
     * @throws Throwable
657
     *
658
     * @return mixed Constraints.
659
     */
660
    private function loadTableConstraints(string $tableName, string $returnType): mixed
661
    {
662
        $sql = <<<SQL
663
        SELECT
664 129
            "uc"."CONSTRAINT_NAME" AS "name",
665
            "uccol"."COLUMN_NAME" AS "column_name",
666
            "uc"."CONSTRAINT_TYPE" AS "type",
667
            "fuc"."OWNER" AS "foreign_table_schema",
668
            "fuc"."TABLE_NAME" AS "foreign_table_name",
669
            "fuccol"."COLUMN_NAME" AS "foreign_column_name",
670
            "uc"."DELETE_RULE" AS "on_delete",
671 129
            "uc"."SEARCH_CONDITION" AS "check_expr"
672 129
        FROM "USER_CONSTRAINTS" "uc"
673 129
        INNER JOIN "USER_CONS_COLUMNS" "uccol"
674
        ON "uccol"."OWNER" = "uc"."OWNER" AND "uccol"."CONSTRAINT_NAME" = "uc"."CONSTRAINT_NAME"
675
        LEFT JOIN "USER_CONSTRAINTS" "fuc"
676
        ON "fuc"."OWNER" = "uc"."R_OWNER" AND "fuc"."CONSTRAINT_NAME" = "uc"."R_CONSTRAINT_NAME"
677
        LEFT JOIN "USER_CONS_COLUMNS" "fuccol"
678
        ON "fuccol"."OWNER" = "fuc"."OWNER" AND "fuccol"."CONSTRAINT_NAME" = "fuc"."CONSTRAINT_NAME" AND "fuccol"."POSITION" = "uccol"."POSITION"
679
        WHERE "uc"."OWNER" = :schemaName AND "uc"."TABLE_NAME" = :tableName
680
        ORDER BY "uccol"."POSITION" ASC
681
        SQL;
682
683
        $resolvedName = $this->resolveTableName($tableName);
684
        $constraints = $this->db->createCommand($sql, [
685
            ':schemaName' => $resolvedName->getSchemaName(),
686
            ':tableName' => $resolvedName->getName(),
687
        ])->queryAll();
688
689
        /** @psalm-var array[] $constraints */
690
        $constraints = $this->normalizeRowKeyCase($constraints, true);
691
        $constraints = DbArrayHelper::index($constraints, null, ['type', 'name']);
692
693 89
        $result = [
694
            self::PRIMARY_KEY => null,
695 89
            self::FOREIGN_KEYS => [],
696
            self::UNIQUES => [],
697
            self::CHECKS => [],
698
        ];
699
700
        /**
701
         * @psalm-var string $type
702
         * @psalm-var array $names
703
         */
704
        foreach ($constraints as $type => $names) {
705
            /**
706
             * @psalm-var object|string|null $name
707
             * @psalm-var ConstraintArray $constraint
708
             */
709
            foreach ($names as $name => $constraint) {
710
                switch ($type) {
711
                    case 'P':
712
                        $result[self::PRIMARY_KEY] = (new Constraint())
713
                            ->name($name)
714 89
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'));
715
                        break;
716 89
                    case 'R':
717 89
                        $result[self::FOREIGN_KEYS][] = (new ForeignKeyConstraint())
718 89
                            ->name($name)
719 89
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'))
720 89
                            ->foreignSchemaName($constraint[0]['foreign_table_schema'])
721
                            ->foreignTableName($constraint[0]['foreign_table_name'])
722
                            ->foreignColumnNames(DbArrayHelper::getColumn($constraint, 'foreign_column_name'))
723 89
                            ->onDelete($constraint[0]['on_delete'])
724 89
                            ->onUpdate(null);
725
                        break;
726 89
                    case 'U':
727 89
                        $result[self::UNIQUES][] = (new Constraint())
728 89
                            ->name($name)
729 89
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'));
730 89
                        break;
731 89
                    case 'C':
732
                        $result[self::CHECKS][] = (new CheckConstraint())
733
                            ->name($name)
734
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'))
735
                            ->expression($constraint[0]['check_expr']);
736
                        break;
737 89
                }
738
            }
739
        }
740
741
        foreach ($result as $type => $data) {
742 82
            $this->setTableMetadata($tableName, $type, $data);
743
        }
744 82
745 57
        return $result[$returnType];
746 57
    }
747 57
748 57
    /**
749 82
     * @throws Exception
750 19
     * @throws InvalidConfigException
751 19
     * @throws Throwable
752 19
     */
753 19
    protected function findViewNames(string $schema = ''): array
754 19
    {
755 19
        $sql = match ($schema) {
756 19
            '' => <<<SQL
757 19
            SELECT VIEW_NAME FROM USER_VIEWS
758 19
            SQL,
759 82
            default => <<<SQL
760 58
            SELECT VIEW_NAME FROM ALL_VIEWS WHERE OWNER = '$schema'
761 58
            SQL,
762 58
        };
763 58
764 82
        /** @psalm-var string[][] $views */
765 82
        $views = $this->db->createCommand($sql)->queryAll();
766 82
767 82
        foreach ($views as $key => $view) {
768 82
            $views[$key] = $view['VIEW_NAME'];
769 82
        }
770
771
        return $views;
772
    }
773
774 89
    /**
775 89
     * Returns the cache key for the specified table name.
776
     *
777
     * @param string $name The table name.
778 89
     *
779
     * @return array The cache key.
780
     */
781
    protected function getCacheKey(string $name): array
782
    {
783
        return array_merge([self::class], $this->generateCacheKey(), [$this->getRawTableName($name)]);
784
    }
785
786 2
    /**
787
     * Returns the cache tag name.
788 2
     *
789 2
     * This allows {@see refresh()} to invalidate all cached table schemas.
790
     *
791 2
     * @return string The cache tag name.
792 2
     */
793 2
    protected function getCacheTag(): string
794 2
    {
795 2
        return md5(serialize(array_merge([self::class], $this->generateCacheKey())));
796
    }
797
}
798