Passed
Pull Request — master (#86)
by Def
46:32 queued 15:35
created

Schema::resolveTableNames()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0987

Importance

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

628
        /** @scrutinizer ignore-unused */ ?string $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...
629
        ?string $scale,
630
        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

630
        /** @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...
631
    ): void {
632 75
        $column->dbType($dbType);
633
634 75
        if (str_contains($dbType, 'FLOAT') || str_contains($dbType, 'DOUBLE')) {
635 17
            $column->type(self::TYPE_DOUBLE);
636 75
        } elseif (str_contains($dbType, 'NUMBER')) {
637 72
            if ($scale === null || $scale > 0) {
638 18
                $column->type(self::TYPE_DECIMAL);
639
            } else {
640 72
                $column->type(self::TYPE_INTEGER);
641
            }
642 68
        } elseif (str_contains($dbType, 'INTEGER')) {
643
            $column->type(self::TYPE_INTEGER);
644 68
        } elseif (str_contains($dbType, 'BLOB')) {
645 19
            $column->type(self::TYPE_BINARY);
646 65
        } elseif (str_contains($dbType, 'CLOB')) {
647 22
            $column->type(self::TYPE_TEXT);
648 64
        } elseif (str_contains($dbType, 'TIMESTAMP')) {
649 16
            $column->type(self::TYPE_TIMESTAMP);
650
        } else {
651 64
            $column->type(self::TYPE_STRING);
652
        }
653
    }
654
655
    /**
656
     * Extracts size, precision and scale information from column's DB type.
657
     *
658
     * @param ColumnSchema $column
659
     * @param string $dbType the column's DB type.
660
     * @param string|null $precision total number of digits.
661
     * @param string|null $scale number of digits on the right of the decimal separator.
662
     * @param string $length length for character types.
663
     */
664 75
    protected function extractColumnSize(
665
        ColumnSchema $column,
666
        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

666
        /** @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...
667
        ?string $precision,
668
        ?string $scale,
669
        string $length
670
    ): void {
671 75
        $column->size(trim($length) === '' ? null : (int) $length);
672 75
        $column->precision(trim((string) $precision) === '' ? null : (int) $precision);
673 75
        $column->scale($scale === '' || $scale === null ? null : (int) $scale);
674
    }
675
676
    /**
677
     * Loads multiple types of constraints and returns the specified ones.
678
     *
679
     * @param string $tableName table name.
680
     * @param string $returnType return type:
681
     * - primaryKey
682
     * - foreignKeys
683
     * - uniques
684
     * - checks
685
     *
686
     * @throws Exception|InvalidConfigException|NotSupportedException|Throwable
687
     *
688
     * @return mixed constraints.
689
     */
690 64
    private function loadTableConstraints(string $tableName, string $returnType): mixed
691
    {
692 64
        $sql = <<<SQL
693
        SELECT
694
            "uc"."CONSTRAINT_NAME" AS "name",
695
            "uccol"."COLUMN_NAME" AS "column_name",
696
            "uc"."CONSTRAINT_TYPE" AS "type",
697
            "fuc"."OWNER" AS "foreign_table_schema",
698
            "fuc"."TABLE_NAME" AS "foreign_table_name",
699
            "fuccol"."COLUMN_NAME" AS "foreign_column_name",
700
            "uc"."DELETE_RULE" AS "on_delete",
701
            "uc"."SEARCH_CONDITION" AS "check_expr"
702
        FROM "USER_CONSTRAINTS" "uc"
703
        INNER JOIN "USER_CONS_COLUMNS" "uccol"
704
        ON "uccol"."OWNER" = "uc"."OWNER" AND "uccol"."CONSTRAINT_NAME" = "uc"."CONSTRAINT_NAME"
705
        LEFT JOIN "USER_CONSTRAINTS" "fuc"
706
        ON "fuc"."OWNER" = "uc"."R_OWNER" AND "fuc"."CONSTRAINT_NAME" = "uc"."R_CONSTRAINT_NAME"
707
        LEFT JOIN "USER_CONS_COLUMNS" "fuccol"
708
        ON "fuccol"."OWNER" = "fuc"."OWNER" AND "fuccol"."CONSTRAINT_NAME" = "fuc"."CONSTRAINT_NAME" AND "fuccol"."POSITION" = "uccol"."POSITION"
709
        WHERE "uc"."OWNER" = :schemaName AND "uc"."TABLE_NAME" = :tableName
710
        ORDER BY "uccol"."POSITION" ASC
711
        SQL;
712
713 64
        $resolvedName = $this->resolveTableName($tableName);
714
715 64
        $constraints = $this->db->createCommand($sql, [
716 64
            ':schemaName' => $resolvedName->getSchemaName(),
717 64
            ':tableName' => $resolvedName->getName(),
718 64
        ])->queryAll();
719
720
        /** @var Constraint[] $constraints */
721 64
        $constraints = $this->normalizeRowKeyCase($constraints, true);
722 64
        $constraints = ArrayHelper::index($constraints, null, ['type', 'name']);
723
724 64
        $result = [
725
            self::PRIMARY_KEY => null,
726 64
            self::FOREIGN_KEYS => [],
727 64
            self::UNIQUES => [],
728 64
            self::CHECKS => [],
729
        ];
730
731
        /**
732
         * @var string $type
733
         * @var array $names
734
         */
735 64
        foreach ($constraints as $type => $names) {
736
            /**
737
             * @psalm-var object|string|null $name
738
             * @psalm-var ConstraintArray $constraint
739
             */
740 64
            foreach ($names as $name => $constraint) {
741 64
                switch ($type) {
742 64
                    case 'P':
743 49
                        $result[self::PRIMARY_KEY] = (new Constraint())
744 49
                            ->name($name)
745 49
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'));
746 49
                        break;
747 64
                    case 'R':
748 17
                        $result[self::FOREIGN_KEYS][] = (new ForeignKeyConstraint())
749 17
                            ->name($name)
750 17
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
751 17
                            ->foreignSchemaName($constraint[0]['foreign_table_schema'])
752 17
                            ->foreignTableName($constraint[0]['foreign_table_name'])
753 17
                            ->foreignColumnNames(ArrayHelper::getColumn($constraint, 'foreign_column_name'))
754 17
                            ->onDelete($constraint[0]['on_delete'])
755 17
                            ->onUpdate(null);
756 17
                        break;
757 64
                    case 'U':
758 50
                        $result[self::UNIQUES][] = (new Constraint())
759 50
                            ->name($name)
760 50
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'));
761 50
                        break;
762 64
                    case 'C':
763 64
                        $result[self::CHECKS][] = (new CheckConstraint())
764 64
                            ->name($name)
765 64
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
766 64
                            ->expression($constraint[0]['check_expr']);
767 64
                        break;
768
                }
769
            }
770
        }
771
772 64
        foreach ($result as $type => $data) {
773 64
            $this->setTableMetadata($tableName, $type, $data);
774
        }
775
776 64
        return $result[$returnType];
777
    }
778
779
    /**
780
     * Creates a column schema for the database.
781
     *
782
     * This method may be overridden by child classes to create a DBMS-specific column schema.
783
     *
784
     * @return ColumnSchema column schema instance.
785
     */
786 75
    protected function createColumnSchema(): ColumnSchema
787
    {
788 75
        return new ColumnSchema();
789
    }
790
791
    /**
792
     * Returns the actual name of a given table name.
793
     *
794
     * This method will strip off curly brackets from the given table name and replace the percentage character '%' with
795
     * {@see ConnectionInterface::tablePrefix}.
796
     *
797
     * @param string $name the table name to be converted.
798
     *
799
     * @return string the real name of the given table name.
800
     */
801 154
    public function getRawTableName(string $name): string
802
    {
803 154
        if (str_contains($name, '{{')) {
804 21
            $name = preg_replace('/{{(.*?)}}/', '\1', $name);
805
806 21
            return str_replace('%', $this->db->getTablePrefix(), $name);
807
        }
808
809 154
        return $name;
810
    }
811
812
    /**
813
     * Returns the cache key for the specified table name.
814
     *
815
     * @param string $name the table name.
816
     *
817
     * @return array the cache key.
818
     */
819 154
    protected function getCacheKey(string $name): array
820
    {
821 154
        return array_merge([__CLASS__], $this->db->getCacheKey(), [$this->getRawTableName($name)]);
822
    }
823
824
    /**
825
     * Returns the cache tag name.
826
     *
827
     * This allows {@see refresh()} to invalidate all cached table schemas.
828
     *
829
     * @return string the cache tag name.
830
     */
831 154
    protected function getCacheTag(): string
832
    {
833 154
        return md5(serialize(array_merge([__CLASS__], $this->db->getCacheKey())));
834
    }
835
836
    /**
837
     * Changes row's array key case to lower.
838
     *
839
     * @param array $row row's array or an array of row's arrays.
840
     * @param bool $multiple whether multiple rows or a single row passed.
841
     *
842
     * @return array normalized row or rows.
843
     */
844 135
    protected function normalizeRowKeyCase(array $row, bool $multiple): array
845
    {
846 135
        if ($multiple) {
847 75
            return array_map(static function (array $row) {
848 72
                return array_change_key_case($row, CASE_LOWER);
849
            }, $row);
850
        }
851
852 82
        return array_change_key_case($row, CASE_LOWER);
853
    }
854
855
    /**
856
     * @return bool whether this DBMS supports [savepoint](http://en.wikipedia.org/wiki/Savepoint).
857
     */
858 5
    public function supportsSavepoint(): bool
859
    {
860 5
        return $this->db->isSavepointEnabled();
861
    }
862
}
863