Passed
Pull Request — master (#303)
by Sergei
03:52
created

Schema::getUniqueIndexInformation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 22
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 1
eloc 19
c 3
b 0
f 0
nc 1
nop 1
dl 0
loc 22
ccs 7
cts 7
cp 1
crap 1
rs 9.6333
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\Schema\Builder\ColumnInterface;
21
use Yiisoft\Db\Schema\ColumnSchemaInterface;
22
use Yiisoft\Db\Schema\TableSchemaInterface;
23
24
use function array_merge;
25
use function array_unique;
26
use function array_values;
27
use function explode;
28
use function hex2bin;
29
use function is_string;
30
use function preg_match;
31
use function preg_replace;
32
use function str_replace;
33
use function str_starts_with;
34
use function substr;
35
36
/**
37
 * Implements the PostgreSQL Server specific schema, supporting PostgreSQL Server version 9.6 and above.
38
 *
39
 * @psalm-type ColumnArray = array{
40
 *   table_schema: string,
41
 *   table_name: string,
42
 *   column_name: string,
43
 *   data_type: string,
44
 *   type_type: string|null,
45
 *   type_scheme: string|null,
46
 *   character_maximum_length: int,
47
 *   column_comment: string|null,
48
 *   modifier: int,
49
 *   is_nullable: bool,
50
 *   column_default: string|null,
51
 *   is_autoinc: bool,
52
 *   sequence_name: string|null,
53
 *   enum_values: string|null,
54
 *   numeric_precision: int|null,
55
 *   numeric_scale: int|null,
56
 *   size: string|null,
57
 *   is_pkey: bool|null,
58
 *   dimension: int
59
 * }
60
 * @psalm-type ConstraintArray = array<
61
 *   array-key,
62
 *   array {
63
 *     name: string,
64
 *     column_name: string,
65
 *     type: string,
66
 *     foreign_table_schema: string|null,
67
 *     foreign_table_name: string|null,
68
 *     foreign_column_name: string|null,
69
 *     on_update: string,
70
 *     on_delete: string,
71
 *     check_expr: string
72
 *   }
73
 * >
74
 * @psalm-type FindConstraintArray = array{
75
 *   constraint_name: string,
76
 *   column_name: string,
77
 *   foreign_table_name: string,
78
 *   foreign_table_schema: string,
79
 *   foreign_column_name: string,
80
 * }
81
 */
82
final class Schema extends AbstractPdoSchema
83
{
84
    /**
85
     * Define the abstract column type as `bit`.
86
     */
87
    public const TYPE_BIT = 'bit';
88
    /**
89
     * Define the abstract column type as `composite`.
90
     */
91
    public const TYPE_COMPOSITE = 'composite';
92
93
    /**
94
     * The mapping from physical column types (keys) to abstract column types (values).
95
     *
96
     * @link https://www.postgresql.org/docs/current/datatype.html#DATATYPE-TABLE
97
     *
98
     * @var string[]
99
     */
100
    private const TYPE_MAP = [
101
        'bit' => self::TYPE_BIT,
102
        'bit varying' => self::TYPE_BIT,
103
        'varbit' => self::TYPE_BIT,
104
        'bool' => self::TYPE_BOOLEAN,
105
        'boolean' => self::TYPE_BOOLEAN,
106
        'box' => self::TYPE_STRING,
107
        'circle' => self::TYPE_STRING,
108
        'point' => self::TYPE_STRING,
109
        'line' => self::TYPE_STRING,
110
        'lseg' => self::TYPE_STRING,
111
        'polygon' => self::TYPE_STRING,
112
        'path' => self::TYPE_STRING,
113
        'character' => self::TYPE_CHAR,
114
        'char' => self::TYPE_CHAR,
115
        'bpchar' => self::TYPE_CHAR,
116
        'character varying' => self::TYPE_STRING,
117
        'varchar' => self::TYPE_STRING,
118
        'text' => self::TYPE_TEXT,
119
        'bytea' => self::TYPE_BINARY,
120
        'cidr' => self::TYPE_STRING,
121
        'inet' => self::TYPE_STRING,
122
        'macaddr' => self::TYPE_STRING,
123
        'real' => self::TYPE_FLOAT,
124
        'float4' => self::TYPE_FLOAT,
125
        'double precision' => self::TYPE_DOUBLE,
126
        'float8' => self::TYPE_DOUBLE,
127
        'decimal' => self::TYPE_DECIMAL,
128
        'numeric' => self::TYPE_DECIMAL,
129
        'money' => self::TYPE_MONEY,
130
        'smallint' => self::TYPE_SMALLINT,
131
        'int2' => self::TYPE_SMALLINT,
132
        'int4' => self::TYPE_INTEGER,
133
        'int' => self::TYPE_INTEGER,
134
        'integer' => self::TYPE_INTEGER,
135
        'bigint' => self::TYPE_BIGINT,
136
        'int8' => self::TYPE_BIGINT,
137
        'oid' => self::TYPE_BIGINT, // shouldn't be used. it's pg internal!
138
        'smallserial' => self::TYPE_SMALLINT,
139
        'serial2' => self::TYPE_SMALLINT,
140
        'serial4' => self::TYPE_INTEGER,
141
        'serial' => self::TYPE_INTEGER,
142
        'bigserial' => self::TYPE_BIGINT,
143
        'serial8' => self::TYPE_BIGINT,
144
        'pg_lsn' => self::TYPE_BIGINT,
145
        'date' => self::TYPE_DATE,
146
        'interval' => self::TYPE_STRING,
147
        'time without time zone' => self::TYPE_TIME,
148
        'time' => self::TYPE_TIME,
149
        'time with time zone' => self::TYPE_TIME,
150
        'timetz' => self::TYPE_TIME,
151
        'timestamp without time zone' => self::TYPE_TIMESTAMP,
152
        'timestamp' => self::TYPE_TIMESTAMP,
153
        'timestamp with time zone' => self::TYPE_TIMESTAMP,
154
        'timestamptz' => self::TYPE_TIMESTAMP,
155
        'abstime' => self::TYPE_TIMESTAMP,
156
        'tsquery' => self::TYPE_STRING,
157
        'tsvector' => self::TYPE_STRING,
158
        'txid_snapshot' => self::TYPE_STRING,
159
        'unknown' => self::TYPE_STRING,
160
        'uuid' => self::TYPE_STRING,
161
        'json' => self::TYPE_JSON,
162
        'jsonb' => self::TYPE_JSON,
163
        'xml' => self::TYPE_STRING,
164
    ];
165
166
    /**
167
     * @var string|null The default schema used for the current session.
168
     */
169
    protected string|null $defaultSchema = 'public';
170
171
    /**
172
     * @var string|string[] Character used to quote schema, table, etc. names.
173
     *
174
     * An array of 2 characters can be used in case starting and ending characters are different.
175
     */
176
    protected string|array $tableQuoteCharacter = '"';
177
178 14
    public function createColumn(string $type, array|int|string $length = null): ColumnInterface
179
    {
180 14
        return new Column($type, $length);
181
    }
182
183
    /**
184
     * Resolves the table name and schema name (if any).
185
     *
186
     * @param string $name The table name.
187
     *
188
     * @return TableSchemaInterface With resolved table, schema, etc. names.
189
     *
190
     * @see TableSchemaInterface
191
     */
192 241
    protected function resolveTableName(string $name): TableSchemaInterface
193
    {
194 241
        $resolvedName = new TableSchema();
195
196 241
        $parts = array_reverse($this->db->getQuoter()->getTableNameParts($name));
197 241
        $resolvedName->name($parts[0] ?? '');
198 241
        $resolvedName->schemaName($parts[1] ?? $this->defaultSchema);
199
200 241
        $resolvedName->fullName(
201 241
            $resolvedName->getSchemaName() !== $this->defaultSchema ?
202 241
            implode('.', array_reverse($parts)) : $resolvedName->getName()
203 241
        );
204
205 241
        return $resolvedName;
206
    }
207
208
    /**
209
     * Returns all schema names in the database, including the default one but not system schemas.
210
     *
211
     * This method should be overridden by child classes to support this feature because the default implementation
212
     * simply throws an exception.
213
     *
214
     * @throws Exception
215
     * @throws InvalidConfigException
216
     * @throws Throwable
217
     *
218
     * @return array All schemas name in the database, except system schemas.
219
     */
220 1
    protected function findSchemaNames(): array
221
    {
222 1
        $sql = <<<SQL
223
        SELECT "ns"."nspname"
224
        FROM "pg_namespace" AS "ns"
225
        WHERE "ns"."nspname" != 'information_schema' AND "ns"."nspname" NOT LIKE 'pg_%'
226
        ORDER BY "ns"."nspname" ASC
227 1
        SQL;
228
229 1
        return $this->db->createCommand($sql)->queryColumn();
230
    }
231
232
    /**
233
     * @throws Exception
234
     * @throws InvalidConfigException
235
     * @throws Throwable
236
     */
237 186
    protected function findTableComment(TableSchemaInterface $tableSchema): void
238
    {
239 186
        $sql = <<<SQL
240
        SELECT obj_description(pc.oid, 'pg_class')
241
        FROM pg_catalog.pg_class pc
242
        INNER JOIN pg_namespace pn ON pc.relnamespace = pn.oid
243
        WHERE
244
        pc.relname=:tableName AND
245
        pn.nspname=:schemaName
246 186
        SQL;
247
248 186
        $comment = $this->db->createCommand($sql, [
249 186
            ':schemaName' => $tableSchema->getSchemaName(),
250 186
            ':tableName' => $tableSchema->getName(),
251 186
        ])->queryScalar();
252
253 186
        $tableSchema->comment(is_string($comment) ? $comment : null);
254
    }
255
256
    /**
257
     * Returns all table names in the database.
258
     *
259
     * This method should be overridden by child classes to support this feature because the default implementation
260
     * simply throws an exception.
261
     *
262
     * @param string $schema The schema of the tables.
263
     * Defaults to empty string, meaning the current or default schema.
264
     *
265
     * @throws Exception
266
     * @throws InvalidConfigException
267
     * @throws Throwable
268
     *
269
     * @return array All tables name in the database. The names have NO schema name prefix.
270
     */
271 12
    protected function findTableNames(string $schema = ''): array
272
    {
273 12
        if ($schema === '') {
274 11
            $schema = $this->defaultSchema;
275
        }
276
277 12
        $sql = <<<SQL
278
        SELECT c.relname AS table_name
279
        FROM pg_class c
280
        INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace
281
        WHERE ns.nspname = :schemaName AND c.relkind IN ('r','v','m','f', 'p')
282
        ORDER BY c.relname
283 12
        SQL;
284
285 12
        return $this->db->createCommand($sql, [':schemaName' => $schema])->queryColumn();
286
    }
287
288
    /**
289
     * Loads the metadata for the specified table.
290
     *
291
     * @param string $name The table name.
292
     *
293
     * @throws Exception
294
     * @throws InvalidConfigException
295
     * @throws Throwable
296
     *
297
     * @return TableSchemaInterface|null DBMS-dependent table metadata, `null` if the table doesn't exist.
298
     */
299 186
    protected function loadTableSchema(string $name): TableSchemaInterface|null
300
    {
301 186
        $table = $this->resolveTableName($name);
302 186
        $this->findTableComment($table);
303
304 186
        if ($this->findColumns($table)) {
305 164
            $this->findConstraints($table);
306 164
            return $table;
307
        }
308
309 43
        return null;
310
    }
311
312
    /**
313
     * Loads a primary key for the given table.
314
     *
315
     * @param string $tableName The table name.
316
     *
317
     * @throws Exception
318
     * @throws InvalidConfigException
319
     * @throws Throwable
320
     *
321
     * @return Constraint|null Primary key for the given table, `null` if the table has no primary key.
322
     */
323 41
    protected function loadTablePrimaryKey(string $tableName): Constraint|null
324
    {
325 41
        $tablePrimaryKey = $this->loadTableConstraints($tableName, self::PRIMARY_KEY);
326
327 41
        return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
328
    }
329
330
    /**
331
     * Loads all foreign keys for the given table.
332
     *
333
     * @param string $tableName The table name.
334
     *
335
     * @throws Exception
336
     * @throws InvalidConfigException
337
     * @throws Throwable
338
     *
339
     * @return array Foreign keys for the given table.
340
     *
341
     * @psaml-return array|ForeignKeyConstraint[]
342
     */
343 8
    protected function loadTableForeignKeys(string $tableName): array
344
    {
345 8
        $tableForeignKeys = $this->loadTableConstraints($tableName, self::FOREIGN_KEYS);
346
347 8
        return is_array($tableForeignKeys) ? $tableForeignKeys : [];
348
    }
349
350
    /**
351
     * Loads all indexes for the given table.
352
     *
353
     * @param string $tableName The table name.
354
     *
355
     * @throws Exception
356
     * @throws InvalidConfigException
357
     * @throws Throwable
358
     *
359
     * @return IndexConstraint[] Indexes for the given table.
360
     */
361 39
    protected function loadTableIndexes(string $tableName): array
362
    {
363 39
        $sql = <<<SQL
364
        SELECT
365
            "ic"."relname" AS "name",
366
            "ia"."attname" AS "column_name",
367
            "i"."indisunique" AS "index_is_unique",
368
            "i"."indisprimary" AS "index_is_primary"
369
        FROM "pg_class" AS "tc"
370
        INNER JOIN "pg_namespace" AS "tcns"
371
            ON "tcns"."oid" = "tc"."relnamespace"
372
        INNER JOIN "pg_index" AS "i"
373
            ON "i"."indrelid" = "tc"."oid"
374
        INNER JOIN "pg_class" AS "ic"
375
            ON "ic"."oid" = "i"."indexrelid"
376
        INNER JOIN "pg_attribute" AS "ia"
377
            ON "ia"."attrelid" = "i"."indexrelid"
378
        WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName
379
        ORDER BY "ia"."attnum" ASC
380 39
        SQL;
381
382 39
        $resolvedName = $this->resolveTableName($tableName);
383 39
        $indexes = $this->db->createCommand($sql, [
384 39
            ':schemaName' => $resolvedName->getSchemaName(),
385 39
            ':tableName' => $resolvedName->getName(),
386 39
        ])->queryAll();
387
388
        /** @psalm-var array[] $indexes */
389 39
        $indexes = $this->normalizeRowKeyCase($indexes, true);
390 39
        $indexes = DbArrayHelper::index($indexes, null, ['name']);
391 39
        $result = [];
392
393
        /**
394
         * @psalm-var object|string|null $name
395
         * @psalm-var array<
396
         *   array-key,
397
         *   array{
398
         *     name: string,
399
         *     column_name: string,
400
         *     index_is_unique: bool,
401
         *     index_is_primary: bool
402
         *   }
403
         * > $index
404
         */
405 39
        foreach ($indexes as $name => $index) {
406 36
            $ic = (new IndexConstraint())
407 36
                ->name($name)
408 36
                ->columnNames(DbArrayHelper::getColumn($index, 'column_name'))
409 36
                ->primary($index[0]['index_is_primary'])
410 36
                ->unique($index[0]['index_is_unique']);
411
412 36
            $result[] = $ic;
413
        }
414
415 39
        return $result;
416
    }
417
418
    /**
419
     * Loads all unique constraints for the given table.
420
     *
421
     * @param string $tableName The table name.
422
     *
423
     * @throws Exception
424
     * @throws InvalidConfigException
425
     * @throws Throwable
426
     *
427
     * @return array Unique constraints for the given table.
428
     *
429
     * @psalm-return array|Constraint[]
430
     */
431 17
    protected function loadTableUniques(string $tableName): array
432
    {
433 17
        $tableUniques = $this->loadTableConstraints($tableName, self::UNIQUES);
434
435 17
        return is_array($tableUniques) ? $tableUniques : [];
436
    }
437
438
    /**
439
     * Loads all check constraints for the given table.
440
     *
441
     * @param string $tableName The table name.
442
     *
443
     * @throws Exception
444
     * @throws InvalidConfigException
445
     * @throws Throwable
446
     *
447
     * @return array Check constraints for the given table.
448
     *
449
     * @psaml-return array|CheckConstraint[]
450
     */
451 17
    protected function loadTableChecks(string $tableName): array
452
    {
453 17
        $tableChecks = $this->loadTableConstraints($tableName, self::CHECKS);
454
455 17
        return is_array($tableChecks) ? $tableChecks : [];
456
    }
457
458
    /**
459
     * Loads all default value constraints for the given table.
460
     *
461
     * @param string $tableName The table name.
462
     *
463
     * @throws NotSupportedException
464
     *
465
     * @return DefaultValueConstraint[] Default value constraints for the given table.
466
     */
467 13
    protected function loadTableDefaultValues(string $tableName): array
468
    {
469 13
        throw new NotSupportedException(__METHOD__ . ' is not supported by PostgreSQL.');
470
    }
471
472
    /**
473
     * @throws Exception
474
     * @throws InvalidConfigException
475
     * @throws Throwable
476
     */
477 3
    protected function findViewNames(string $schema = ''): array
478
    {
479 3
        if ($schema === '') {
480 1
            $schema = $this->defaultSchema;
481
        }
482
483 3
        $sql = <<<SQL
484
        SELECT c.relname AS table_name
485
        FROM pg_class c
486
        INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace
487
        WHERE ns.nspname = :schemaName AND (c.relkind = 'v' OR c.relkind = 'm')
488
        ORDER BY c.relname
489 3
        SQL;
490
491 3
        return $this->db->createCommand($sql, [':schemaName' => $schema])->queryColumn();
492
    }
493
494
    /**
495
     * Collects the foreign key column details for the given table.
496
     *
497
     * @param TableSchemaInterface $table The table metadata
498
     *
499
     * @throws Exception
500
     * @throws InvalidConfigException
501
     * @throws Throwable
502
     */
503 164
    protected function findConstraints(TableSchemaInterface $table): void
504
    {
505
        /**
506
         * We need to extract the constraints de hard way since:
507
         * {@see https://www.postgresql.org/message-id/[email protected]}
508
         */
509
510 164
        $sql = <<<SQL
511
        SELECT
512
            ct.conname as constraint_name,
513
            a.attname as column_name,
514
            fc.relname as foreign_table_name,
515
            fns.nspname as foreign_table_schema,
516
            fa.attname as foreign_column_name
517
            FROM
518
            (SELECT ct.conname, ct.conrelid, ct.confrelid, ct.conkey, ct.contype, ct.confkey,
519
                generate_subscripts(ct.conkey, 1) AS s
520
                FROM pg_constraint ct
521
            ) AS ct
522
            inner join pg_class c on c.oid=ct.conrelid
523
            inner join pg_namespace ns on c.relnamespace=ns.oid
524
            inner join pg_attribute a on a.attrelid=ct.conrelid and a.attnum = ct.conkey[ct.s]
525
            left join pg_class fc on fc.oid=ct.confrelid
526
            left join pg_namespace fns on fc.relnamespace=fns.oid
527
            left join pg_attribute fa on fa.attrelid=ct.confrelid and fa.attnum = ct.confkey[ct.s]
528
        WHERE
529
            ct.contype='f'
530
            and c.relname=:tableName
531
            and ns.nspname=:schemaName
532
        ORDER BY
533
            fns.nspname, fc.relname, a.attnum
534 164
        SQL;
535
536
        /** @psalm-var array{array{tableName: string, columns: array}} $constraints */
537 164
        $constraints = [];
538
539
        /** @psalm-var array<FindConstraintArray> $rows */
540 164
        $rows = $this->db->createCommand($sql, [
541 164
            ':schemaName' => $table->getSchemaName(),
542 164
            ':tableName' => $table->getName(),
543 164
        ])->queryAll();
544
545 164
        foreach ($rows as $constraint) {
546
            /** @psalm-var FindConstraintArray $constraint */
547 16
            $constraint = $this->normalizeRowKeyCase($constraint, false);
548
549 16
            if ($constraint['foreign_table_schema'] !== $this->defaultSchema) {
550 3
                $foreignTable = $constraint['foreign_table_schema'] . '.' . $constraint['foreign_table_name'];
551
            } else {
552 16
                $foreignTable = $constraint['foreign_table_name'];
553
            }
554
555 16
            $name = $constraint['constraint_name'];
556
557 16
            if (!isset($constraints[$name])) {
558 16
                $constraints[$name] = [
559 16
                    'tableName' => $foreignTable,
560 16
                    'columns' => [],
561 16
                ];
562
            }
563
564 16
            $constraints[$name]['columns'][$constraint['column_name']] = $constraint['foreign_column_name'];
565
        }
566
567
        /**
568
         * @psalm-var int|string $foreingKeyName.
569
         * @psalm-var array{tableName: string, columns: array} $constraint
570
         */
571 164
        foreach ($constraints as $foreingKeyName => $constraint) {
572 16
            $table->foreignKey(
573 16
                (string) $foreingKeyName,
574 16
                array_merge([$constraint['tableName']], $constraint['columns'])
575 16
            );
576
        }
577
    }
578
579
    /**
580
     * Gets information about given table unique indexes.
581
     *
582
     * @param TableSchemaInterface $table The table metadata.
583
     *
584
     * @throws Exception
585
     * @throws InvalidConfigException
586
     * @throws Throwable
587
     *
588
     * @return array With index and column names.
589
     */
590 1
    protected function getUniqueIndexInformation(TableSchemaInterface $table): array
591
    {
592 1
        $sql = <<<'SQL'
593
        SELECT
594
            i.relname as indexname,
595
            pg_get_indexdef(idx.indexrelid, k + 1, TRUE) AS columnname
596
        FROM (
597
            SELECT *, generate_subscripts(indkey, 1) AS k
598
            FROM pg_index
599
        ) idx
600
        INNER JOIN pg_class i ON i.oid = idx.indexrelid
601
        INNER JOIN pg_class c ON c.oid = idx.indrelid
602
        INNER JOIN pg_namespace ns ON c.relnamespace = ns.oid
603
        WHERE idx.indisprimary = FALSE AND idx.indisunique = TRUE
604
        AND c.relname = :tableName AND ns.nspname = :schemaName
605
        ORDER BY i.relname, k
606 1
        SQL;
607
608 1
        return $this->db->createCommand($sql, [
609 1
            ':schemaName' => $table->getSchemaName(),
610 1
            ':tableName' => $table->getName(),
611 1
        ])->queryAll();
612
    }
613
614
    /**
615
     * Returns all unique indexes for the given table.
616
     *
617
     * Each array element is of the following structure:
618
     *
619
     * ```php
620
     * [
621
     *     'IndexName1' => ['col1' [, ...]],
622
     *     'IndexName2' => ['col2' [, ...]],
623
     * ]
624
     * ```
625
     *
626
     * @param TableSchemaInterface $table The table metadata
627
     *
628
     * @throws Exception
629
     * @throws InvalidConfigException
630
     * @throws Throwable
631
     *
632
     * @return array All unique indexes for the given table.
633
     */
634 1
    public function findUniqueIndexes(TableSchemaInterface $table): array
635
    {
636 1
        $uniqueIndexes = [];
637
638
        /** @psalm-var array{indexname: string, columnname: string} $row */
639 1
        foreach ($this->getUniqueIndexInformation($table) as $row) {
640
            /** @psalm-var array{indexname: string, columnname: string} $row */
641 1
            $row = $this->normalizeRowKeyCase($row, false);
642
643 1
            $column = $row['columnname'];
644
645 1
            if (str_starts_with($column, '"') && str_ends_with($column, '"')) {
646
                /**
647
                 * postgres will quote names that aren't lowercase-only.
648
                 *
649
                 * {@see https://github.com/yiisoft/yii2/issues/10613}
650
                 */
651 1
                $column = substr($column, 1, -1);
652
            }
653
654 1
            $uniqueIndexes[$row['indexname']][] = $column;
655
        }
656
657 1
        return $uniqueIndexes;
658
    }
659
660
    /**
661
     * Collects the metadata of table columns.
662
     *
663
     * @param TableSchemaInterface $table The table metadata.
664
     *
665
     * @throws Exception
666
     * @throws InvalidConfigException
667
     * @throws JsonException
668
     * @throws Throwable
669
     *
670
     * @return bool Whether the table exists in the database.
671
     */
672 186
    protected function findColumns(TableSchemaInterface $table): bool
673
    {
674 186
        $orIdentity = '';
675
676 186
        if (version_compare($this->db->getServerVersion(), '12.0', '>=')) {
677 179
            $orIdentity = 'OR a.attidentity != \'\'';
678
        }
679
680 186
        $sql = <<<SQL
681 186
        SELECT
682
            d.nspname AS table_schema,
683
            c.relname AS table_name,
684
            a.attname AS column_name,
685
            COALESCE(td.typname, tb.typname, t.typname) AS data_type,
686
            COALESCE(td.typtype, tb.typtype, t.typtype) AS type_type,
687
            (SELECT nspname FROM pg_namespace WHERE oid = COALESCE(td.typnamespace, tb.typnamespace, t.typnamespace)) AS type_scheme,
688
            a.attlen AS character_maximum_length,
689
            pg_catalog.col_description(c.oid, a.attnum) AS column_comment,
690
            information_schema._pg_truetypmod(a, t) AS modifier,
691
            NOT (a.attnotnull OR t.typnotnull) AS is_nullable,
692
            COALESCE(t.typdefault, pg_get_expr(ad.adbin, ad.adrelid)) AS column_default,
693 186
            COALESCE(pg_get_expr(ad.adbin, ad.adrelid) ~ 'nextval', false) $orIdentity AS is_autoinc,
694
            pg_get_serial_sequence(quote_ident(d.nspname) || '.' || quote_ident(c.relname), a.attname)
695
            AS sequence_name,
696
            CASE WHEN COALESCE(td.typtype, tb.typtype, t.typtype) = 'e'::char
697
                THEN array_to_string(
698
                    (
699
                        SELECT array_agg(enumlabel)
700
                        FROM pg_enum
701
                        WHERE enumtypid = COALESCE(td.oid, tb.oid, a.atttypid)
702
                    )::varchar[],
703
                ',')
704
                ELSE NULL
705
            END AS enum_values,
706
            information_schema._pg_numeric_precision(
707
                COALESCE(td.oid, tb.oid, a.atttypid),
708
                information_schema._pg_truetypmod(a, t)
709
            ) AS numeric_precision,
710
            information_schema._pg_numeric_scale(
711
                COALESCE(td.oid, tb.oid, a.atttypid),
712
                information_schema._pg_truetypmod(a, t)
713
            ) AS numeric_scale,
714
            information_schema._pg_char_max_length(
715
                COALESCE(td.oid, tb.oid, a.atttypid),
716
                information_schema._pg_truetypmod(a, t)
717
            ) AS size,
718
            a.attnum = any (ct.conkey) as is_pkey,
719
            COALESCE(NULLIF(a.attndims, 0), NULLIF(t.typndims, 0), (t.typcategory='A')::int) AS dimension
720
        FROM
721
            pg_class c
722
            LEFT JOIN pg_attribute a ON a.attrelid = c.oid
723
            LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum
724
            LEFT JOIN pg_type t ON a.atttypid = t.oid
725
            LEFT JOIN pg_type tb ON (a.attndims > 0 OR t.typcategory='A') AND t.typelem > 0 AND t.typelem = tb.oid
726
                                        OR t.typbasetype > 0 AND t.typbasetype = tb.oid
727
            LEFT JOIN pg_type td ON t.typndims > 0 AND t.typbasetype > 0 AND tb.typelem = td.oid
728
            LEFT JOIN pg_namespace d ON d.oid = c.relnamespace
729
            LEFT JOIN pg_constraint ct ON ct.conrelid = c.oid AND ct.contype = 'p'
730
        WHERE
731
            a.attnum > 0 AND t.typname != '' AND NOT a.attisdropped
732
            AND c.relname = :tableName
733
            AND d.nspname = :schemaName
734
        ORDER BY
735
            a.attnum;
736 186
        SQL;
737
738 186
        $columns = $this->db->createCommand($sql, [
739 186
            ':schemaName' => $table->getSchemaName(),
740 186
            ':tableName' => $table->getName(),
741 186
        ])->queryAll();
742
743 186
        if (empty($columns)) {
744 43
            return false;
745
        }
746
747
        /** @psalm-var ColumnArray $info */
748 164
        foreach ($columns as $info) {
749
            /** @psalm-var ColumnArray $info */
750 164
            $info = $this->normalizeRowKeyCase($info, false);
751
752
            /** @psalm-var ColumnSchema $column */
753 164
            $column = $this->loadColumnSchema($info);
754
755 164
            $table->column($column->getName(), $column);
756
757 164
            if ($column->isPrimaryKey()) {
758 98
                $table->primaryKey($column->getName());
759
760 98
                if ($table->getSequenceName() === null) {
761 98
                    $table->sequenceName($column->getSequenceName());
762
                }
763
            }
764
        }
765
766 164
        return true;
767
    }
768
769
    /**
770
     * Loads the column information into a {@see ColumnSchemaInterface} object.
771
     *
772
     * @psalm-param ColumnArray $info Column information.
773
     *
774
     * @return ColumnSchemaInterface The column schema object.
775
     */
776 164
    protected function loadColumnSchema(array $info): ColumnSchemaInterface
777
    {
778 164
        $column = $this->createColumnSchema($info['column_name']);
779 164
        $column->allowNull($info['is_nullable']);
780 164
        $column->autoIncrement($info['is_autoinc']);
781 164
        $column->comment($info['column_comment']);
782
783 164
        if (!in_array($info['type_scheme'], [$this->defaultSchema, 'pg_catalog'], true)) {
784 1
            $column->dbType($info['type_scheme'] . '.' . $info['data_type']);
785
        } else {
786 164
            $column->dbType($info['data_type']);
787
        }
788
789 164
        $column->enumValues($info['enum_values'] !== null
790 1
            ? explode(',', str_replace(["''"], ["'"], $info['enum_values']))
791 164
            : null);
792 164
        $column->unsigned(false); // has no meaning in PG
793 164
        $column->primaryKey((bool) $info['is_pkey']);
794 164
        $column->precision($info['numeric_precision']);
795 164
        $column->scale($info['numeric_scale']);
796 164
        $column->size($info['size'] === null ? null : (int) $info['size']);
797 164
        $column->dimension($info['dimension']);
798
799
        /**
800
         * pg_get_serial_sequence() doesn't track DEFAULT value change.
801
         * GENERATED BY IDENTITY columns always have a null default value.
802
         */
803 164
        $defaultValue = $info['column_default'];
804
805
        if (
806 164
            $defaultValue !== null
807 164
            && preg_match("/^nextval\('([^']+)/", $defaultValue, $matches) === 1
808
        ) {
809 81
            $column->sequenceName($matches[1]);
810 164
        } elseif ($info['sequence_name'] !== null) {
811 5
            $column->sequenceName($this->resolveTableName($info['sequence_name'])->getFullName());
812
        }
813
814 164
        if ($info['type_type'] === 'c') {
815 5
            $column->type(self::TYPE_COMPOSITE);
816 5
            $composite = $this->resolveTableName((string) $column->getDbType());
817
818 5
            if ($this->findColumns($composite)) {
819 5
                $column->columns($composite->getColumns());
820
            }
821
        } else {
822 164
            $column->type(self::TYPE_MAP[(string) $column->getDbType()] ?? self::TYPE_STRING);
823
        }
824
825 164
        $column->phpType($this->getColumnPhpType($column));
826 164
        $column->defaultValue($this->normalizeDefaultValue($defaultValue, $column));
827
828 164
        if ($column->getType() === self::TYPE_COMPOSITE && $column->getDimension() === 0) {
829
            /** @psalm-var array|null $defaultValue */
830 5
            $defaultValue = $column->getDefaultValue();
831 5
            if (is_array($defaultValue)) {
832 5
                foreach ($column->getColumns() as $compositeColumnName => $compositeColumn) {
833 5
                    $compositeColumn->defaultValue($defaultValue[$compositeColumnName] ?? null);
834
                }
835
            }
836
        }
837
838 164
        return $column;
839
    }
840
841
    /**
842
     * Extracts the PHP type from an abstract DB type.
843
     *
844
     * @param ColumnSchemaInterface $column The column schema information.
845
     *
846
     * @return string The PHP type name.
847
     */
848 164
    protected function getColumnPhpType(ColumnSchemaInterface $column): string
849
    {
850 164
        return match ($column->getType()) {
851 164
            self::TYPE_BIT => self::PHP_TYPE_INTEGER,
852 164
            self::TYPE_COMPOSITE => self::PHP_TYPE_ARRAY,
853 164
            default => parent::getColumnPhpType($column),
854 164
        };
855
    }
856
857
    /**
858
     * Converts column's default value according to {@see ColumnSchema::phpType} after retrieval from the database.
859
     *
860
     * @param string|null $defaultValue The default value retrieved from the database.
861
     * @param ColumnSchemaInterface $column The column schema object.
862
     *
863
     * @return mixed The normalized default value.
864
     */
865 164
    private function normalizeDefaultValue(string|null $defaultValue, ColumnSchemaInterface $column): mixed
866
    {
867
        if (
868 164
            $defaultValue === null
869 128
            || $column->isPrimaryKey()
870 164
            || str_starts_with($defaultValue, 'NULL::')
871
        ) {
872 160
            return null;
873
        }
874
875 99
        if ($column->getType() === self::TYPE_BOOLEAN && in_array($defaultValue, ['true', 'false'], true)) {
876 71
            return $defaultValue === 'true';
877
        }
878
879
        if (
880 98
            in_array($column->getType(), [self::TYPE_TIMESTAMP, self::TYPE_DATE, self::TYPE_TIME], true)
881 98
            && in_array(strtoupper($defaultValue), ['NOW()', 'CURRENT_TIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIME'], true)
882
        ) {
883 39
            return new Expression($defaultValue);
884
        }
885
886 98
        $value = preg_replace("/^B?['(](.*?)[)'](?:::[^:]+)?$/s", '$1', $defaultValue);
887 98
        $value = str_replace("''", "'", $value);
888
889 98
        if ($column->getType() === self::TYPE_BINARY && str_starts_with($value, '\\x')) {
890 39
            return hex2bin(substr($value, 2));
891
        }
892
893 98
        return $column->phpTypecast($value);
894
    }
895
896
    /**
897
     * Loads multiple types of constraints and returns the specified ones.
898
     *
899
     * @param string $tableName The table name.
900
     * @param string $returnType The return type:
901
     * - primaryKey
902
     * - foreignKeys
903
     * - uniques
904
     * - checks
905
     *
906
     * @throws Exception
907
     * @throws InvalidConfigException
908
     * @throws Throwable
909
     *
910
     * @return array|Constraint|null Constraints.
911
     *
912
     * @psalm-return CheckConstraint[]|Constraint[]|ForeignKeyConstraint[]|Constraint|null
913
     */
914 83
    private function loadTableConstraints(string $tableName, string $returnType): array|Constraint|null
915
    {
916 83
        $sql = <<<SQL
917
        SELECT
918
            "c"."conname" AS "name",
919
            "a"."attname" AS "column_name",
920
            "c"."contype" AS "type",
921
            "ftcns"."nspname" AS "foreign_table_schema",
922
            "ftc"."relname" AS "foreign_table_name",
923
            "fa"."attname" AS "foreign_column_name",
924
            "c"."confupdtype" AS "on_update",
925
            "c"."confdeltype" AS "on_delete",
926
            pg_get_constraintdef("c"."oid") AS "check_expr"
927
        FROM "pg_class" AS "tc"
928
        INNER JOIN "pg_namespace" AS "tcns"
929
            ON "tcns"."oid" = "tc"."relnamespace"
930
        INNER JOIN "pg_constraint" AS "c"
931
            ON "c"."conrelid" = "tc"."oid"
932
        INNER JOIN "pg_attribute" AS "a"
933
            ON "a"."attrelid" = "c"."conrelid" AND "a"."attnum" = ANY ("c"."conkey")
934
        LEFT JOIN "pg_class" AS "ftc"
935
            ON "ftc"."oid" = "c"."confrelid"
936
        LEFT JOIN "pg_namespace" AS "ftcns"
937
            ON "ftcns"."oid" = "ftc"."relnamespace"
938
        LEFT JOIN "pg_attribute" "fa"
939
            ON "fa"."attrelid" = "c"."confrelid" AND "fa"."attnum" = ANY ("c"."confkey")
940
        WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName
941
        ORDER BY "a"."attnum" ASC, "fa"."attnum" ASC
942 83
        SQL;
943
944
        /** @psalm-var string[] $actionTypes */
945 83
        $actionTypes = [
946 83
            'a' => 'NO ACTION',
947 83
            'r' => 'RESTRICT',
948 83
            'c' => 'CASCADE',
949 83
            'n' => 'SET NULL',
950 83
            'd' => 'SET DEFAULT',
951 83
        ];
952
953 83
        $resolvedName = $this->resolveTableName($tableName);
954 83
        $constraints = $this->db->createCommand($sql, [
955 83
            ':schemaName' => $resolvedName->getSchemaName(),
956 83
            ':tableName' => $resolvedName->getName(),
957 83
        ])->queryAll();
958
959
        /** @psalm-var array[][] $constraints */
960 83
        $constraints = $this->normalizeRowKeyCase($constraints, true);
961 83
        $constraints = DbArrayHelper::index($constraints, null, ['type', 'name']);
962
963 83
        $result = [
964 83
            self::PRIMARY_KEY => null,
965 83
            self::FOREIGN_KEYS => [],
966 83
            self::UNIQUES => [],
967 83
            self::CHECKS => [],
968 83
        ];
969
970
        /**
971
         * @psalm-var string $type
972
         * @psalm-var array $names
973
         */
974 83
        foreach ($constraints as $type => $names) {
975
            /**
976
             * @psalm-var object|string|null $name
977
             * @psalm-var ConstraintArray $constraint
978
             */
979 83
            foreach ($names as $name => $constraint) {
980
                switch ($type) {
981 83
                    case 'p':
982 58
                        $result[self::PRIMARY_KEY] = (new Constraint())
983 58
                            ->name($name)
984 58
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'));
985 58
                        break;
986 75
                    case 'f':
987 19
                        $onDelete = $actionTypes[$constraint[0]['on_delete']] ?? null;
988 19
                        $onUpdate = $actionTypes[$constraint[0]['on_update']] ?? null;
989
990 19
                        $result[self::FOREIGN_KEYS][] = (new ForeignKeyConstraint())
991 19
                            ->name($name)
992 19
                            ->columnNames(array_values(
993 19
                                array_unique(DbArrayHelper::getColumn($constraint, 'column_name'))
994 19
                            ))
995 19
                            ->foreignSchemaName($constraint[0]['foreign_table_schema'])
996 19
                            ->foreignTableName($constraint[0]['foreign_table_name'])
997 19
                            ->foreignColumnNames(array_values(
998 19
                                array_unique(DbArrayHelper::getColumn($constraint, 'foreign_column_name'))
999 19
                            ))
1000 19
                            ->onDelete($onDelete)
1001 19
                            ->onUpdate($onUpdate);
1002 19
                        break;
1003 62
                    case 'u':
1004 59
                        $result[self::UNIQUES][] = (new Constraint())
1005 59
                            ->name($name)
1006 59
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'));
1007 59
                        break;
1008 15
                    case 'c':
1009 15
                        $result[self::CHECKS][] = (new CheckConstraint())
1010 15
                            ->name($name)
1011 15
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'))
1012 15
                            ->expression($constraint[0]['check_expr']);
1013 15
                        break;
1014
                }
1015
            }
1016
        }
1017
1018 83
        foreach ($result as $type => $data) {
1019 83
            $this->setTableMetadata($tableName, $type, $data);
1020
        }
1021
1022 83
        return $result[$returnType];
1023
    }
1024
1025
    /**
1026
     * Creates a column schema for the database.
1027
     *
1028
     * This method may be overridden by child classes to create a DBMS-specific column schema.
1029
     *
1030
     * @param string $name Name of the column.
1031
     *
1032
     * @return ColumnSchema
1033
     */
1034 164
    private function createColumnSchema(string $name): ColumnSchema
1035
    {
1036 164
        return new ColumnSchema($name);
1037
    }
1038
1039
    /**
1040
     * Returns the cache key for the specified table name.
1041
     *
1042
     * @param string $name The table name.
1043
     *
1044
     * @return array The cache key.
1045
     */
1046 276
    protected function getCacheKey(string $name): array
1047
    {
1048 276
        return array_merge([self::class], $this->generateCacheKey(), [$this->getRawTableName($name)]);
1049
    }
1050
1051
    /**
1052
     * Returns the cache tag name.
1053
     *
1054
     * This allows {@see refresh()} to invalidate all cached table schemas.
1055
     *
1056
     * @return string The cache tag name.
1057
     */
1058 242
    protected function getCacheTag(): string
1059
    {
1060 242
        return md5(serialize(array_merge([self::class], $this->generateCacheKey())));
1061
    }
1062
}
1063