Test Failed
Pull Request — master (#315)
by Sergei
02:45
created

Schema::loadTableConstraints()   B

Complexity

Conditions 8
Paths 14

Size

Total Lines 109
Code Lines 81

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 58
CRAP Score 8

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 8
eloc 81
c 3
b 0
f 0
nc 14
nop 2
dl 0
loc 109
ccs 58
cts 58
cp 1
crap 8
rs 7.1701

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Pgsql;
6
7
use JsonException;
8
use Throwable;
9
use Yiisoft\Db\Constraint\CheckConstraint;
10
use Yiisoft\Db\Constraint\Constraint;
11
use Yiisoft\Db\Constraint\DefaultValueConstraint;
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\Pgsql\Column\ArrayColumnSchema;
21
use Yiisoft\Db\Pgsql\Column\BinaryColumnSchema;
22
use Yiisoft\Db\Pgsql\Column\BitColumnSchema;
23
use Yiisoft\Db\Pgsql\Column\BooleanColumnSchema;
24
use Yiisoft\Db\Pgsql\Column\IntegerColumnSchema;
25
use Yiisoft\Db\Pgsql\Column\IntegerColumnSchemaInterface;
26
use Yiisoft\Db\Schema\Builder\ColumnInterface;
27
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...
28
use Yiisoft\Db\Schema\TableSchemaInterface;
29
30
use function array_merge;
31
use function array_unique;
32
use function array_values;
33
use function explode;
34
use function is_string;
35
use function preg_match;
36
use function preg_replace;
37
use function str_replace;
38
use function str_starts_with;
39
use function substr;
40
41
/**
42
 * Implements the PostgreSQL Server specific schema, supporting PostgreSQL Server version 9.6 and above.
43
 *
44
 * @psalm-type ColumnArray = array{
45
 *   table_schema: string,
46
 *   table_name: string,
47
 *   column_name: string,
48
 *   data_type: string,
49
 *   type_type: string|null,
50
 *   type_scheme: string|null,
51
 *   character_maximum_length: int,
52
 *   column_comment: string|null,
53
 *   modifier: int,
54
 *   is_nullable: bool,
55
 *   column_default: string|null,
56
 *   is_autoinc: bool,
57
 *   sequence_name: string|null,
58
 *   enum_values: string|null,
59
 *   numeric_precision: int|null,
60
 *   numeric_scale: int|null,
61
 *   size: string|null,
62
 *   is_pkey: bool|null,
63
 *   dimension: int
64
 * }
65
 * @psalm-type ConstraintArray = array<
66
 *   array-key,
67
 *   array {
68
 *     name: string,
69
 *     column_name: string,
70
 *     type: string,
71
 *     foreign_table_schema: string|null,
72
 *     foreign_table_name: string|null,
73
 *     foreign_column_name: string|null,
74
 *     on_update: string,
75
 *     on_delete: string,
76
 *     check_expr: string
77
 *   }
78
 * >
79
 * @psalm-type FindConstraintArray = array{
80
 *   constraint_name: string,
81
 *   column_name: string,
82
 *   foreign_table_name: string,
83
 *   foreign_table_schema: string,
84
 *   foreign_column_name: string,
85
 * }
86
 */
87
final class Schema extends AbstractPdoSchema
88
{
89
    /**
90
     * Define the abstract column type as `bit`.
91
     */
92
    public const TYPE_BIT = 'bit';
93
94
    /**
95
     * @var array The mapping from physical column types (keys) to abstract column types (values).
96
     *
97
     * @link https://www.postgresql.org/docs/current/static/datatype.html#DATATYPE-TABLE
98
     *
99
     * @psalm-var string[]
100
     */
101
    private array $typeMap = [
102
        'bit' => self::TYPE_BIT,
103
        'bit varying' => self::TYPE_BIT,
104
        'varbit' => self::TYPE_BIT,
105
        'bool' => self::TYPE_BOOLEAN,
106
        'boolean' => self::TYPE_BOOLEAN,
107
        'box' => self::TYPE_STRING,
108
        'circle' => self::TYPE_STRING,
109
        'point' => self::TYPE_STRING,
110
        'line' => self::TYPE_STRING,
111
        'lseg' => self::TYPE_STRING,
112
        'polygon' => self::TYPE_STRING,
113
        'path' => self::TYPE_STRING,
114
        'character' => self::TYPE_CHAR,
115
        'char' => self::TYPE_CHAR,
116
        'bpchar' => self::TYPE_CHAR,
117
        'character varying' => self::TYPE_STRING,
118
        'varchar' => self::TYPE_STRING,
119
        'text' => self::TYPE_TEXT,
120
        'bytea' => self::TYPE_BINARY,
121
        'cidr' => self::TYPE_STRING,
122
        'inet' => self::TYPE_STRING,
123
        'macaddr' => self::TYPE_STRING,
124
        'real' => self::TYPE_FLOAT,
125
        'float4' => self::TYPE_FLOAT,
126
        'double precision' => self::TYPE_DOUBLE,
127
        'float8' => self::TYPE_DOUBLE,
128
        'decimal' => self::TYPE_DECIMAL,
129
        'numeric' => self::TYPE_DECIMAL,
130
        'money' => self::TYPE_MONEY,
131
        'smallint' => self::TYPE_SMALLINT,
132
        'int2' => self::TYPE_SMALLINT,
133
        'int4' => self::TYPE_INTEGER,
134
        'int' => self::TYPE_INTEGER,
135
        'integer' => self::TYPE_INTEGER,
136
        'bigint' => self::TYPE_BIGINT,
137
        'int8' => self::TYPE_BIGINT,
138
        'oid' => self::TYPE_BIGINT, // shouldn't be used. it's pg internal!
139
        'smallserial' => self::TYPE_SMALLINT,
140
        'serial2' => self::TYPE_SMALLINT,
141
        'serial4' => self::TYPE_INTEGER,
142
        'serial' => self::TYPE_INTEGER,
143
        'bigserial' => self::TYPE_BIGINT,
144
        'serial8' => self::TYPE_BIGINT,
145
        'pg_lsn' => self::TYPE_BIGINT,
146
        'date' => self::TYPE_DATE,
147
        'interval' => self::TYPE_STRING,
148
        'time without time zone' => self::TYPE_TIME,
149
        'time' => self::TYPE_TIME,
150
        'time with time zone' => self::TYPE_TIME,
151
        'timetz' => self::TYPE_TIME,
152
        'timestamp without time zone' => self::TYPE_TIMESTAMP,
153
        'timestamp' => self::TYPE_TIMESTAMP,
154
        'timestamp with time zone' => self::TYPE_TIMESTAMP,
155
        'timestamptz' => self::TYPE_TIMESTAMP,
156
        'abstime' => self::TYPE_TIMESTAMP,
157
        'tsquery' => self::TYPE_STRING,
158
        'tsvector' => self::TYPE_STRING,
159
        'txid_snapshot' => self::TYPE_STRING,
160
        'unknown' => self::TYPE_STRING,
161
        'uuid' => self::TYPE_STRING,
162
        'json' => self::TYPE_JSON,
163
        'jsonb' => self::TYPE_JSON,
164
        'xml' => self::TYPE_STRING,
165
    ];
166
167
    /**
168
     * @var string|null The default schema used for the current session.
169
     */
170
    protected string|null $defaultSchema = 'public';
171
172
    /**
173
     * @var string|string[] Character used to quote schema, table, etc. names.
174 14
     *
175
     * An array of 2 characters can be used in case starting and ending characters are different.
176 14
     */
177
    protected string|array $tableQuoteCharacter = '"';
178
179
    public function createColumn(string $type, array|int|string $length = null): ColumnInterface
180
    {
181
        return new Column($type, $length);
182
    }
183
184
    /**
185
     * Resolves the table name and schema name (if any).
186
     *
187
     * @param string $name The table name.
188 233
     *
189
     * @return TableSchemaInterface With resolved table, schema, etc. names.
190 233
     *
191
     * @see TableSchemaInterface
192 233
     */
193 233
    protected function resolveTableName(string $name): TableSchemaInterface
194 233
    {
195
        $resolvedName = new TableSchema();
196 233
197 233
        $parts = array_reverse($this->db->getQuoter()->getTableNameParts($name));
198 233
        $resolvedName->name($parts[0] ?? '');
199 233
        $resolvedName->schemaName($parts[1] ?? $this->defaultSchema);
200
201 233
        $resolvedName->fullName(
202
            $resolvedName->getSchemaName() !== $this->defaultSchema ?
203
            implode('.', array_reverse($parts)) : $resolvedName->getName()
204
        );
205
206
        return $resolvedName;
207
    }
208
209
    /**
210
     * Returns all schema names in the database, including the default one but not system schemas.
211
     *
212
     * This method should be overridden by child classes to support this feature because the default implementation
213
     * simply throws an exception.
214
     *
215
     * @throws Exception
216 1
     * @throws InvalidConfigException
217
     * @throws Throwable
218 1
     *
219
     * @return array All schemas name in the database, except system schemas.
220
     */
221
    protected function findSchemaNames(): array
222
    {
223 1
        $sql = <<<SQL
224
        SELECT "ns"."nspname"
225 1
        FROM "pg_namespace" AS "ns"
226
        WHERE "ns"."nspname" != 'information_schema' AND "ns"."nspname" NOT LIKE 'pg_%'
227
        ORDER BY "ns"."nspname" ASC
228
        SQL;
229
230
        return $this->db->createCommand($sql)->queryColumn();
231
    }
232
233 181
    /**
234
     * @throws Exception
235 181
     * @throws InvalidConfigException
236
     * @throws Throwable
237
     */
238
    protected function findTableComment(TableSchemaInterface $tableSchema): void
239
    {
240
        $sql = <<<SQL
241
        SELECT obj_description(pc.oid, 'pg_class')
242 181
        FROM pg_catalog.pg_class pc
243
        INNER JOIN pg_namespace pn ON pc.relnamespace = pn.oid
244 181
        WHERE
245 181
        pc.relname=:tableName AND
246 181
        pn.nspname=:schemaName
247 181
        SQL;
248
249 181
        $comment = $this->db->createCommand($sql, [
250
            ':schemaName' => $tableSchema->getSchemaName(),
251
            ':tableName' => $tableSchema->getName(),
252
        ])->queryScalar();
253
254
        $tableSchema->comment(is_string($comment) ? $comment : null);
255
    }
256
257
    /**
258
     * Returns all table names in the database.
259
     *
260
     * This method should be overridden by child classes to support this feature because the default implementation
261
     * simply throws an exception.
262
     *
263
     * @param string $schema The schema of the tables.
264
     * Defaults to empty string, meaning the current or default schema.
265
     *
266
     * @throws Exception
267 12
     * @throws InvalidConfigException
268
     * @throws Throwable
269 12
     *
270 11
     * @return array All tables name in the database. The names have NO schema name prefix.
271
     */
272
    protected function findTableNames(string $schema = ''): array
273 12
    {
274
        if ($schema === '') {
275
            $schema = $this->defaultSchema;
276
        }
277
278
        $sql = <<<SQL
279 12
        SELECT c.relname AS table_name
280
        FROM pg_class c
281 12
        INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace
282
        WHERE ns.nspname = :schemaName AND c.relkind IN ('r','v','m','f', 'p')
283
        ORDER BY c.relname
284
        SQL;
285
286
        return $this->db->createCommand($sql, [':schemaName' => $schema])->queryColumn();
287
    }
288
289
    /**
290
     * Loads the metadata for the specified table.
291
     *
292
     * @param string $name The table name.
293
     *
294
     * @throws Exception
295 181
     * @throws InvalidConfigException
296
     * @throws Throwable
297 181
     *
298 181
     * @return TableSchemaInterface|null DBMS-dependent table metadata, `null` if the table doesn't exist.
299
     */
300 181
    protected function loadTableSchema(string $name): TableSchemaInterface|null
301 159
    {
302 159
        $table = $this->resolveTableName($name);
303
        $this->findTableComment($table);
304
305 43
        if ($this->findColumns($table)) {
306
            $this->findConstraints($table);
307
            return $table;
308
        }
309
310
        return null;
311
    }
312
313
    /**
314
     * Loads a primary key for the given table.
315
     *
316
     * @param string $tableName The table name.
317
     *
318
     * @throws Exception
319 40
     * @throws InvalidConfigException
320
     * @throws Throwable
321 40
     *
322
     * @return Constraint|null Primary key for the given table, `null` if the table has no primary key.
323 40
     */
324
    protected function loadTablePrimaryKey(string $tableName): Constraint|null
325
    {
326
        $tablePrimaryKey = $this->loadTableConstraints($tableName, self::PRIMARY_KEY);
327
328
        return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
329
    }
330
331
    /**
332
     * Loads all foreign keys for the given table.
333
     *
334
     * @param string $tableName The table name.
335
     *
336
     * @throws Exception
337
     * @throws InvalidConfigException
338
     * @throws Throwable
339 8
     *
340
     * @return array Foreign keys for the given table.
341 8
     *
342
     * @psaml-return array|ForeignKeyConstraint[]
343 8
     */
344
    protected function loadTableForeignKeys(string $tableName): array
345
    {
346
        $tableForeignKeys = $this->loadTableConstraints($tableName, self::FOREIGN_KEYS);
347
348
        return is_array($tableForeignKeys) ? $tableForeignKeys : [];
349
    }
350
351
    /**
352
     * Loads all indexes for the given table.
353
     *
354
     * @param string $tableName The table name.
355
     *
356
     * @throws Exception
357 38
     * @throws InvalidConfigException
358
     * @throws Throwable
359 38
     *
360
     * @return IndexConstraint[] Indexes for the given table.
361
     */
362
    protected function loadTableIndexes(string $tableName): array
363
    {
364
        $sql = <<<SQL
365
        SELECT
366
            "ic"."relname" AS "name",
367
            "ia"."attname" AS "column_name",
368
            "i"."indisunique" AS "index_is_unique",
369
            "i"."indisprimary" AS "index_is_primary"
370
        FROM "pg_class" AS "tc"
371
        INNER JOIN "pg_namespace" AS "tcns"
372
            ON "tcns"."oid" = "tc"."relnamespace"
373
        INNER JOIN "pg_index" AS "i"
374
            ON "i"."indrelid" = "tc"."oid"
375
        INNER JOIN "pg_class" AS "ic"
376 38
            ON "ic"."oid" = "i"."indexrelid"
377
        INNER JOIN "pg_attribute" AS "ia"
378 38
            ON "ia"."attrelid" = "i"."indexrelid"
379 38
        WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName
380 38
        ORDER BY "ia"."attnum" ASC
381 38
        SQL;
382 38
383
        $resolvedName = $this->resolveTableName($tableName);
384
        $indexes = $this->db->createCommand($sql, [
385 38
            ':schemaName' => $resolvedName->getSchemaName(),
386 38
            ':tableName' => $resolvedName->getName(),
387 38
        ])->queryAll();
388
389
        /** @psalm-var array[] $indexes */
390
        $indexes = $this->normalizeRowKeyCase($indexes, true);
391
        $indexes = DbArrayHelper::index($indexes, null, ['name']);
392
        $result = [];
393
394
        /**
395
         * @psalm-var object|string|null $name
396
         * @psalm-var array<
397
         *   array-key,
398
         *   array{
399
         *     name: string,
400
         *     column_name: string,
401 38
         *     index_is_unique: bool,
402 35
         *     index_is_primary: bool
403 35
         *   }
404 35
         * > $index
405 35
         */
406 35
        foreach ($indexes as $name => $index) {
407
            $ic = (new IndexConstraint())
408 35
                ->name($name)
409
                ->columnNames(DbArrayHelper::getColumn($index, 'column_name'))
410
                ->primary($index[0]['index_is_primary'])
411 38
                ->unique($index[0]['index_is_unique']);
412
413
            $result[] = $ic;
414
        }
415
416
        return $result;
417
    }
418
419
    /**
420
     * Loads all unique constraints for the given table.
421
     *
422
     * @param string $tableName The table name.
423
     *
424
     * @throws Exception
425
     * @throws InvalidConfigException
426
     * @throws Throwable
427 17
     *
428
     * @return array Unique constraints for the given table.
429 17
     *
430
     * @psalm-return array|Constraint[]
431 17
     */
432
    protected function loadTableUniques(string $tableName): array
433
    {
434
        $tableUniques = $this->loadTableConstraints($tableName, self::UNIQUES);
435
436
        return is_array($tableUniques) ? $tableUniques : [];
437
    }
438
439
    /**
440
     * Loads all check constraints for the given table.
441
     *
442
     * @param string $tableName The table name.
443
     *
444
     * @throws Exception
445
     * @throws InvalidConfigException
446
     * @throws Throwable
447 17
     *
448
     * @return array Check constraints for the given table.
449 17
     *
450
     * @psaml-return array|CheckConstraint[]
451 17
     */
452
    protected function loadTableChecks(string $tableName): array
453
    {
454
        $tableChecks = $this->loadTableConstraints($tableName, self::CHECKS);
455
456
        return is_array($tableChecks) ? $tableChecks : [];
457
    }
458
459
    /**
460
     * Loads all default value constraints for the given table.
461
     *
462
     * @param string $tableName The table name.
463 13
     *
464
     * @throws NotSupportedException
465 13
     *
466
     * @return DefaultValueConstraint[] Default value constraints for the given table.
467
     */
468
    protected function loadTableDefaultValues(string $tableName): array
469
    {
470
        throw new NotSupportedException(__METHOD__ . ' is not supported by PostgreSQL.');
471
    }
472
473 3
    /**
474
     * @throws Exception
475 3
     * @throws InvalidConfigException
476 1
     * @throws Throwable
477
     */
478
    protected function findViewNames(string $schema = ''): array
479 3
    {
480
        if ($schema === '') {
481
            $schema = $this->defaultSchema;
482
        }
483
484
        $sql = <<<SQL
485 3
        SELECT c.relname AS table_name
486
        FROM pg_class c
487 3
        INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace
488
        WHERE ns.nspname = :schemaName AND (c.relkind = 'v' OR c.relkind = 'm')
489
        ORDER BY c.relname
490
        SQL;
491
492
        return $this->db->createCommand($sql, [':schemaName' => $schema])->queryColumn();
493
    }
494
495
    /**
496
     * Collects the foreign key column details for the given table.
497
     *
498
     * @param TableSchemaInterface $table The table metadata
499 159
     *
500
     * @throws Exception
501
     * @throws InvalidConfigException
502
     * @throws Throwable
503
     */
504
    protected function findConstraints(TableSchemaInterface $table): void
505
    {
506 159
        /**
507
         * We need to extract the constraints de hard way since:
508
         * {@see https://www.postgresql.org/message-id/[email protected]}
509
         */
510
511
        $sql = <<<SQL
512
        SELECT
513
            ct.conname as constraint_name,
514
            a.attname as column_name,
515
            fc.relname as foreign_table_name,
516
            fns.nspname as foreign_table_schema,
517
            fa.attname as foreign_column_name
518
            FROM
519
            (SELECT ct.conname, ct.conrelid, ct.confrelid, ct.conkey, ct.contype, ct.confkey,
520
                generate_subscripts(ct.conkey, 1) AS s
521
                FROM pg_constraint ct
522
            ) AS ct
523
            inner join pg_class c on c.oid=ct.conrelid
524
            inner join pg_namespace ns on c.relnamespace=ns.oid
525
            inner join pg_attribute a on a.attrelid=ct.conrelid and a.attnum = ct.conkey[ct.s]
526
            left join pg_class fc on fc.oid=ct.confrelid
527
            left join pg_namespace fns on fc.relnamespace=fns.oid
528
            left join pg_attribute fa on fa.attrelid=ct.confrelid and fa.attnum = ct.confkey[ct.s]
529
        WHERE
530 159
            ct.contype='f'
531
            and c.relname=:tableName
532
            and ns.nspname=:schemaName
533 159
        ORDER BY
534
            fns.nspname, fc.relname, a.attnum
535
        SQL;
536 159
537 159
        /** @psalm-var array{array{tableName: string, columns: array}} $constraints */
538 159
        $constraints = [];
539 159
540
        /** @psalm-var array<FindConstraintArray> $rows */
541 159
        $rows = $this->db->createCommand($sql, [
542
            ':schemaName' => $table->getSchemaName(),
543 16
            ':tableName' => $table->getName(),
544
        ])->queryAll();
545 16
546 3
        foreach ($rows as $constraint) {
547
            /** @psalm-var FindConstraintArray $constraint */
548 16
            $constraint = $this->normalizeRowKeyCase($constraint, false);
549
550
            if ($constraint['foreign_table_schema'] !== $this->defaultSchema) {
551 16
                $foreignTable = $constraint['foreign_table_schema'] . '.' . $constraint['foreign_table_name'];
552
            } else {
553 16
                $foreignTable = $constraint['foreign_table_name'];
554 16
            }
555 16
556 16
            $name = $constraint['constraint_name'];
557 16
558
            if (!isset($constraints[$name])) {
559
                $constraints[$name] = [
560 16
                    'tableName' => $foreignTable,
561
                    'columns' => [],
562
                ];
563
            }
564
565
            $constraints[$name]['columns'][$constraint['column_name']] = $constraint['foreign_column_name'];
566
        }
567 159
568 16
        /**
569 16
         * @psalm-var int|string $foreingKeyName.
570 16
         * @psalm-var array{tableName: string, columns: array} $constraint
571 16
         */
572
        foreach ($constraints as $foreingKeyName => $constraint) {
573
            $table->foreignKey(
574
                (string) $foreingKeyName,
575
                array_merge([$constraint['tableName']], $constraint['columns'])
576
            );
577
        }
578
    }
579
580
    /**
581
     * Gets information about given table unique indexes.
582
     *
583
     * @param TableSchemaInterface $table The table metadata.
584
     *
585
     * @throws Exception
586 1
     * @throws InvalidConfigException
587
     * @throws Throwable
588 1
     *
589
     * @return array With index and column names.
590
     */
591
    protected function getUniqueIndexInformation(TableSchemaInterface $table): array
592
    {
593
        $sql = <<<'SQL'
594
        SELECT
595
            i.relname as indexname,
596
            pg_get_indexdef(idx.indexrelid, k + 1, TRUE) AS columnname
597
        FROM (
598
            SELECT *, generate_subscripts(indkey, 1) AS k
599
            FROM pg_index
600
        ) idx
601
        INNER JOIN pg_class i ON i.oid = idx.indexrelid
602 1
        INNER JOIN pg_class c ON c.oid = idx.indrelid
603
        INNER JOIN pg_namespace ns ON c.relnamespace = ns.oid
604 1
        WHERE idx.indisprimary = FALSE AND idx.indisunique = TRUE
605 1
        AND c.relname = :tableName AND ns.nspname = :schemaName
606 1
        ORDER BY i.relname, k
607 1
        SQL;
608
609
        return $this->db->createCommand($sql, [
610
            ':schemaName' => $table->getSchemaName(),
611
            ':tableName' => $table->getName(),
612
        ])->queryAll();
613
    }
614
615
    /**
616
     * Returns all unique indexes for the given table.
617
     *
618
     * Each array element is of the following structure:
619
     *
620
     * ```php
621
     * [
622
     *     'IndexName1' => ['col1' [, ...]],
623
     *     'IndexName2' => ['col2' [, ...]],
624
     * ]
625
     * ```
626
     *
627
     * @param TableSchemaInterface $table The table metadata
628
     *
629
     * @throws Exception
630 1
     * @throws InvalidConfigException
631
     * @throws Throwable
632 1
     *
633
     * @return array All unique indexes for the given table.
634
     */
635 1
    public function findUniqueIndexes(TableSchemaInterface $table): array
636
    {
637 1
        $uniqueIndexes = [];
638
639 1
        /** @psalm-var array{indexname: string, columnname: string} $row */
640
        foreach ($this->getUniqueIndexInformation($table) as $row) {
641 1
            /** @psalm-var array{indexname: string, columnname: string} $row */
642
            $row = $this->normalizeRowKeyCase($row, false);
643
644
            $column = $row['columnname'];
645
646
            if (str_starts_with($column, '"') && str_ends_with($column, '"')) {
647 1
                /**
648
                 * postgres will quote names that aren't lowercase-only.
649
                 *
650 1
                 * {@see https://github.com/yiisoft/yii2/issues/10613}
651
                 */
652
                $column = substr($column, 1, -1);
653 1
            }
654
655
            $uniqueIndexes[$row['indexname']][] = $column;
656
        }
657
658
        return $uniqueIndexes;
659
    }
660
661
    /**
662
     * Collects the metadata of table columns.
663
     *
664
     * @param TableSchemaInterface $table The table metadata.
665
     *
666
     * @throws Exception
667
     * @throws InvalidConfigException
668 181
     * @throws JsonException
669
     * @throws Throwable
670 181
     *
671
     * @return bool Whether the table exists in the database.
672 181
     */
673 174
    protected function findColumns(TableSchemaInterface $table): bool
674
    {
675
        $orIdentity = '';
676 181
677 181
        if (version_compare($this->db->getServerVersion(), '12.0', '>=')) {
678
            $orIdentity = 'OR a.attidentity != \'\'';
679
        }
680
681
        $sql = <<<SQL
682
        SELECT
683
            d.nspname AS table_schema,
684
            c.relname AS table_name,
685
            a.attname AS column_name,
686
            COALESCE(td.typname, tb.typname, t.typname) AS data_type,
687
            COALESCE(td.typtype, tb.typtype, t.typtype) AS type_type,
688
            (SELECT nspname FROM pg_namespace WHERE oid = COALESCE(td.typnamespace, tb.typnamespace, t.typnamespace)) AS type_scheme,
689 181
            a.attlen AS character_maximum_length,
690
            pg_catalog.col_description(c.oid, a.attnum) AS column_comment,
691
            information_schema._pg_truetypmod(a, t) AS modifier,
692
            NOT (a.attnotnull OR t.typnotnull) AS is_nullable,
693
            COALESCE(t.typdefault, pg_get_expr(ad.adbin, ad.adrelid)) AS column_default,
694
            COALESCE(pg_get_expr(ad.adbin, ad.adrelid) ~ 'nextval', false) $orIdentity AS is_autoinc,
695
            pg_get_serial_sequence(quote_ident(d.nspname) || '.' || quote_ident(c.relname), a.attname)
696
            AS sequence_name,
697
            CASE WHEN COALESCE(td.typtype, tb.typtype, t.typtype) = 'e'::char
698
                THEN array_to_string(
699
                    (
700
                        SELECT array_agg(enumlabel)
701
                        FROM pg_enum
702
                        WHERE enumtypid = COALESCE(td.oid, tb.oid, a.atttypid)
703
                    )::varchar[],
704
                ',')
705
                ELSE NULL
706
            END AS enum_values,
707
            information_schema._pg_numeric_precision(
708
                COALESCE(td.oid, tb.oid, a.atttypid),
709
                information_schema._pg_truetypmod(a, t)
710
            ) AS numeric_precision,
711
            information_schema._pg_numeric_scale(
712
                COALESCE(td.oid, tb.oid, a.atttypid),
713
                information_schema._pg_truetypmod(a, t)
714
            ) AS numeric_scale,
715
            information_schema._pg_char_max_length(
716
                COALESCE(td.oid, tb.oid, a.atttypid),
717
                information_schema._pg_truetypmod(a, t)
718
            ) AS size,
719
            a.attnum = any (ct.conkey) as is_pkey,
720
            COALESCE(NULLIF(a.attndims, 0), NULLIF(t.typndims, 0), (t.typcategory='A')::int) AS dimension
721
        FROM
722
            pg_class c
723
            LEFT JOIN pg_attribute a ON a.attrelid = c.oid
724
            LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum
725
            LEFT JOIN pg_type t ON a.atttypid = t.oid
726
            LEFT JOIN pg_type tb ON (a.attndims > 0 OR t.typcategory='A') AND t.typelem > 0 AND t.typelem = tb.oid
727
                                        OR t.typbasetype > 0 AND t.typbasetype = tb.oid
728
            LEFT JOIN pg_type td ON t.typndims > 0 AND t.typbasetype > 0 AND tb.typelem = td.oid
729
            LEFT JOIN pg_namespace d ON d.oid = c.relnamespace
730
            LEFT JOIN pg_constraint ct ON ct.conrelid = c.oid AND ct.contype = 'p'
731
        WHERE
732 181
            a.attnum > 0 AND t.typname != '' AND NOT a.attisdropped
733
            AND c.relname = :tableName
734 181
            AND d.nspname = :schemaName
735 181
        ORDER BY
736 181
            a.attnum;
737 181
        SQL;
738
739 181
        $columns = $this->db->createCommand($sql, [
740 43
            ':schemaName' => $table->getSchemaName(),
741
            ':tableName' => $table->getName(),
742
        ])->queryAll();
743
744 159
        if (empty($columns)) {
745
            return false;
746 159
        }
747
748
        /** @psalm-var ColumnArray $info */
749 159
        foreach ($columns as $info) {
750
            /** @psalm-var ColumnArray $info */
751 159
            $info = $this->normalizeRowKeyCase($info, false);
752
753 159
            $column = $this->loadColumnSchema($info);
754 98
755
            $table->column($column->getName(), $column);
756 98
757 98
            if ($column->isPrimaryKey()) {
758
                $table->primaryKey($column->getName());
759
760
                if ($table->getSequenceName() === null && ($column instanceof IntegerColumnSchemaInterface)) {
761
                    $table->sequenceName($column->getSequenceName());
762 159
                }
763
            }
764
        }
765
766
        return true;
767
    }
768
769
    /**
770
     * Loads the column information into a {@see ColumnSchemaInterface} object.
771
     *
772 159
     * @psalm-param ColumnArray $info Column information.
773
     *
774 159
     * @return ColumnSchemaInterface The column schema object.
775 159
     */
776 159
    private function loadColumnSchema(array $info): ColumnSchemaInterface
777 159
    {
778
        $dbType = $info['data_type'];
779 159
780 1
        if (!in_array($info['type_scheme'], [$this->defaultSchema, 'pg_catalog'], true)) {
781
            $dbType = $info['type_scheme'] . '.' . $dbType;
782 159
        }
783
784
        $type = $this->typeMap[$dbType] ?? self::TYPE_STRING;
785 159
786 1
        $column = $this->createColumnSchema($type, $info['column_name'], dimension: $info['dimension']);
787 159
        $column->dbType($dbType);
788 159
        $column->allowNull($info['is_nullable']);
789 159
        $column->autoIncrement($info['is_autoinc']);
790 159
        $column->comment($info['column_comment']);
791 159
        $column->enumValues($info['enum_values'] !== null
792 159
            ? explode(',', str_replace(["''"], ["'"], $info['enum_values']))
793 159
            : null);
794
        $column->primaryKey((bool) $info['is_pkey']);
795
        $column->precision($info['numeric_precision']);
796
        $column->scale($info['numeric_scale']);
797
        $column->size($info['size'] === null ? null : (int) $info['size']);
798
799 159
        /**
800
         * pg_get_serial_sequence() doesn't track DEFAULT value change.
801
         * GENERATED BY IDENTITY columns always have a null default value.
802 159
         */
803 159
        $defaultValue = $info['column_default'];
804
805 81
        if ($column instanceof IntegerColumnSchemaInterface) {
806 159
            if (
807 5
                $defaultValue !== null
808
                && preg_match("/^nextval\('([^']+)/", $defaultValue, $matches) === 1
809
            ) {
810 159
                $column->sequenceName($matches[1]);
811 159
            } elseif ($info['sequence_name'] !== null) {
812 159
                $column->sequenceName($this->resolveTableName($info['sequence_name'])->getFullName());
813
            }
814 159
        }
815
816
        $column->defaultValue($this->normalizeDefaultValue($defaultValue, $column));
817
818
        return $column;
819
    }
820
821
    protected function getColumnPhpType(string $type): string
822
    {
823
        if ($type === self::TYPE_BIT) {
824 159
            return self::PHP_TYPE_INTEGER;
825
        }
826 159
827 34
        return parent::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

827
        return parent::getColumnPhpType(/** @scrutinizer ignore-type */ $type);
Loading history...
828
    }
829
830 159
    protected function createPhpTypeColumnSchema(string $phpType, string $name): ColumnSchemaInterface
831
    {
832
        return match ($phpType) {
833
            self::PHP_TYPE_INTEGER => new IntegerColumnSchema($name),
834
            self::PHP_TYPE_BOOLEAN => new BooleanColumnSchema($name),
835
            self::PHP_TYPE_RESOURCE => new BinaryColumnSchema($name),
836
            default => parent::createPhpTypeColumnSchema($phpType, $name),
837
        };
838
    }
839
840
    /**
841 159
     * Converts column's default value according to {@see ColumnSchema::phpType} after retrieval from the database.
842
     *
843
     * @param string|null $defaultValue The default value retrieved from the database.
844 159
     * @param ColumnSchemaInterface $column The column schema object.
845 123
     *
846 159
     * @return mixed The normalized default value.
847
     */
848 155
    private function normalizeDefaultValue(string|null $defaultValue, ColumnSchemaInterface $column): mixed
849
    {
850
        if (
851 94
            $defaultValue === null
852 66
            || $column->isPrimaryKey()
853
            || str_starts_with($defaultValue, 'NULL::')
854
        ) {
855
            return null;
856 93
        }
857 93
858
        if ($column->getType() === self::TYPE_BOOLEAN && in_array($defaultValue, ['true', 'false'], true)) {
859 34
            return $defaultValue === 'true';
860
        }
861
862 93
        if (
863 93
            in_array($column->getType(), [self::TYPE_TIMESTAMP, self::TYPE_DATE, self::TYPE_TIME], true)
864
            && in_array(strtoupper($defaultValue), ['NOW()', 'CURRENT_TIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIME'], true)
865 93
        ) {
866 34
            return new Expression($defaultValue);
867
        }
868
869 93
        $value = preg_replace("/^B?['(](.*?)[)'](?:::[^:]+)?$/s", '$1', $defaultValue);
870
        $value = str_replace("''", "'", $value);
871
872
        if ($column->getType() === self::TYPE_BINARY && str_starts_with($value, '\\x')) {
873
            return hex2bin(substr($value, 2));
874
        }
875
876
        return $column->phpTypecast($value);
877
    }
878
879
    /**
880
     * Loads multiple types of constraints and returns the specified ones.
881
     *
882
     * @param string $tableName The table name.
883
     * @param string $returnType The return type:
884
     * - primaryKey
885
     * - foreignKeys
886
     * - uniques
887
     * - checks
888
     *
889
     * @throws Exception
890 82
     * @throws InvalidConfigException
891
     * @throws Throwable
892 82
     *
893
     * @return array|Constraint|null Constraints.
894
     *
895
     * @psalm-return CheckConstraint[]|Constraint[]|ForeignKeyConstraint[]|Constraint|null
896
     */
897
    private function loadTableConstraints(string $tableName, string $returnType): array|Constraint|null
898
    {
899
        $sql = <<<SQL
900
        SELECT
901
            "c"."conname" AS "name",
902
            "a"."attname" AS "column_name",
903
            "c"."contype" AS "type",
904
            "ftcns"."nspname" AS "foreign_table_schema",
905
            "ftc"."relname" AS "foreign_table_name",
906
            "fa"."attname" AS "foreign_column_name",
907
            "c"."confupdtype" AS "on_update",
908
            "c"."confdeltype" AS "on_delete",
909
            pg_get_constraintdef("c"."oid") AS "check_expr"
910
        FROM "pg_class" AS "tc"
911
        INNER JOIN "pg_namespace" AS "tcns"
912
            ON "tcns"."oid" = "tc"."relnamespace"
913
        INNER JOIN "pg_constraint" AS "c"
914
            ON "c"."conrelid" = "tc"."oid"
915
        INNER JOIN "pg_attribute" AS "a"
916
            ON "a"."attrelid" = "c"."conrelid" AND "a"."attnum" = ANY ("c"."conkey")
917
        LEFT JOIN "pg_class" AS "ftc"
918 82
            ON "ftc"."oid" = "c"."confrelid"
919
        LEFT JOIN "pg_namespace" AS "ftcns"
920
            ON "ftcns"."oid" = "ftc"."relnamespace"
921 82
        LEFT JOIN "pg_attribute" "fa"
922 82
            ON "fa"."attrelid" = "c"."confrelid" AND "fa"."attnum" = ANY ("c"."confkey")
923 82
        WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName
924 82
        ORDER BY "a"."attnum" ASC, "fa"."attnum" ASC
925 82
        SQL;
926 82
927 82
        /** @psalm-var string[] $actionTypes */
928
        $actionTypes = [
929 82
            'a' => 'NO ACTION',
930 82
            'r' => 'RESTRICT',
931 82
            'c' => 'CASCADE',
932 82
            'n' => 'SET NULL',
933 82
            'd' => 'SET DEFAULT',
934
        ];
935
936 82
        $resolvedName = $this->resolveTableName($tableName);
937 82
        $constraints = $this->db->createCommand($sql, [
938
            ':schemaName' => $resolvedName->getSchemaName(),
939 82
            ':tableName' => $resolvedName->getName(),
940 82
        ])->queryAll();
941 82
942 82
        /** @psalm-var array[][] $constraints */
943 82
        $constraints = $this->normalizeRowKeyCase($constraints, true);
944 82
        $constraints = DbArrayHelper::index($constraints, null, ['type', 'name']);
945
946
        $result = [
947
            self::PRIMARY_KEY => null,
948
            self::FOREIGN_KEYS => [],
949
            self::UNIQUES => [],
950 82
            self::CHECKS => [],
951
        ];
952
953
        /**
954
         * @psalm-var string $type
955 82
         * @psalm-var array $names
956
         */
957 82
        foreach ($constraints as $type => $names) {
958 57
            /**
959 57
             * @psalm-var object|string|null $name
960 57
             * @psalm-var ConstraintArray $constraint
961 57
             */
962 74
            foreach ($names as $name => $constraint) {
963 19
                switch ($type) {
964 19
                    case 'p':
965
                        $result[self::PRIMARY_KEY] = (new Constraint())
966 19
                            ->name($name)
967 19
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'));
968 19
                        break;
969 19
                    case 'f':
970 19
                        $onDelete = $actionTypes[$constraint[0]['on_delete']] ?? null;
971 19
                        $onUpdate = $actionTypes[$constraint[0]['on_update']] ?? null;
972 19
973 19
                        $result[self::FOREIGN_KEYS][] = (new ForeignKeyConstraint())
974 19
                            ->name($name)
975 19
                            ->columnNames(array_values(
976 19
                                array_unique(DbArrayHelper::getColumn($constraint, 'column_name'))
977 19
                            ))
978 19
                            ->foreignSchemaName($constraint[0]['foreign_table_schema'])
979 61
                            ->foreignTableName($constraint[0]['foreign_table_name'])
980 58
                            ->foreignColumnNames(array_values(
981 58
                                array_unique(DbArrayHelper::getColumn($constraint, 'foreign_column_name'))
982 58
                            ))
983 58
                            ->onDelete($onDelete)
984 15
                            ->onUpdate($onUpdate);
985 15
                        break;
986 15
                    case 'u':
987 15
                        $result[self::UNIQUES][] = (new Constraint())
988 15
                            ->name($name)
989 15
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'));
990
                        break;
991
                    case 'c':
992
                        $result[self::CHECKS][] = (new CheckConstraint())
993
                            ->name($name)
994 82
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'))
995 82
                            ->expression($constraint[0]['check_expr']);
996
                        break;
997
                }
998 82
            }
999
        }
1000
1001
        foreach ($result as $type => $data) {
1002
            $this->setTableMetadata($tableName, $type, $data);
1003
        }
1004
1005
        return $result[$returnType];
1006
    }
1007
1008
    protected function createColumnSchema(string $type, string $name, bool|int ...$info): ColumnSchemaInterface
1009
    {
1010 159
        $dimension = (int) $info['dimension'];
1011
        $phpType = $this->getColumnPhpType($type);
1012 159
1013
        if ($dimension > 0) {
1014
            $column = new ArrayColumnSchema($name);
1015
            $column->dimension($dimension);
1016
        } elseif ($type === self::TYPE_BIT) {
1017
            $column = new BitColumnSchema($name);
1018
        } else {
1019
            return parent::createColumnSchema($type, $name);
0 ignored issues
show
Bug introduced by
The method createColumnSchema() does not exist on Yiisoft\Db\Driver\Pdo\AbstractPdoSchema. 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

1019
            return parent::/** @scrutinizer ignore-call */ createColumnSchema($type, $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...
1020
        }
1021
1022 272
        $column->type($type);
1023
        $column->phpType($phpType);
1024 272
1025
        return $column;
1026
    }
1027
1028
    /**
1029
     * Returns the cache key for the specified table name.
1030
     *
1031
     * @param string $name The table name.
1032
     *
1033
     * @return array The cache key.
1034 234
     */
1035
    protected function getCacheKey(string $name): array
1036 234
    {
1037
        return array_merge([self::class], $this->generateCacheKey(), [$this->getRawTableName($name)]);
1038
    }
1039
1040
    /**
1041
     * Returns the cache tag name.
1042
     *
1043
     * This allows {@see refresh()} to invalidate all cached table schemas.
1044
     *
1045
     * @return string The cache tag name.
1046
     */
1047
    protected function getCacheTag(): string
1048
    {
1049
        return md5(serialize(array_merge([self::class], $this->generateCacheKey())));
1050
    }
1051
}
1052