Test Failed
Push — master ( 25811b...c24873 )
by Wilmer
10:44 queued 07:40
created

Schema::findViewNames()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 2
nop 1
dl 0
loc 19
ccs 2
cts 2
cp 1
crap 2
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Oracle;
6
7
use Throwable;
8
use Yiisoft\Arrays\ArrayHelper;
9
use Yiisoft\Db\Cache\SchemaCache;
10
use Yiisoft\Db\Connection\ConnectionInterface;
11
use Yiisoft\Db\Constraint\CheckConstraint;
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\Schema as AbstractSchema;
20
use Yiisoft\Db\Schema\TableSchemaInterface;
21
22
use function array_merge;
23
use function is_array;
24
use function md5;
25
use function serialize;
26
use function str_contains;
27
use function stripos;
28
use function strlen;
29
use function substr;
30
use function trim;
31
32
/**
33
 * Schema is the class for retrieving metadata from an Oracle database.
34
 *
35
 * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the
36
 * sequence object. This property is read-only.
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 AbstractSchema
54
{
55 476
    public function __construct(protected ConnectionInterface $db, SchemaCache $schemaCache, string $defaultSchema)
56
    {
57 476
        $this->defaultSchema = $defaultSchema;
58 476
        parent::__construct($db, $schemaCache);
59
    }
60
61 184
    protected function resolveTableName(string $name): TableSchemaInterface
62
    {
63 184
        $resolvedName = new TableSchema();
64
65 184
        $parts = array_reverse(
66 184
            $this->db->getQuoter()->getTableNameParts($name)
67
        );
68
69 184
        $resolvedName->name($parts[0] ?? '');
70 184
        $resolvedName->schemaName($parts[1] ?? $this->defaultSchema);
71
72 184
        $resolvedName->fullName(
73 184
            $resolvedName->getSchemaName() !== $this->defaultSchema ?
74 184
            implode('.', array_reverse($parts)) : $resolvedName->getName()
75
        );
76
77 184
        return $resolvedName;
78
    }
79
80
    /**
81
     * @link https://docs.oracle.com/cd/B28359_01/server.111/b28337/tdpsg_user_accounts.htm
82
     *
83 1
     * @throws Exception
84
     * @throws InvalidConfigException
85 1
     * @throws NotSupportedException
86
     * @throws Throwable
87
     */
88
    protected function findSchemaNames(): array
89
    {
90
        $sql = <<<SQL
91
        SELECT "u"."USERNAME"
92 1
        FROM "DBA_USERS" "u"
93
        WHERE "u"."DEFAULT_TABLESPACE" NOT IN ('SYSTEM', 'SYSAUX')
94
        ORDER BY "u"."USERNAME" ASC
95 124
        SQL;
96
97 124
        return $this->db->createCommand($sql)->queryColumn();
98
    }
99
100
    /**
101
     * @throws Exception
102
     * @throws InvalidConfigException
103
     * @throws Throwable
104
     */
105 124
    protected function findTableComment(TableSchemaInterface $tableSchema): void
106 124
    {
107 124
        $sql = <<<SQL
108 124
        SELECT "COMMENTS"
109
        FROM ALL_TAB_COMMENTS
110 124
        WHERE
111
              "OWNER" = :schemaName AND
112
              "TABLE_NAME" = :tableName
113
        SQL;
114
115
        $comment = $this->db->createCommand($sql, [
116
            ':schemaName' => $tableSchema->getSchemaName(),
117
            ':tableName' => $tableSchema->getName(),
118 10
        ])->queryScalar();
119
120 10
        $tableSchema->comment(is_string($comment) ? $comment : null);
121 10
    }
122
123
    /**
124
     * @throws Exception
125
     * @throws InvalidConfigException
126
     * @throws Throwable
127
     */
128
    protected function findTableNames(string $schema = ''): array
129
    {
130
        if ($schema === '') {
131
            $sql = <<<SQL
132
            SELECT TABLE_NAME
133 10
            FROM USER_TABLES
134
            UNION ALL
135
            SELECT VIEW_NAME AS TABLE_NAME
136
            FROM USER_VIEWS
137
            UNION ALL
138
            SELECT MVIEW_NAME AS TABLE_NAME
139
            FROM USER_MVIEWS
140
            ORDER BY TABLE_NAME
141
            SQL;
142
143
            $command = $this->db->createCommand($sql);
144 10
        } else {
145 10
            $sql = <<<SQL
146
            SELECT OBJECT_NAME AS TABLE_NAME
147
            FROM ALL_OBJECTS
148 10
            WHERE OBJECT_TYPE IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW') AND OWNER = :schema
149
            ORDER BY OBJECT_NAME
150 10
            SQL;
151 10
            $command = $this->db->createCommand($sql, [':schema' => $schema]);
152
        }
153
154 10
        $rows = $command->queryAll();
155
        $names = [];
156
157
        /** @psalm-var string[][] $rows */
158
        foreach ($rows as $row) {
159
            /** @psalm-var string[] $row */
160
            $row = $this->normalizeRowKeyCase($row, false);
161
            $names[] = $row['table_name'];
162 124
        }
163
164 124
        return $names;
165 124
    }
166
167 124
    /**
168 108
     * @throws Exception
169 108
     * @throws InvalidConfigException
170
     * @throws Throwable
171
     */
172 26
    protected function loadTableSchema(string $name): TableSchemaInterface|null
173
    {
174
        $table = $this->resolveTableName($name);
175
        $this->findTableComment($table);
176
177
        if ($this->findColumns($table)) {
178
            $this->findConstraints($table);
179
            return $table;
180
        }
181 40
182
        return null;
183
    }
184 40
185 40
    /**
186
     * @throws Exception
187
     * @throws InvalidConfigException
188
     * @throws NotSupportedException
189
     * @throws Throwable
190
     */
191
    protected function loadTablePrimaryKey(string $tableName): Constraint|null
192
    {
193
        /** @psalm-var mixed $tablePrimaryKey */
194 9
        $tablePrimaryKey = $this->loadTableConstraints($tableName, self::PRIMARY_KEY);
195
        return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
196
    }
197 9
198 9
    /**
199
     * @throws Exception
200
     * @throws InvalidConfigException
201
     * @throws NotSupportedException
202
     * @throws Throwable
203
     */
204
    protected function loadTableForeignKeys(string $tableName): array
205
    {
206
        /** @psalm-var mixed $tableForeingKeys */
207 31
        $tableForeingKeys = $this->loadTableConstraints($tableName, self::FOREIGN_KEYS);
208
        return is_array($tableForeingKeys) ? $tableForeingKeys : [];
209 31
    }
210
211
    /**
212
     * @throws Exception
213
     * @throws InvalidConfigException
214
     * @throws NotSupportedException
215
     * @throws Throwable
216
     */
217
    protected function loadTableIndexes(string $tableName): array
218
    {
219
        $sql = <<<SQL
220
        SELECT "ui"."INDEX_NAME" AS "name", "uicol"."COLUMN_NAME" AS "column_name",
221
        CASE "ui"."UNIQUENESS" WHEN 'UNIQUE' THEN 1 ELSE 0 END AS "index_is_unique",
222 31
        CASE WHEN "uc"."CONSTRAINT_NAME" IS NOT NULL THEN 1 ELSE 0 END AS "index_is_primary"
223
        FROM "SYS"."USER_INDEXES" "ui"
224 31
        LEFT JOIN "SYS"."USER_IND_COLUMNS" "uicol"
225 31
        ON "uicol"."INDEX_NAME" = "ui"."INDEX_NAME"
226 31
        LEFT JOIN "SYS"."USER_CONSTRAINTS" "uc"
227 31
        ON "uc"."OWNER" = "ui"."TABLE_OWNER" AND "uc"."CONSTRAINT_NAME" = "ui"."INDEX_NAME" AND "uc"."CONSTRAINT_TYPE" = 'P'
228
        WHERE "ui"."TABLE_OWNER" = :schemaName AND "ui"."TABLE_NAME" = :tableName
229
        ORDER BY "uicol"."COLUMN_POSITION" ASC
230 31
        SQL;
231 31
232
        $resolvedName = $this->resolveTableName($tableName);
233 31
234
        $indexes = $this->db->createCommand($sql, [
235
            ':schemaName' => $resolvedName->getSchemaName(),
236
            ':tableName' => $resolvedName->getName(),
237
        ])->queryAll();
238
239 31
        /** @psalm-var array[] $indexes */
240 28
        $indexes = $this->normalizeRowKeyCase($indexes, true);
241
        $indexes = ArrayHelper::index($indexes, null, 'name');
242 28
243 18
        $result = [];
244
245
        /**
246 28
         * @psalm-var object|string|null $name
247 28
         * @psalm-var array[] $index
248 28
         */
249 28
        foreach ($indexes as $name => $index) {
250 28
            $columnNames = ArrayHelper::getColumn($index, 'column_name');
251
252
            if ($columnNames[0] === null) {
253 31
                $columnNames[0] = '';
254
            }
255
256
            $result[] = (new IndexConstraint())
257
                ->primary((bool) $index[0]['index_is_primary'])
258
                ->unique((bool) $index[0]['index_is_unique'])
259
                ->name($name)
260
                ->columnNames($columnNames);
261
        }
262 17
263
        return $result;
264
    }
265 17
266 17
    /**
267
     * @throws Exception
268
     * @throws InvalidConfigException
269
     * @throws NotSupportedException
270
     * @throws Throwable
271
     */
272
    protected function loadTableUniques(string $tableName): array
273
    {
274
        /** @psalm-var mixed $tableUniques */
275 15
        $tableUniques = $this->loadTableConstraints($tableName, self::UNIQUES);
276
        return is_array($tableUniques) ? $tableUniques : [];
277
    }
278 15
279 15
    /**
280
     * @throws Exception
281
     * @throws InvalidConfigException
282
     * @throws NotSupportedException
283
     * @throws Throwable
284
     */
285 12
    protected function loadTableChecks(string $tableName): array
286
    {
287 12
        /** @psalm-var mixed $tableCheck */
288
        $tableCheck = $this->loadTableConstraints($tableName, self::CHECKS);
289
        return is_array($tableCheck) ? $tableCheck : [];
290
    }
291
292
    /**
293
     * @throws NotSupportedException if this method is called.
294
     */
295
    protected function loadTableDefaultValues(string $tableName): array
296
    {
297
        throw new NotSupportedException(__METHOD__ . ' is not supported by Oracle.');
298
    }
299
300
    /**
301
     * Create a column schema builder instance giving the type and value precision.
302 9
     *
303
     * This method may be overridden by child classes to create a DBMS-specific column schema builder.
304 9
     *
305
     * @param string $type type of the column. See {@see ColumnSchemaBuilder::$type}.
306
     * @param array|int|string|null $length length or precision of the column {@see ColumnSchemaBuilder::$length}.
307
     *
308
     * @return ColumnSchemaBuilder column schema builder instance
309
     *
310
     * @psalm-param string[]|int|string|null $length
311
     */
312
    public function createColumnSchemaBuilder(string $type, array|int|string $length = null): ColumnSchemaBuilder
313
    {
314
        return new ColumnSchemaBuilder($type, $length);
315
    }
316
317 124
    /**
318
     * Collects the table column metadata.
319 124
     *
320
     * @param TableSchemaInterface $table the table schema.
321
     *
322
     * @throws Exception
323
     * @throws Throwable
324
     *
325
     * @return bool whether the table exists.
326
     */
327
    protected function findColumns(TableSchemaInterface $table): bool
328
    {
329
        $sql = <<<SQL
330
        SELECT
331
            A.COLUMN_NAME,
332
            A.DATA_TYPE,
333
            A.DATA_PRECISION,
334
            A.DATA_SCALE,
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
            COM.COMMENTS AS COLUMN_COMMENT
343
        FROM ALL_TAB_COLUMNS A
344 124
            INNER JOIN ALL_OBJECTS B ON B.OWNER = A.OWNER AND LTRIM(B.OBJECT_NAME) = LTRIM(A.TABLE_NAME)
345 124
            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)
346 124
        WHERE
347 124
            A.OWNER = :schemaName
348
            AND B.OBJECT_TYPE IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW')
349
            AND B.OBJECT_NAME = :tableName
350
        ORDER BY A.COLUMN_ID
351
        SQL;
352 124
353 26
        $columns = $this->db->createCommand($sql, [
354
            ':tableName' => $table->getName(),
355
            ':schemaName' => $table->getSchemaName(),
356
        ])->queryAll();
357 108
358 108
        if ($columns === []) {
359
            return false;
360 108
        }
361
362 108
        /** @psalm-var string[][] $columns */
363
        foreach ($columns as $column) {
364
            $column = $this->normalizeRowKeyCase($column, false);
365 108
366
            $c = $this->createColumn($column);
367
368
            $table->columns($c->getName(), $c);
369
        }
370
371
        return true;
372
    }
373
374
    /**
375
     * Sequence name of table.
376
     *
377
     * @throws Exception
378
     * @throws InvalidConfigException
379 72
     * @throws Throwable
380
     *
381 72
     * @return bool|float|int|string|null whether the sequence exists.
382
     *
383
     * @internal TableSchemaInterface `$table->getName()` the table schema.
384
     */
385
    protected function getTableSequenceName(string $tableName): bool|float|int|string|null
386
    {
387
        $sequenceNameSql = <<<SQL
388
        SELECT
389
            UD.REFERENCED_NAME AS SEQUENCE_NAME
390
        FROM USER_DEPENDENCIES UD
391 72
            JOIN USER_TRIGGERS UT ON (UT.TRIGGER_NAME = UD.NAME)
392
        WHERE
393 72
            UT.TABLE_NAME = :tableName
394
            AND UD.TYPE = 'TRIGGER'
395
            AND UD.REFERENCED_TYPE = 'SEQUENCE'
396
        SQL;
397
        $sequenceName = $this->db->createCommand($sequenceNameSql, [':tableName' => $tableName])->queryScalar();
398
399 108
        return $sequenceName === false ? null : $sequenceName;
400
    }
401 108
402
    /**
403
     * Creates ColumnSchema instance.
404
     */
405
    protected function createColumn(array|string $column): ColumnSchema
406
    {
407
        $c = $this->createColumnSchema();
408
409
        /**
410
         * @psalm-var array{
411
         *   column_name: string,
412
         *   data_type: string,
413
         *   data_precision: string,
414
         *   data_scale: string,
415 108
         *   data_length: string,
416 108
         *   nullable: string,
417 108
         *   data_default: string|null,
418 108
         *   column_comment: string|null
419
         * } $column
420 108
         */
421
        $c->name($column['column_name']);
422 108
        $c->allowNull($column['nullable'] === 'Y');
423 108
        $c->comment($column['column_comment'] ?? '');
424 108
        $c->primaryKey(false);
425 108
426
        $this->extractColumnType(
427
            $c,
428 108
            $column['data_type'],
429
            $column['data_precision'],
430 108
            $column['data_scale'],
431 108
            $column['data_length']
432 108
        );
433 108
434
        $this->extractColumnSize(
435
            $c,
436 108
            $column['data_type'],
437
            $column['data_precision'],
438 108
            $column['data_scale'],
439 108
            $column['data_length']
440 18
        );
441
442 108
        $c->phpType($this->getColumnPhpType($c));
443
444 108
        if (!$c->isPrimaryKey()) {
445
            if ($column['data_default'] !== null && stripos($column['data_default'], 'timestamp') !== false) {
446
                $c->defaultValue(null);
447 108
            } else {
448 66
                $defaultValue = $column['data_default'];
449 66
450
                if ($c->getType() === 'timestamp' && $defaultValue === 'CURRENT_TIMESTAMP') {
451 18
                    $c->defaultValue(new Expression('CURRENT_TIMESTAMP'));
452
                } else {
453 66
                    if ($defaultValue !== null) {
454
                        if (
455
                            ($len = strlen($defaultValue)) > 2 &&
456 108
                            $defaultValue[0] === "'" &&
457
                            $defaultValue[$len - 1] === "'"
458
                        ) {
459
                            $defaultValue = substr((string) $column['data_default'], 1, -1);
460
                        } else {
461 108
                            $defaultValue = trim($defaultValue);
462
                        }
463
                    }
464
                    $c->defaultValue($c->phpTypecast($defaultValue));
465
                }
466
            }
467
        }
468
469
        return $c;
470
    }
471
472
    /**
473 108
     * Finds constraints and fills them into TableSchemaInterface object passed.
474
     *
475 108
     * @throws Exception
476
     * @throws InvalidConfigException
477
     * @throws Throwable
478
     *
479
     * @psalm-suppress PossiblyNullArrayOffset
480
     */
481
    protected function findConstraints(TableSchemaInterface $table): void
482
    {
483
        $sql = <<<SQL
484
        SELECT
485
            /*+ PUSH_PRED(C) PUSH_PRED(D) PUSH_PRED(E) */
486
            D.CONSTRAINT_NAME,
487
            D.CONSTRAINT_TYPE,
488
            C.COLUMN_NAME,
489
            C.POSITION,
490
            D.R_CONSTRAINT_NAME,
491
            E.TABLE_NAME AS TABLE_REF,
492
            F.COLUMN_NAME AS COLUMN_REF,
493
            C.TABLE_NAME
494
        FROM ALL_CONS_COLUMNS C
495
            INNER JOIN ALL_CONSTRAINTS D ON D.OWNER = C.OWNER AND D.CONSTRAINT_NAME = C.CONSTRAINT_NAME
496
            LEFT JOIN ALL_CONSTRAINTS E ON E.OWNER = D.R_OWNER AND E.CONSTRAINT_NAME = D.R_CONSTRAINT_NAME
497
            LEFT JOIN ALL_CONS_COLUMNS F ON F.OWNER = E.OWNER AND F.CONSTRAINT_NAME = E.CONSTRAINT_NAME AND F.POSITION = C.POSITION
498
        WHERE
499
            C.OWNER = :schemaName
500
            AND C.TABLE_NAME = :tableName
501
            ORDER BY D.CONSTRAINT_NAME, C.POSITION
502
        SQL;
503
504
        /**
505
         * @psalm-var array{
506
         *   array{
507
         *     constraint_name: string,
508
         *     constraint_type: string,
509
         *     column_name: string,
510 108
         *     position: string|null,
511
         *     r_constraint_name: string|null,
512 108
         *     table_ref: string|null,
513 108
         *     column_ref: string|null,
514
         *     table_name: string
515 108
         *   }
516
         * } $rows
517 108
         */
518
        $rows = $this->db->createCommand(
519 98
            $sql,
520
            [':tableName' => $table->getName(), ':schemaName' => $table->getSchemaName()]
521 98
        )->queryAll();
522 72
523 72
        $constraints = [];
524
525 72
        foreach ($rows as $row) {
526 72
            /** @psalm-var string[] $row */
527
            $row = $this->normalizeRowKeyCase($row, false);
528
529
            if ($row['constraint_type'] === 'P') {
530 98
                $table->getColumns()[$row['column_name']]->primaryKey(true);
531
                $table->primaryKey($row['column_name']);
532
533
                if (empty($table->getSequenceName())) {
534
                    $table->sequenceName((string) $this->getTableSequenceName($table->getName()));
535
                }
536 98
            }
537
538
            if ($row['constraint_type'] !== 'R') {
539 11
                /**
540
                 * This condition is not checked in SQL WHERE because of an Oracle Bug:
541 11
                 *
542 11
                 * {@see https://github.com/yiisoft/yii2/pull/8844}
543 11
                 */
544
                continue;
545
            }
546
547
            $name = $row['constraint_name'];
548 11
549
            if (!isset($constraints[$name])) {
550
                $constraints[$name] = [
551 108
                    'tableName' => $row['table_ref'],
552 11
                    'columns' => [],
553
                ];
554
            }
555
556
            $constraints[$name]['columns'][$row['column_name']] = $row['column_ref'];
557
        }
558
559
        foreach ($constraints as $index => $constraint) {
560
            $table->foreignKey($index, array_merge([$constraint['tableName']], $constraint['columns']));
561
        }
562
    }
563
564
    /**
565
     * Returns all unique indexes for the given table.
566
     *
567
     * Each array element is of the following structure:.
568
     *
569
     * ```php
570
     * [
571
     *     'IndexName1' => ['col1' [, ...]],
572
     *     'IndexName2' => ['col2' [, ...]],
573
     * ]
574
     * ```
575
     *
576 1
     * @param TableSchemaInterface $table the table metadata.
577
     *
578 1
     * @throws Exception
579
     * @throws InvalidConfigException
580
     * @throws Throwable
581
     *
582
     * @return array all unique indexes for the given table.
583
     */
584
    public function findUniqueIndexes(TableSchemaInterface $table): array
585
    {
586
        $query = <<<SQL
587
        SELECT
588
            DIC.INDEX_NAME,
589
            DIC.COLUMN_NAME
590 1
        FROM ALL_INDEXES DI
591
            INNER JOIN ALL_IND_COLUMNS DIC ON DI.TABLE_NAME = DIC.TABLE_NAME AND DI.INDEX_NAME = DIC.INDEX_NAME
592 1
        WHERE
593
            DI.UNIQUENESS = 'UNIQUE'
594 1
            AND DIC.TABLE_OWNER = :schemaName
595 1
            AND DIC.TABLE_NAME = :tableName
596
        ORDER BY DIC.TABLE_NAME, DIC.INDEX_NAME, DIC.COLUMN_POSITION
597
        SQL;
598 1
        $result = [];
599 1
600
        $rows = $this->db->createCommand(
601
            $query,
602 1
            [':tableName' => $table->getName(), ':schemaName' => $table->getschemaName()]
603
        )->queryAll();
604
605
        /** @psalm-var array<array{INDEX_NAME: string, COLUMN_NAME: string}> $rows */
606
        foreach ($rows as $row) {
607
            $result[$row['INDEX_NAME']][] = $row['COLUMN_NAME'];
608
        }
609
610
        return $result;
611
    }
612
613 108
    /**
614
     * Extracts the data types for the given column.
615
     *
616
     * @param string $dbType DB type.
617
     * @param string|null $precision total number of digits.
618
     * @param string|null $scale number of digits on the right of the decimal separator.
619
     * @param string $length length for character types.
620 108
     */
621
    protected function extractColumnType(
622 108
        ColumnSchema $column,
623 20
        string $dbType,
624 108
        string|null $precision,
0 ignored issues
show
Unused Code introduced by
The parameter $precision is not used and could be removed. ( Ignorable by Annotation )

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

624
        /** @scrutinizer ignore-unused */ string|null $precision,

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

Loading history...
625 104
        string|null $scale,
626 21
        string $length
0 ignored issues
show
Unused Code introduced by
The parameter $length is not used and could be removed. ( Ignorable by Annotation )

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

626
        /** @scrutinizer ignore-unused */ string $length

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

Loading history...
627
    ): void {
628 104
        $column->dbType($dbType);
629
630 82
        if (str_contains($dbType, 'FLOAT') || str_contains($dbType, 'DOUBLE')) {
631
            $column->type(self::TYPE_DOUBLE);
632 82
        } elseif (str_contains($dbType, 'NUMBER')) {
633 22
            if ($scale === null || $scale > 0) {
634 79
                $column->type(self::TYPE_DECIMAL);
635 22
            } else {
636 78
                $column->type(self::TYPE_INTEGER);
637 19
            }
638
        } elseif (str_contains($dbType, 'BLOB')) {
639 78
            $column->type(self::TYPE_BINARY);
640
        } elseif (str_contains($dbType, 'CLOB')) {
641
            $column->type(self::TYPE_TEXT);
642
        } elseif (str_contains($dbType, 'TIMESTAMP')) {
643
            $column->type(self::TYPE_TIMESTAMP);
644
        } else {
645
            $column->type(self::TYPE_STRING);
646
        }
647
    }
648
649
    /**
650
     * Extracts size, precision and scale information from column's DB type.
651 108
     *
652
     * @param string $dbType the column's DB type.
653
     * @param string|null $precision total number of digits.
654
     * @param string|null $scale number of digits on the right of the decimal separator.
655
     * @param string $length length for character types.
656
     */
657
    protected function extractColumnSize(
658 108
        ColumnSchema $column,
659 108
        string $dbType,
0 ignored issues
show
Unused Code introduced by
The parameter $dbType is not used and could be removed. ( Ignorable by Annotation )

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

659
        /** @scrutinizer ignore-unused */ string $dbType,

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

Loading history...
660 108
        string|null $precision,
661
        string|null $scale,
662
        string $length
663
    ): void {
664
        $column->size(trim($length) === '' ? null : (int) $length);
665
        $column->precision(trim((string) $precision) === '' ? null : (int) $precision);
666
        $column->scale($scale === '' || $scale === null ? null : (int) $scale);
667
    }
668
669
    /**
670
     * Loads multiple types of constraints and returns the specified ones.
671
     *
672
     * @param string $tableName table name.
673
     * @param string $returnType return type:
674
     * - primaryKey
675
     * - foreignKeys
676
     * - uniques
677
     * - checks
678
     *
679
     * @throws Exception
680 81
     * @throws InvalidConfigException
681
     * @throws NotSupportedException
682 81
     * @throws Throwable
683
     *
684
     * @return mixed constraints.
685
     */
686
    private function loadTableConstraints(string $tableName, string $returnType): mixed
687
    {
688
        $sql = <<<SQL
689
        SELECT
690
            "uc"."CONSTRAINT_NAME" AS "name",
691
            "uccol"."COLUMN_NAME" AS "column_name",
692
            "uc"."CONSTRAINT_TYPE" AS "type",
693
            "fuc"."OWNER" AS "foreign_table_schema",
694
            "fuc"."TABLE_NAME" AS "foreign_table_name",
695
            "fuccol"."COLUMN_NAME" AS "foreign_column_name",
696
            "uc"."DELETE_RULE" AS "on_delete",
697
            "uc"."SEARCH_CONDITION" AS "check_expr"
698
        FROM "USER_CONSTRAINTS" "uc"
699
        INNER JOIN "USER_CONS_COLUMNS" "uccol"
700
        ON "uccol"."OWNER" = "uc"."OWNER" AND "uccol"."CONSTRAINT_NAME" = "uc"."CONSTRAINT_NAME"
701
        LEFT JOIN "USER_CONSTRAINTS" "fuc"
702
        ON "fuc"."OWNER" = "uc"."R_OWNER" AND "fuc"."CONSTRAINT_NAME" = "uc"."R_CONSTRAINT_NAME"
703 81
        LEFT JOIN "USER_CONS_COLUMNS" "fuccol"
704
        ON "fuccol"."OWNER" = "fuc"."OWNER" AND "fuccol"."CONSTRAINT_NAME" = "fuc"."CONSTRAINT_NAME" AND "fuccol"."POSITION" = "uccol"."POSITION"
705 81
        WHERE "uc"."OWNER" = :schemaName AND "uc"."TABLE_NAME" = :tableName
706 81
        ORDER BY "uccol"."POSITION" ASC
707 81
        SQL;
708 81
709
        $resolvedName = $this->resolveTableName($tableName);
710
711 81
        $constraints = $this->db->createCommand($sql, [
712 81
            ':schemaName' => $resolvedName->getSchemaName(),
713
            ':tableName' => $resolvedName->getName(),
714 81
        ])->queryAll();
715
716
        /** @var Constraint[] $constraints */
717
        $constraints = $this->normalizeRowKeyCase($constraints, true);
718
        $constraints = ArrayHelper::index($constraints, null, ['type', 'name']);
719
720
        $result = [
721
            self::PRIMARY_KEY => null,
722
            self::FOREIGN_KEYS => [],
723
            self::UNIQUES => [],
724
            self::CHECKS => [],
725 81
        ];
726
727
        /**
728
         * @var string $type
729
         * @var array $names
730 74
         */
731
        foreach ($constraints as $type => $names) {
732 74
            /**
733 52
             * @psalm-var object|string|null $name
734 52
             * @psalm-var ConstraintArray $constraint
735 52
             */
736 52
            foreach ($names as $name => $constraint) {
737 74
                switch ($type) {
738 21
                    case 'P':
739 21
                        $result[self::PRIMARY_KEY] = (new Constraint())
740 21
                            ->name($name)
741 21
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'));
742 21
                        break;
743 21
                    case 'R':
744 21
                        $result[self::FOREIGN_KEYS][] = (new ForeignKeyConstraint())
745 21
                            ->name($name)
746 21
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
747 74
                            ->foreignSchemaName($constraint[0]['foreign_table_schema'])
748 56
                            ->foreignTableName($constraint[0]['foreign_table_name'])
749 56
                            ->foreignColumnNames(ArrayHelper::getColumn($constraint, 'foreign_column_name'))
750 56
                            ->onDelete($constraint[0]['on_delete'])
751 56
                            ->onUpdate(null);
752 74
                        break;
753 74
                    case 'U':
754 74
                        $result[self::UNIQUES][] = (new Constraint())
755 74
                            ->name($name)
756 74
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'));
757 74
                        break;
758
                    case 'C':
759
                        $result[self::CHECKS][] = (new CheckConstraint())
760
                            ->name($name)
761
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
762 81
                            ->expression($constraint[0]['check_expr']);
763 81
                        break;
764
                }
765
            }
766 81
        }
767
768
        foreach ($result as $type => $data) {
769
            $this->setTableMetadata($tableName, $type, $data);
770
        }
771
772
        return $result[$returnType];
773
    }
774
775
    /**
776 108
     * Creates a column schema for the database.
777
     *
778 108
     * This method may be overridden by child classes to create a DBMS-specific column schema.
779
     *
780
     * @return ColumnSchema column schema instance.
781
     */
782
    protected function createColumnSchema(): ColumnSchema
783
    {
784
        return new ColumnSchema();
785
    }
786
787
    /**
788 196
     * @throws Exception
789
     * @throws InvalidConfigException
790 196
     * @throws Throwable
791
     */
792
    protected function findViewNames(string $schema = ''): array
793
    {
794
        $sql = match ($schema) {
795
            '' => <<<SQL
796
            SELECT VIEW_NAME FROM USER_VIEWS
797
            SQL,
798
            default => <<<SQL
799
            SELECT VIEW_NAME FROM ALL_VIEWS WHERE OWNER = '$schema'
800 196
            SQL,
801
        };
802 196
803
        /** @psalm-var string[][] $views */
804
        $views = $this->db->createCommand($sql)->queryAll();
805
806
        foreach ($views as $key => $view) {
807
            $views[$key] = $view['VIEW_NAME'];
808
        }
809
810
        return $views;
811
    }
812
813
    /**
814
     * Returns the cache key for the specified table name.
815
     *
816
     * @param string $name the table name.
817
     *
818
     * @return array the cache key.
819
     */
820
    protected function getCacheKey(string $name): array
821
    {
822
        return array_merge([self::class], $this->db->getCacheKey(), [$this->getRawTableName($name)]);
823
    }
824
825
    /**
826
     * Returns the cache tag name.
827
     *
828
     * This allows {@see refresh()} to invalidate all cached table schemas.
829
     *
830
     * @return string the cache tag name.
831
     */
832
    protected function getCacheTag(): string
833
    {
834
        return md5(serialize(array_merge([self::class], $this->db->getCacheKey())));
835
    }
836
}
837