Test Failed
Pull Request — master (#307)
by
unknown
04:01
created

Schema::getUniqueIndexInformation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 22
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

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