Test Setup Failed
Pull Request — master (#236)
by Sergei
20:20 queued 17:14
created

Schema::loadColumnSchema()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 18
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 14
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 18
ccs 11
cts 11
cp 1
crap 3
rs 9.7998
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\Column\ColumnSchemaInterface;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Schema\Column\ColumnSchemaInterface was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
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 preg_match;
30
use function serialize;
31
use function str_replace;
32
use function trim;
33
34
/**
35
 * Implements the Oracle Server specific schema, supporting Oracle Server 11C and above.
36
 *
37
 * @psalm-type ColumnInfoArray = array{
38
 *   column_name: string,
39
 *   data_type: string,
40
 *   data_precision: string|null,
41
 *   data_scale: string|null,
42
 *   data_length: string,
43
 *   nullable: string,
44
 *   data_default: string|null,
45
 *   is_pk: string|null,
46
 *   identity_column: string,
47
 *   column_comment: string|null
48
 * }
49
 *
50
 * @psalm-type ConstraintArray = array<
51
 *   array-key,
52
 *   array {
53
 *     name: string,
54
 *     column_name: string,
55 543
 *     type: string,
56
 *     foreign_table_schema: string|null,
57 543
 *     foreign_table_name: string|null,
58 543
 *     foreign_column_name: string|null,
59
 *     on_update: string,
60
 *     on_delete: string,
61 15
 *     check_expr: string
62
 *   }
63 15
 * >
64
 */
65
final class Schema extends AbstractPdoSchema
66 205
{
67
    public function __construct(protected ConnectionInterface $db, SchemaCache $schemaCache, string $defaultSchema)
68 205
    {
69
        $this->defaultSchema = $defaultSchema;
70 205
        parent::__construct($db, $schemaCache);
71 205
    }
72 205
73
    public function createColumn(string $type, array|int|string $length = null): ColumnInterface
74 205
    {
75 205
        return new Column($type, $length);
76
    }
77 205
78 205
    protected function resolveTableName(string $name): TableSchemaInterface
79 205
    {
80 205
        $resolvedName = new TableSchema();
81
82 205
        $parts = array_reverse(
83
            $this->db->getQuoter()->getTableNameParts($name)
84
        );
85
86
        $resolvedName->name($parts[0] ?? '');
87
        $resolvedName->schemaName($parts[1] ?? $this->defaultSchema);
88
89
        $resolvedName->fullName(
90
            $resolvedName->getSchemaName() !== $this->defaultSchema ?
91
            implode('.', array_reverse($parts)) : $resolvedName->getName()
92
        );
93 1
94
        return $resolvedName;
95 1
    }
96
97
    /**
98
     * @link https://docs.oracle.com/cd/B28359_01/server.111/b28337/tdpsg_user_accounts.htm
99
     *
100 1
     * @throws Exception
101
     * @throws InvalidConfigException
102 1
     * @throws NotSupportedException
103
     * @throws Throwable
104
     */
105
    protected function findSchemaNames(): array
106
    {
107
        $sql = <<<SQL
108
        SELECT "u"."USERNAME"
109
        FROM "DBA_USERS" "u"
110 146
        WHERE "u"."DEFAULT_TABLESPACE" NOT IN ('SYSTEM', 'SYSAUX')
111
        ORDER BY "u"."USERNAME" ASC
112 146
        SQL;
113
114
        return $this->db->createCommand($sql)->queryColumn();
115
    }
116
117
    /**
118 146
     * @throws Exception
119
     * @throws InvalidConfigException
120 146
     * @throws Throwable
121 146
     */
122 146
    protected function findTableComment(TableSchemaInterface $tableSchema): void
123 146
    {
124
        $sql = <<<SQL
125 146
        SELECT "COMMENTS"
126
        FROM ALL_TAB_COMMENTS
127
        WHERE
128
              "OWNER" = :schemaName AND
129
              "TABLE_NAME" = :tableName
130
        SQL;
131
132
        $comment = $this->db->createCommand($sql, [
133 12
            ':schemaName' => $tableSchema->getSchemaName(),
134
            ':tableName' => $tableSchema->getName(),
135 12
        ])->queryScalar();
136 11
137
        $tableSchema->comment(is_string($comment) ? $comment : null);
138
    }
139
140
    /**
141
     * @throws Exception
142
     * @throws InvalidConfigException
143
     * @throws Throwable
144
     */
145
    protected function findTableNames(string $schema = ''): array
146 11
    {
147
        if ($schema === '') {
148 11
            $sql = <<<SQL
149
            SELECT TABLE_NAME
150 1
            FROM USER_TABLES
151
            UNION ALL
152
            SELECT VIEW_NAME AS TABLE_NAME
153
            FROM USER_VIEWS
154
            UNION ALL
155 1
            SELECT MVIEW_NAME AS TABLE_NAME
156 1
            FROM USER_MVIEWS
157
            ORDER BY TABLE_NAME
158
            SQL;
159 12
160 12
            $command = $this->db->createCommand($sql);
161
        } else {
162
            $sql = <<<SQL
163 12
            SELECT OBJECT_NAME AS TABLE_NAME
164
            FROM ALL_OBJECTS
165 12
            WHERE OBJECT_TYPE IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW') AND OWNER = :schema
166 12
            ORDER BY OBJECT_NAME
167
            SQL;
168
            $command = $this->db->createCommand($sql, [':schema' => $schema]);
169 12
        }
170
171
        $rows = $command->queryAll();
172
        $names = [];
173
174
        /** @psalm-var string[][] $rows */
175
        foreach ($rows as $row) {
176
            /** @psalm-var string[] $row */
177 146
            $row = $this->normalizeRowKeyCase($row, false);
178
            $names[] = $row['table_name'];
179 146
        }
180 146
181
        return $names;
182 146
    }
183 129
184 129
    /**
185
     * @throws Exception
186
     * @throws InvalidConfigException
187 33
     * @throws Throwable
188
     */
189
    protected function loadTableSchema(string $name): TableSchemaInterface|null
190
    {
191
        $table = $this->resolveTableName($name);
192
        $this->findTableComment($table);
193
194
        if ($this->findColumns($table)) {
195
            $this->findConstraints($table);
196 47
            return $table;
197
        }
198
199 47
        return null;
200 47
    }
201
202
    /**
203
     * @throws Exception
204
     * @throws InvalidConfigException
205
     * @throws NotSupportedException
206
     * @throws Throwable
207
     */
208
    protected function loadTablePrimaryKey(string $tableName): Constraint|null
209 8
    {
210
        /** @psalm-var mixed $tablePrimaryKey */
211
        $tablePrimaryKey = $this->loadTableConstraints($tableName, self::PRIMARY_KEY);
212 8
        return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
213 8
    }
214
215
    /**
216
     * @throws Exception
217
     * @throws InvalidConfigException
218
     * @throws NotSupportedException
219
     * @throws Throwable
220
     */
221
    protected function loadTableForeignKeys(string $tableName): array
222 38
    {
223
        /** @psalm-var mixed $tableForeignKeys */
224 38
        $tableForeignKeys = $this->loadTableConstraints($tableName, self::FOREIGN_KEYS);
225
        return is_array($tableForeignKeys) ? $tableForeignKeys : [];
226
    }
227
228
    /**
229
     * @throws Exception
230
     * @throws InvalidConfigException
231
     * @throws NotSupportedException
232
     * @throws Throwable
233
     */
234
    protected function loadTableIndexes(string $tableName): array
235 38
    {
236
        $sql = <<<SQL
237 38
        SELECT "ui"."INDEX_NAME" AS "name", "uicol"."COLUMN_NAME" AS "column_name",
238 38
        CASE "ui"."UNIQUENESS" WHEN 'UNIQUE' THEN 1 ELSE 0 END AS "index_is_unique",
239 38
        CASE WHEN "uc"."CONSTRAINT_NAME" IS NOT NULL THEN 1 ELSE 0 END AS "index_is_primary"
240 38
        FROM "SYS"."USER_INDEXES" "ui"
241 38
        LEFT JOIN "SYS"."USER_IND_COLUMNS" "uicol"
242
        ON "uicol"."INDEX_NAME" = "ui"."INDEX_NAME"
243
        LEFT JOIN "SYS"."USER_CONSTRAINTS" "uc"
244 38
        ON "uc"."OWNER" = "ui"."TABLE_OWNER" AND "uc"."CONSTRAINT_NAME" = "ui"."INDEX_NAME" AND "uc"."CONSTRAINT_TYPE" = 'P'
245 38
        WHERE "ui"."TABLE_OWNER" = :schemaName AND "ui"."TABLE_NAME" = :tableName
246
        ORDER BY "uicol"."COLUMN_POSITION" ASC
247 38
        SQL;
248
249
        $resolvedName = $this->resolveTableName($tableName);
250
        $indexes = $this->db->createCommand($sql, [
251
            ':schemaName' => $resolvedName->getSchemaName(),
252
            ':tableName' => $resolvedName->getName(),
253 38
        ])->queryAll();
254 35
255
        /** @psalm-var array[] $indexes */
256 35
        $indexes = $this->normalizeRowKeyCase($indexes, true);
257 20
        $indexes = DbArrayHelper::index($indexes, null, ['name']);
258
259
        $result = [];
260 35
261 35
        /**
262 35
         * @psalm-var object|string|null $name
263 35
         * @psalm-var array[] $index
264 35
         */
265
        foreach ($indexes as $name => $index) {
266
            $columnNames = DbArrayHelper::getColumn($index, 'column_name');
267 38
268
            if ($columnNames[0] === null) {
269
                $columnNames[0] = '';
270
            }
271
272
            $result[] = (new IndexConstraint())
273
                ->primary((bool) $index[0]['index_is_primary'])
274
                ->unique((bool) $index[0]['index_is_unique'])
275
                ->name($name)
276 17
                ->columnNames($columnNames);
277
        }
278
279 17
        return $result;
280 17
    }
281
282
    /**
283
     * @throws Exception
284
     * @throws InvalidConfigException
285
     * @throws NotSupportedException
286
     * @throws Throwable
287
     */
288
    protected function loadTableUniques(string $tableName): array
289 17
    {
290
        /** @psalm-var mixed $tableUniques */
291
        $tableUniques = $this->loadTableConstraints($tableName, self::UNIQUES);
292 17
        return is_array($tableUniques) ? $tableUniques : [];
293 17
    }
294
295
    /**
296
     * @throws Exception
297
     * @throws InvalidConfigException
298
     * @throws NotSupportedException
299 13
     * @throws Throwable
300
     */
301 13
    protected function loadTableChecks(string $tableName): array
302
    {
303
        /** @psalm-var mixed $tableCheck */
304
        $tableCheck = $this->loadTableConstraints($tableName, self::CHECKS);
305
        return is_array($tableCheck) ? $tableCheck : [];
306
    }
307
308
    /**
309
     * @throws NotSupportedException If this method is called.
310
     */
311
    protected function loadTableDefaultValues(string $tableName): array
312
    {
313
        throw new NotSupportedException(__METHOD__ . ' is not supported by Oracle.');
314 146
    }
315
316 146
    /**
317
     * Collects the table column metadata.
318
     *
319
     * @param TableSchemaInterface $table The table schema.
320
     *
321
     * @throws Exception
322
     * @throws Throwable
323
     *
324
     * @return bool Whether the table exists.
325
     */
326
    protected function findColumns(TableSchemaInterface $table): bool
327
    {
328
        $sql = <<<SQL
329
        SELECT
330
            A.COLUMN_NAME,
331
            A.DATA_TYPE,
332
            A.DATA_PRECISION,
333
            A.DATA_SCALE,
334
            A.IDENTITY_COLUMN,
335
            (
336
            CASE A.CHAR_USED WHEN 'C' THEN A.CHAR_LENGTH
337
                ELSE A.DATA_LENGTH
338
            END
339
            ) AS DATA_LENGTH,
340
            A.NULLABLE,
341
            A.DATA_DEFAULT,
342
            (
343
                SELECT COUNT(*)
344
                FROM ALL_CONSTRAINTS AC
345
                INNER JOIN ALL_CONS_COLUMNS ACC ON ACC.CONSTRAINT_NAME=AC.CONSTRAINT_NAME
346
                WHERE
347
                     AC.OWNER = A.OWNER
348 146
                   AND AC.TABLE_NAME = B.OBJECT_NAME
349
                   AND ACC.COLUMN_NAME = A.COLUMN_NAME
350 146
                   AND AC.CONSTRAINT_TYPE = 'P'
351 146
            ) AS IS_PK,
352 146
            COM.COMMENTS AS COLUMN_COMMENT
353 146
        FROM ALL_TAB_COLUMNS A
354
            INNER JOIN ALL_OBJECTS B ON B.OWNER = A.OWNER AND LTRIM(B.OBJECT_NAME) = LTRIM(A.TABLE_NAME)
355 146
            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)
356 33
        WHERE
357
            A.OWNER = :schemaName
358
            AND B.OBJECT_TYPE IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW')
359
            AND B.OBJECT_NAME = :tableName
360 129
        ORDER BY A.COLUMN_ID
361 129
        SQL;
362
363
        $columns = $this->db->createCommand($sql, [
364
            ':tableName' => $table->getName(),
365
            ':schemaName' => $table->getSchemaName(),
366
        ])->queryAll();
367
368
        if ($columns === []) {
369
            return false;
370
        }
371
372
        /** @psalm-var ColumnInfoArray $info */
373
        foreach ($columns as $info) {
374
            /** @psalm-var ColumnInfoArray $info */
375
            $info = $this->normalizeRowKeyCase($info, false);
376 129
377
            $column = $this->loadColumnSchema($info);
378 129
379
            $table->column($column->getName(), $column);
380
        }
381 129
382
        return true;
383
    }
384
385
    /**
386
     * Sequence name of table.
387
     *
388
     * @throws Exception
389
     * @throws InvalidConfigException
390
     * @throws Throwable
391
     *
392
     * @return bool|float|int|string|null Whether the sequence exists.
393
     *
394
     * @internal TableSchemaInterface `$table->getName()` The table schema.
395 79
     */
396
    protected function getTableSequenceName(string $tableName): bool|float|int|string|null
397 79
    {
398
        $sequenceNameSql = <<<SQL
399
        SELECT
400
            UD.REFERENCED_NAME AS SEQUENCE_NAME
401
        FROM USER_DEPENDENCIES UD
402
            JOIN USER_TRIGGERS UT ON (UT.TRIGGER_NAME = UD.NAME)
403
        WHERE
404
            UT.TABLE_NAME = :tableName
405
            AND UD.TYPE = 'TRIGGER'
406 79
            AND UD.REFERENCED_TYPE = 'SEQUENCE'
407 79
        SQL;
408
        $sequenceName = $this->db->createCommand($sequenceNameSql, [':tableName' => $tableName])->queryScalar();
409 79
410
        return $sequenceName === false ? null : $sequenceName;
411
    }
412
413
    /**
414
     * Loads the column information into a {@see ColumnSchemaInterface} object.
415
     *
416
     * @param array $info The column information.
417
     *
418
     * @return ColumnSchemaInterface The column schema object.
419
     *
420
     * @psalm-param ColumnInfoArray $info The column information.
421
     */
422
    private function loadColumnSchema(array $info): ColumnSchemaInterface
423
    {
424
        $dbType = $info['data_type'];
425
        $type = $this->extractColumnType($dbType, $info);
426
        /** @psalm-var ColumnInfoArray $info */
427 129
        $column = $this->createColumnSchema($type, $info['column_name']);
0 ignored issues
show
Bug introduced by
The method createColumnSchema() does not exist on Yiisoft\Db\Oracle\Schema. Did you maybe mean createColumn()? ( Ignorable by Annotation )

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

427
        /** @scrutinizer ignore-call */ 
428
        $column = $this->createColumnSchema($type, $info['column_name']);

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

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

Loading history...
428
        $column->allowNull($info['nullable'] === 'Y');
429 129
        $column->comment($info['column_comment']);
430 129
        $column->primaryKey((bool) $info['is_pk']);
431 129
        $column->autoIncrement($info['identity_column'] === 'YES');
432 129
        $column->size((int) $info['data_length']);
433
        $column->precision($info['data_precision'] !== null ? (int) $info['data_precision'] : null);
434 129
        $column->scale($info['data_scale'] !== null ? (int) $info['data_scale'] : null);
435 129
        $column->dbType($dbType);
436 129
        $column->phpType($this->getColumnPhpType($type));
0 ignored issues
show
Bug introduced by
$type of type string is incompatible with the type Yiisoft\Db\Schema\ColumnSchemaInterface expected by parameter $column of Yiisoft\Db\Schema\Abstra...ema::getColumnPhpType(). ( Ignorable by Annotation )

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

436
        $column->phpType($this->getColumnPhpType(/** @scrutinizer ignore-type */ $type));
Loading history...
437 129
        $column->defaultValue($this->normalizeDefaultValue($info['data_default'], $column));
438 129
439 129
        return $column;
440 129
    }
441
442 129
    protected function createPhpTypeColumnSchema(string $phpType, string $name): ColumnSchemaInterface
443 129
    {
444 129
        if ($phpType === self::PHP_TYPE_RESOURCE) {
445 129
            return new BinaryColumnSchema($name);
446 129
        }
447 129
448 129
        return parent::createPhpTypeColumnSchema($phpType, $name);
449
    }
450 129
451
    /**
452 129
     * Converts column's default value according to {@see ColumnSchema::phpType} after retrieval from the database.
453 125
     *
454 121
     * @param string|null $defaultValue The default value retrieved from the database.
455
     * @param ColumnSchemaInterface $column The column schema object.
456 71
     *
457
     * @return mixed The normalized default value.
458 71
     */
459
    private function normalizeDefaultValue(string|null $defaultValue, ColumnSchemaInterface $column): mixed
460
    {
461
        if ($defaultValue === null || $column->isPrimaryKey()) {
462 71
            return null;
463 71
        }
464 71
465
        $defaultValue = trim($defaultValue);
466 25
467
        if ($defaultValue === 'NULL') {
468 71
            return null;
469
        }
470
471 71
        if ($column->getType() === self::TYPE_TIMESTAMP && $defaultValue === 'CURRENT_TIMESTAMP') {
472
            return new Expression($defaultValue);
473
        }
474
475
        if (preg_match("/^'(.*)'$/s", $defaultValue, $matches) === 1) {
476 129
            $defaultValue = str_replace("''", "'", $matches[1]);
477
        }
478
479
        return $column->phpTypecast($defaultValue);
480
    }
481
482
    /**
483
     * Finds constraints and fills them into TableSchemaInterface object passed.
484
     *
485
     * @throws Exception
486
     * @throws InvalidConfigException
487
     * @throws Throwable
488 129
     *
489
     * @psalm-suppress PossiblyNullArrayOffset
490 129
     */
491
    protected function findConstraints(TableSchemaInterface $table): void
492
    {
493
        $sql = <<<SQL
494
        SELECT
495
            /*+ PUSH_PRED(C) PUSH_PRED(D) PUSH_PRED(E) */
496
            D.CONSTRAINT_NAME,
497
            D.CONSTRAINT_TYPE,
498
            C.COLUMN_NAME,
499
            C.POSITION,
500
            D.R_CONSTRAINT_NAME,
501
            E.TABLE_NAME AS TABLE_REF,
502
            F.COLUMN_NAME AS COLUMN_REF,
503
            C.TABLE_NAME
504
        FROM ALL_CONS_COLUMNS C
505
            INNER JOIN ALL_CONSTRAINTS D ON D.OWNER = C.OWNER AND D.CONSTRAINT_NAME = C.CONSTRAINT_NAME
506
            LEFT JOIN ALL_CONSTRAINTS E ON E.OWNER = D.R_OWNER AND E.CONSTRAINT_NAME = D.R_CONSTRAINT_NAME
507
            LEFT JOIN ALL_CONS_COLUMNS F ON F.OWNER = E.OWNER AND F.CONSTRAINT_NAME = E.CONSTRAINT_NAME AND F.POSITION = C.POSITION
508
        WHERE
509 129
            C.OWNER = :schemaName
510
            AND C.TABLE_NAME = :tableName
511
            ORDER BY D.CONSTRAINT_NAME, C.POSITION
512
        SQL;
513
514
        /**
515
         * @psalm-var array{
516
         *   array{
517
         *     constraint_name: string,
518
         *     constraint_type: string,
519
         *     column_name: string,
520
         *     position: string|null,
521
         *     r_constraint_name: string|null,
522
         *     table_ref: string|null,
523
         *     column_ref: string|null,
524
         *     table_name: string
525 129
         *   }
526 129
         * } $rows
527 129
         */
528 129
        $rows = $this->db->createCommand(
529
            $sql,
530 129
            [':tableName' => $table->getName(), ':schemaName' => $table->getSchemaName()]
531
        )->queryAll();
532 129
533
        $constraints = [];
534 118
535
        foreach ($rows as $row) {
536 118
            /** @psalm-var string[] $row */
537 79
            $row = $this->normalizeRowKeyCase($row, false);
538 79
539
            if ($row['constraint_type'] === 'P') {
540 79
                $table->getColumns()[$row['column_name']]->primaryKey(true);
541 79
                $table->primaryKey($row['column_name']);
542
543
                if (empty($table->getSequenceName())) {
544
                    $table->sequenceName((string) $this->getTableSequenceName($table->getName()));
545 118
                }
546
            }
547
548
            if ($row['constraint_type'] !== 'R') {
549
                /**
550
                 * This condition isn't checked in `WHERE` because of an Oracle Bug:
551 118
                 *
552
                 * @link https://github.com/yiisoft/yii2/pull/8844
553
                 */
554 14
                continue;
555
            }
556 14
557 14
            $name = $row['constraint_name'];
558 14
559 14
            if (!isset($constraints[$name])) {
560 14
                $constraints[$name] = [
561
                    'tableName' => $row['table_ref'],
562
                    'columns' => [],
563 14
                ];
564
            }
565
566 129
            $constraints[$name]['columns'][$row['column_name']] = $row['column_ref'];
567 14
        }
568
569
        foreach ($constraints as $index => $constraint) {
570
            $table->foreignKey($index, array_merge([$constraint['tableName']], $constraint['columns']));
571
        }
572
    }
573
574
    /**
575
     * Returns all unique indexes for the given table.
576
     *
577
     * Each array element is of the following structure:.
578
     *
579
     * ```php
580
     * [
581
     *     'IndexName1' => ['col1' [, ...]],
582
     *     'IndexName2' => ['col2' [, ...]],
583
     * ]
584
     * ```
585
     *
586
     * @param TableSchemaInterface $table The table metadata.
587
     *
588
     * @throws Exception
589
     * @throws InvalidConfigException
590
     * @throws Throwable
591 1
     *
592
     * @return array All unique indexes for the given table.
593 1
     */
594
    public function findUniqueIndexes(TableSchemaInterface $table): array
595
    {
596
        $query = <<<SQL
597
        SELECT
598
            DIC.INDEX_NAME,
599
            DIC.COLUMN_NAME
600
        FROM ALL_INDEXES DI
601
            INNER JOIN ALL_IND_COLUMNS DIC ON DI.TABLE_NAME = DIC.TABLE_NAME AND DI.INDEX_NAME = DIC.INDEX_NAME
602
        WHERE
603
            DI.UNIQUENESS = 'UNIQUE'
604 1
            AND DIC.TABLE_OWNER = :schemaName
605 1
            AND DIC.TABLE_NAME = :tableName
606
        ORDER BY DIC.TABLE_NAME, DIC.INDEX_NAME, DIC.COLUMN_POSITION
607 1
        SQL;
608 1
        $result = [];
609 1
610 1
        $rows = $this->db->createCommand(
611
            $query,
612
            [':tableName' => $table->getName(), ':schemaName' => $table->getschemaName()]
613 1
        )->queryAll();
614 1
615
        /** @psalm-var array<array{INDEX_NAME: string, COLUMN_NAME: string}> $rows */
616
        foreach ($rows as $row) {
617 1
            $result[$row['INDEX_NAME']][] = $row['COLUMN_NAME'];
618
        }
619
620
        return $result;
621
    }
622
623
    /**
624
     * Extracts the data type for the given column.
625
     *
626
     * @param string $dbType The database data type
627
     * @param array $info Column information.
628 129
     * @psalm-param ColumnInfoArray $info
629
     *
630
     * @return string The abstract column type.
631
     */
632
    private function extractColumnType(string $dbType, array $info): string
633
    {
634
        $dbType = explode('(', $dbType, 2)[0];
635 129
636
        return match ($dbType) {
637 129
            'FLOAT', 'DOUBLE' => self::TYPE_DOUBLE,
638 28
            'NUMBER' => $info['data_scale'] === null || $info['data_scale'] > 0
639 129
                ? self::TYPE_DECIMAL
640 121
                : self::TYPE_INTEGER,
641 31
            'BLOB' => self::TYPE_BINARY,
642
            'CLOB' => self::TYPE_TEXT,
643 121
            'TIMESTAMP' => self::TYPE_TIMESTAMP,
644
            default => self::TYPE_STRING,
645 97
        };
646 30
    }
647 93
648 24
    /**
649 92
     * Loads multiple types of constraints and returns the specified ones.
650 26
     *
651
     * @param string $tableName The table name.
652 92
     * @param string $returnType The return type:
653
     * - primaryKey
654
     * - foreignKeys
655
     * - uniques
656
     * - checks
657
     *
658
     * @throws Exception
659
     * @throws InvalidConfigException
660
     * @throws NotSupportedException
661
     * @throws Throwable
662
     *
663
     * @return mixed Constraints.
664 129
     */
665
    private function loadTableConstraints(string $tableName, string $returnType): mixed
666
    {
667
        $sql = <<<SQL
668
        SELECT
669
            "uc"."CONSTRAINT_NAME" AS "name",
670
            "uccol"."COLUMN_NAME" AS "column_name",
671 129
            "uc"."CONSTRAINT_TYPE" AS "type",
672 129
            "fuc"."OWNER" AS "foreign_table_schema",
673 129
            "fuc"."TABLE_NAME" AS "foreign_table_name",
674
            "fuccol"."COLUMN_NAME" AS "foreign_column_name",
675
            "uc"."DELETE_RULE" AS "on_delete",
676
            "uc"."SEARCH_CONDITION" AS "check_expr"
677
        FROM "USER_CONSTRAINTS" "uc"
678
        INNER JOIN "USER_CONS_COLUMNS" "uccol"
679
        ON "uccol"."OWNER" = "uc"."OWNER" AND "uccol"."CONSTRAINT_NAME" = "uc"."CONSTRAINT_NAME"
680
        LEFT JOIN "USER_CONSTRAINTS" "fuc"
681
        ON "fuc"."OWNER" = "uc"."R_OWNER" AND "fuc"."CONSTRAINT_NAME" = "uc"."R_CONSTRAINT_NAME"
682
        LEFT JOIN "USER_CONS_COLUMNS" "fuccol"
683
        ON "fuccol"."OWNER" = "fuc"."OWNER" AND "fuccol"."CONSTRAINT_NAME" = "fuc"."CONSTRAINT_NAME" AND "fuccol"."POSITION" = "uccol"."POSITION"
684
        WHERE "uc"."OWNER" = :schemaName AND "uc"."TABLE_NAME" = :tableName
685
        ORDER BY "uccol"."POSITION" ASC
686
        SQL;
687
688
        $resolvedName = $this->resolveTableName($tableName);
689
        $constraints = $this->db->createCommand($sql, [
690
            ':schemaName' => $resolvedName->getSchemaName(),
691
            ':tableName' => $resolvedName->getName(),
692
        ])->queryAll();
693 89
694
        /** @psalm-var array[] $constraints */
695 89
        $constraints = $this->normalizeRowKeyCase($constraints, true);
696
        $constraints = DbArrayHelper::index($constraints, null, ['type', 'name']);
697
698
        $result = [
699
            self::PRIMARY_KEY => null,
700
            self::FOREIGN_KEYS => [],
701
            self::UNIQUES => [],
702
            self::CHECKS => [],
703
        ];
704
705
        /**
706
         * @psalm-var string $type
707
         * @psalm-var array $names
708
         */
709
        foreach ($constraints as $type => $names) {
710
            /**
711
             * @psalm-var object|string|null $name
712
             * @psalm-var ConstraintArray $constraint
713
             */
714 89
            foreach ($names as $name => $constraint) {
715
                switch ($type) {
716 89
                    case 'P':
717 89
                        $result[self::PRIMARY_KEY] = (new Constraint())
718 89
                            ->name($name)
719 89
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'));
720 89
                        break;
721
                    case 'R':
722
                        $result[self::FOREIGN_KEYS][] = (new ForeignKeyConstraint())
723 89
                            ->name($name)
724 89
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'))
725
                            ->foreignSchemaName($constraint[0]['foreign_table_schema'])
726 89
                            ->foreignTableName($constraint[0]['foreign_table_name'])
727 89
                            ->foreignColumnNames(DbArrayHelper::getColumn($constraint, 'foreign_column_name'))
728 89
                            ->onDelete($constraint[0]['on_delete'])
729 89
                            ->onUpdate(null);
730 89
                        break;
731 89
                    case 'U':
732
                        $result[self::UNIQUES][] = (new Constraint())
733
                            ->name($name)
734
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'));
735
                        break;
736
                    case 'C':
737 89
                        $result[self::CHECKS][] = (new CheckConstraint())
738
                            ->name($name)
739
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'))
740
                            ->expression($constraint[0]['check_expr']);
741
                        break;
742 82
                }
743
            }
744 82
        }
745 57
746 57
        foreach ($result as $type => $data) {
747 57
            $this->setTableMetadata($tableName, $type, $data);
748 57
        }
749 82
750 19
        return $result[$returnType];
751 19
    }
752 19
753 19
    /**
754 19
     * @throws Exception
755 19
     * @throws InvalidConfigException
756 19
     * @throws Throwable
757 19
     */
758 19
    protected function findViewNames(string $schema = ''): array
759 82
    {
760 58
        $sql = match ($schema) {
761 58
            '' => <<<SQL
762 58
            SELECT VIEW_NAME FROM USER_VIEWS
763 58
            SQL,
764 82
            default => <<<SQL
765 82
            SELECT VIEW_NAME FROM ALL_VIEWS WHERE OWNER = '$schema'
766 82
            SQL,
767 82
        };
768 82
769 82
        /** @psalm-var string[][] $views */
770
        $views = $this->db->createCommand($sql)->queryAll();
771
772
        foreach ($views as $key => $view) {
773
            $views[$key] = $view['VIEW_NAME'];
774 89
        }
775 89
776
        return $views;
777
    }
778 89
779
    /**
780
     * Returns the cache key for the specified table name.
781
     *
782
     * @param string $name The table name.
783
     *
784
     * @return array The cache key.
785
     */
786 2
    protected function getCacheKey(string $name): array
787
    {
788 2
        return array_merge([self::class], $this->generateCacheKey(), [$this->getRawTableName($name)]);
789 2
    }
790
791 2
    /**
792 2
     * Returns the cache tag name.
793 2
     *
794 2
     * This allows {@see refresh()} to invalidate all cached table schemas.
795 2
     *
796
     * @return string The cache tag name.
797
     */
798 2
    protected function getCacheTag(): string
799
    {
800 2
        return md5(serialize(array_merge([self::class], $this->generateCacheKey())));
801 2
    }
802
}
803