Passed
Push — master ( be590a...089f25 )
by Sergei
23:18 queued 19:09
created

Schema::createColumn()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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 245
    protected function resolveTableName(string $name): TableSchemaInterface
193
    {
194 245
        $resolvedName = new TableSchema();
195
196 245
        $parts = array_reverse($this->db->getQuoter()->getTableNameParts($name));
197 245
        $resolvedName->name($parts[0] ?? '');
198 245
        $resolvedName->schemaName($parts[1] ?? $this->defaultSchema);
199
200 245
        $resolvedName->fullName(
201 245
            $resolvedName->getSchemaName() !== $this->defaultSchema ?
202 245
            implode('.', array_reverse($parts)) : $resolvedName->getName()
203 245
        );
204
205 245
        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 189
    protected function findTableComment(TableSchemaInterface $tableSchema): void
238
    {
239 189
        $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 189
        SQL;
247
248 189
        $comment = $this->db->createCommand($sql, [
249 189
            ':schemaName' => $tableSchema->getSchemaName(),
250 189
            ':tableName' => $tableSchema->getName(),
251 189
        ])->queryScalar();
252
253 189
        $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 189
    protected function loadTableSchema(string $name): TableSchemaInterface|null
300
    {
301 189
        $table = $this->resolveTableName($name);
302 189
        $this->findTableComment($table);
303
304 189
        if ($this->findColumns($table)) {
305 167
            $this->findConstraints($table);
306 167
            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 43
    protected function loadTablePrimaryKey(string $tableName): Constraint|null
324
    {
325 43
        $tablePrimaryKey = $this->loadTableConstraints($tableName, self::PRIMARY_KEY);
326
327 43
        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 42
    protected function loadTableIndexes(string $tableName): array
362
    {
363 42
        $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
        LEFT JOIN pg_rewrite AS rw
373
            ON tc.relkind = 'v' AND rw.ev_class = tc.oid AND rw.rulename = '_RETURN'
374
        INNER JOIN "pg_index" AS "i"
375
            ON "i"."indrelid" = "tc"."oid"
376
                OR rw.ev_action IS NOT NULL
377
                AND (SELECT regexp_matches(
378
                    rw.ev_action,
379
                    '{TARGETENTRY .*? :resorigtbl ' || "i"."indrelid" || ' :resorigcol ' || "i"."indkey"[0] || ' '
380
                )) IS NOT NULL
381
        INNER JOIN "pg_class" AS "ic"
382
            ON "ic"."oid" = "i"."indexrelid"
383
        INNER JOIN "pg_attribute" AS "ia"
384
            ON "ia"."attrelid" = "i"."indexrelid" AND "ia"."attnum" <= cardinality("i"."indoption")
385
        WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName
386
        ORDER BY "ia"."attnum" ASC
387 42
        SQL;
388
389 42
        $resolvedName = $this->resolveTableName($tableName);
390 42
        $indexes = $this->db->createCommand($sql, [
391 42
            ':schemaName' => $resolvedName->getSchemaName(),
392 42
            ':tableName' => $resolvedName->getName(),
393 42
        ])->queryAll();
394
395
        /** @psalm-var array[] $indexes */
396 42
        $indexes = $this->normalizeRowKeyCase($indexes, true);
397 42
        $indexes = DbArrayHelper::index($indexes, null, ['name']);
398 42
        $result = [];
399
400
        /**
401
         * @psalm-var object|string|null $name
402
         * @psalm-var array<
403
         *   array-key,
404
         *   array{
405
         *     name: string,
406
         *     column_name: string,
407
         *     index_is_unique: bool,
408
         *     index_is_primary: bool
409
         *   }
410
         * > $index
411
         */
412 42
        foreach ($indexes as $name => $index) {
413 39
            $ic = (new IndexConstraint())
414 39
                ->name($name)
415 39
                ->columnNames(DbArrayHelper::getColumn($index, 'column_name'))
416 39
                ->primary($index[0]['index_is_primary'])
417 39
                ->unique($index[0]['index_is_unique']);
418
419 39
            $result[] = $ic;
420
        }
421
422 42
        return $result;
423
    }
424
425
    /**
426
     * Loads all unique constraints for the given table.
427
     *
428
     * @param string $tableName The table name.
429
     *
430
     * @throws Exception
431
     * @throws InvalidConfigException
432
     * @throws Throwable
433
     *
434
     * @return array Unique constraints for the given table.
435
     *
436
     * @psalm-return array|Constraint[]
437
     */
438 17
    protected function loadTableUniques(string $tableName): array
439
    {
440 17
        $tableUniques = $this->loadTableConstraints($tableName, self::UNIQUES);
441
442 17
        return is_array($tableUniques) ? $tableUniques : [];
443
    }
444
445
    /**
446
     * Loads all check constraints for the given table.
447
     *
448
     * @param string $tableName The table name.
449
     *
450
     * @throws Exception
451
     * @throws InvalidConfigException
452
     * @throws Throwable
453
     *
454
     * @return array Check constraints for the given table.
455
     *
456
     * @psaml-return array|CheckConstraint[]
457
     */
458 17
    protected function loadTableChecks(string $tableName): array
459
    {
460 17
        $tableChecks = $this->loadTableConstraints($tableName, self::CHECKS);
461
462 17
        return is_array($tableChecks) ? $tableChecks : [];
463
    }
464
465
    /**
466
     * Loads all default value constraints for the given table.
467
     *
468
     * @param string $tableName The table name.
469
     *
470
     * @throws NotSupportedException
471
     *
472
     * @return DefaultValueConstraint[] Default value constraints for the given table.
473
     */
474 13
    protected function loadTableDefaultValues(string $tableName): array
475
    {
476 13
        throw new NotSupportedException(__METHOD__ . ' is not supported by PostgreSQL.');
477
    }
478
479
    /**
480
     * @throws Exception
481
     * @throws InvalidConfigException
482
     * @throws Throwable
483
     */
484 3
    protected function findViewNames(string $schema = ''): array
485
    {
486 3
        if ($schema === '') {
487 1
            $schema = $this->defaultSchema;
488
        }
489
490 3
        $sql = <<<SQL
491
        SELECT c.relname AS table_name
492
        FROM pg_class c
493
        INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace
494
        WHERE ns.nspname = :schemaName AND (c.relkind = 'v' OR c.relkind = 'm')
495
        ORDER BY c.relname
496 3
        SQL;
497
498 3
        return $this->db->createCommand($sql, [':schemaName' => $schema])->queryColumn();
499
    }
500
501
    /**
502
     * Collects the foreign key column details for the given table.
503
     *
504
     * @param TableSchemaInterface $table The table metadata
505
     *
506
     * @throws Exception
507
     * @throws InvalidConfigException
508
     * @throws Throwable
509
     */
510 167
    protected function findConstraints(TableSchemaInterface $table): void
511
    {
512
        /**
513
         * We need to extract the constraints de hard way since:
514
         * {@see https://www.postgresql.org/message-id/[email protected]}
515
         */
516
517 167
        $sql = <<<SQL
518
        SELECT
519
            ct.conname as constraint_name,
520
            a.attname as column_name,
521
            fc.relname as foreign_table_name,
522
            fns.nspname as foreign_table_schema,
523
            fa.attname as foreign_column_name
524
            FROM
525
            (SELECT ct.conname, ct.conrelid, ct.confrelid, ct.conkey, ct.contype, ct.confkey,
526
                generate_subscripts(ct.conkey, 1) AS s
527
                FROM pg_constraint ct
528
            ) AS ct
529
            inner join pg_class c on c.oid=ct.conrelid
530
            inner join pg_namespace ns on c.relnamespace=ns.oid
531
            inner join pg_attribute a on a.attrelid=ct.conrelid and a.attnum = ct.conkey[ct.s]
532
            left join pg_class fc on fc.oid=ct.confrelid
533
            left join pg_namespace fns on fc.relnamespace=fns.oid
534
            left join pg_attribute fa on fa.attrelid=ct.confrelid and fa.attnum = ct.confkey[ct.s]
535
        WHERE
536
            ct.contype='f'
537
            and c.relname=:tableName
538
            and ns.nspname=:schemaName
539
        ORDER BY
540
            fns.nspname, fc.relname, a.attnum
541 167
        SQL;
542
543
        /** @psalm-var array{array{tableName: string, columns: array}} $constraints */
544 167
        $constraints = [];
545
546
        /** @psalm-var array<FindConstraintArray> $rows */
547 167
        $rows = $this->db->createCommand($sql, [
548 167
            ':schemaName' => $table->getSchemaName(),
549 167
            ':tableName' => $table->getName(),
550 167
        ])->queryAll();
551
552 167
        foreach ($rows as $constraint) {
553
            /** @psalm-var FindConstraintArray $constraint */
554 16
            $constraint = $this->normalizeRowKeyCase($constraint, false);
555
556 16
            if ($constraint['foreign_table_schema'] !== $this->defaultSchema) {
557 3
                $foreignTable = $constraint['foreign_table_schema'] . '.' . $constraint['foreign_table_name'];
558
            } else {
559 16
                $foreignTable = $constraint['foreign_table_name'];
560
            }
561
562 16
            $name = $constraint['constraint_name'];
563
564 16
            if (!isset($constraints[$name])) {
565 16
                $constraints[$name] = [
566 16
                    'tableName' => $foreignTable,
567 16
                    'columns' => [],
568 16
                ];
569
            }
570
571 16
            $constraints[$name]['columns'][$constraint['column_name']] = $constraint['foreign_column_name'];
572
        }
573
574
        /**
575
         * @psalm-var int|string $foreingKeyName.
576
         * @psalm-var array{tableName: string, columns: array} $constraint
577
         */
578 167
        foreach ($constraints as $foreingKeyName => $constraint) {
579 16
            $table->foreignKey(
580 16
                (string) $foreingKeyName,
581 16
                array_merge([$constraint['tableName']], $constraint['columns'])
582 16
            );
583
        }
584
    }
585
586
    /**
587
     * Gets information about given table unique indexes.
588
     *
589
     * @param TableSchemaInterface $table The table metadata.
590
     *
591
     * @throws Exception
592
     * @throws InvalidConfigException
593
     * @throws Throwable
594
     *
595
     * @return array With index and column names.
596
     */
597 1
    protected function getUniqueIndexInformation(TableSchemaInterface $table): array
598
    {
599 1
        $sql = <<<'SQL'
600
        SELECT
601
            i.relname as indexname,
602
            pg_get_indexdef(idx.indexrelid, k + 1, TRUE) AS columnname
603
        FROM (
604
            SELECT *, generate_subscripts(indkey, 1) AS k
605
            FROM pg_index
606
        ) idx
607
        INNER JOIN pg_class i ON i.oid = idx.indexrelid
608
        INNER JOIN pg_class c ON c.oid = idx.indrelid
609
        INNER JOIN pg_namespace ns ON c.relnamespace = ns.oid
610
        WHERE idx.indisprimary = FALSE AND idx.indisunique = TRUE
611
        AND c.relname = :tableName AND ns.nspname = :schemaName
612
        ORDER BY i.relname, k
613 1
        SQL;
614
615 1
        return $this->db->createCommand($sql, [
616 1
            ':schemaName' => $table->getSchemaName(),
617 1
            ':tableName' => $table->getName(),
618 1
        ])->queryAll();
619
    }
620
621
    /**
622
     * Returns all unique indexes for the given table.
623
     *
624
     * Each array element is of the following structure:
625
     *
626
     * ```php
627
     * [
628
     *     'IndexName1' => ['col1' [, ...]],
629
     *     'IndexName2' => ['col2' [, ...]],
630
     * ]
631
     * ```
632
     *
633
     * @param TableSchemaInterface $table The table metadata
634
     *
635
     * @throws Exception
636
     * @throws InvalidConfigException
637
     * @throws Throwable
638
     *
639
     * @return array All unique indexes for the given table.
640
     */
641 1
    public function findUniqueIndexes(TableSchemaInterface $table): array
642
    {
643 1
        $uniqueIndexes = [];
644
645
        /** @psalm-var array{indexname: string, columnname: string} $row */
646 1
        foreach ($this->getUniqueIndexInformation($table) as $row) {
647
            /** @psalm-var array{indexname: string, columnname: string} $row */
648 1
            $row = $this->normalizeRowKeyCase($row, false);
649
650 1
            $column = $row['columnname'];
651
652 1
            if (str_starts_with($column, '"') && str_ends_with($column, '"')) {
653
                /**
654
                 * postgres will quote names that aren't lowercase-only.
655
                 *
656
                 * {@see https://github.com/yiisoft/yii2/issues/10613}
657
                 */
658 1
                $column = substr($column, 1, -1);
659
            }
660
661 1
            $uniqueIndexes[$row['indexname']][] = $column;
662
        }
663
664 1
        return $uniqueIndexes;
665
    }
666
667
    /**
668
     * Collects the metadata of table columns.
669
     *
670
     * @param TableSchemaInterface $table The table metadata.
671
     *
672
     * @throws Exception
673
     * @throws InvalidConfigException
674
     * @throws JsonException
675
     * @throws Throwable
676
     *
677
     * @return bool Whether the table exists in the database.
678
     */
679 189
    protected function findColumns(TableSchemaInterface $table): bool
680
    {
681 189
        $orIdentity = '';
682
683 189
        if (version_compare($this->db->getServerVersion(), '12.0', '>=')) {
684 182
            $orIdentity = 'OR a.attidentity != \'\'';
685
        }
686
687 189
        $sql = <<<SQL
688 189
        SELECT
689
            d.nspname AS table_schema,
690
            c.relname AS table_name,
691
            a.attname AS column_name,
692
            COALESCE(td.typname, tb.typname, t.typname) AS data_type,
693
            COALESCE(td.typtype, tb.typtype, t.typtype) AS type_type,
694
            (SELECT nspname FROM pg_namespace WHERE oid = COALESCE(td.typnamespace, tb.typnamespace, t.typnamespace)) AS type_scheme,
695
            a.attlen AS character_maximum_length,
696
            pg_catalog.col_description(c.oid, a.attnum) AS column_comment,
697
            information_schema._pg_truetypmod(a, t) AS modifier,
698
            NOT (a.attnotnull OR t.typnotnull) AS is_nullable,
699
            COALESCE(t.typdefault, pg_get_expr(ad.adbin, ad.adrelid)) AS column_default,
700 189
            COALESCE(pg_get_expr(ad.adbin, ad.adrelid) ~ 'nextval', false) $orIdentity AS is_autoinc,
701
            pg_get_serial_sequence(quote_ident(d.nspname) || '.' || quote_ident(c.relname), a.attname)
702
            AS sequence_name,
703
            CASE WHEN COALESCE(td.typtype, tb.typtype, t.typtype) = 'e'::char
704
                THEN array_to_string(
705
                    (
706
                        SELECT array_agg(enumlabel)
707
                        FROM pg_enum
708
                        WHERE enumtypid = COALESCE(td.oid, tb.oid, a.atttypid)
709
                    )::varchar[],
710
                ',')
711
                ELSE NULL
712
            END AS enum_values,
713
            information_schema._pg_numeric_precision(
714
                COALESCE(td.oid, tb.oid, a.atttypid),
715
                information_schema._pg_truetypmod(a, t)
716
            ) AS numeric_precision,
717
            information_schema._pg_numeric_scale(
718
                COALESCE(td.oid, tb.oid, a.atttypid),
719
                information_schema._pg_truetypmod(a, t)
720
            ) AS numeric_scale,
721
            information_schema._pg_char_max_length(
722
                COALESCE(td.oid, tb.oid, a.atttypid),
723
                information_schema._pg_truetypmod(a, t)
724
            ) AS size,
725
            ct.oid IS NOT NULL AS is_pkey,
726
            COALESCE(NULLIF(a.attndims, 0), NULLIF(t.typndims, 0), (t.typcategory='A')::int) AS dimension
727
        FROM
728
            pg_class c
729
            LEFT JOIN pg_attribute a ON a.attrelid = c.oid
730
            LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum
731
            LEFT JOIN pg_type t ON a.atttypid = t.oid
732
            LEFT JOIN pg_type tb ON (a.attndims > 0 OR t.typcategory='A') AND t.typelem > 0 AND t.typelem = tb.oid
733
                                        OR t.typbasetype > 0 AND t.typbasetype = tb.oid
734
            LEFT JOIN pg_type td ON t.typndims > 0 AND t.typbasetype > 0 AND tb.typelem = td.oid
735
            LEFT JOIN pg_namespace d ON d.oid = c.relnamespace
736
            LEFT JOIN pg_rewrite rw ON c.relkind = 'v' AND rw.ev_class = c.oid AND rw.rulename = '_RETURN'
737
            LEFT JOIN pg_constraint ct ON ct.conrelid = c.oid AND ct.contype = 'p' AND a.attnum = ANY (ct.conkey)
738
                OR rw.ev_action IS NOT NULL AND ct.contype = 'p'
739
                AND (ARRAY(
740
                    SELECT regexp_matches(rw.ev_action, '{TARGETENTRY .*? :resorigtbl (\d+) :resorigcol (\d+) ', 'g')
741
                ))[a.attnum:a.attnum] <@ (ct.conrelid::text || ct.conkey::text[])
742
        WHERE
743
            a.attnum > 0 AND t.typname != '' AND NOT a.attisdropped
744
            AND c.relname = :tableName
745
            AND d.nspname = :schemaName
746
        ORDER BY
747
            a.attnum;
748 189
        SQL;
749
750 189
        $columns = $this->db->createCommand($sql, [
751 189
            ':schemaName' => $table->getSchemaName(),
752 189
            ':tableName' => $table->getName(),
753 189
        ])->queryAll();
754
755 189
        if (empty($columns)) {
756 43
            return false;
757
        }
758
759
        /** @psalm-var ColumnArray $info */
760 167
        foreach ($columns as $info) {
761
            /** @psalm-var ColumnArray $info */
762 167
            $info = $this->normalizeRowKeyCase($info, false);
763
764
            /** @psalm-var ColumnSchema $column */
765 167
            $column = $this->loadColumnSchema($info);
766
767 167
            $table->column($column->getName(), $column);
768
769 167
            if ($column->isPrimaryKey()) {
770 102
                $table->primaryKey($column->getName());
771
772 102
                if ($table->getSequenceName() === null) {
773 102
                    $table->sequenceName($column->getSequenceName());
774
                }
775
            }
776
        }
777
778 167
        return true;
779
    }
780
781
    /**
782
     * Loads the column information into a {@see ColumnSchemaInterface} object.
783
     *
784
     * @psalm-param ColumnArray $info Column information.
785
     *
786
     * @return ColumnSchemaInterface The column schema object.
787
     */
788 167
    protected function loadColumnSchema(array $info): ColumnSchemaInterface
789
    {
790 167
        $column = $this->createColumnSchema($info['column_name']);
791 167
        $column->allowNull($info['is_nullable']);
792 167
        $column->autoIncrement($info['is_autoinc']);
793 167
        $column->comment($info['column_comment']);
794
795 167
        if (!in_array($info['type_scheme'], [$this->defaultSchema, 'pg_catalog'], true)) {
796 1
            $column->dbType($info['type_scheme'] . '.' . $info['data_type']);
797
        } else {
798 167
            $column->dbType($info['data_type']);
799
        }
800
801 167
        $column->enumValues($info['enum_values'] !== null
802 1
            ? explode(',', str_replace(["''"], ["'"], $info['enum_values']))
803 167
            : null);
804 167
        $column->unsigned(false); // has no meaning in PG
805 167
        $column->primaryKey((bool) $info['is_pkey']);
806 167
        $column->precision($info['numeric_precision']);
807 167
        $column->scale($info['numeric_scale']);
808 167
        $column->size($info['size'] === null ? null : (int) $info['size']);
809 167
        $column->dimension($info['dimension']);
810
811
        /**
812
         * pg_get_serial_sequence() doesn't track DEFAULT value change.
813
         * GENERATED BY IDENTITY columns always have a null default value.
814
         */
815 167
        $defaultValue = $info['column_default'];
816
817
        if (
818 167
            $defaultValue !== null
819 167
            && preg_match("/^nextval\('([^']+)/", $defaultValue, $matches) === 1
820
        ) {
821 81
            $column->sequenceName($matches[1]);
822 167
        } elseif ($info['sequence_name'] !== null) {
823 5
            $column->sequenceName($this->resolveTableName($info['sequence_name'])->getFullName());
824
        }
825
826 167
        if ($info['type_type'] === 'c') {
827 5
            $column->type(self::TYPE_COMPOSITE);
828 5
            $composite = $this->resolveTableName((string) $column->getDbType());
829
830 5
            if ($this->findColumns($composite)) {
831 5
                $column->columns($composite->getColumns());
832
            }
833
        } else {
834 167
            $column->type(self::TYPE_MAP[(string) $column->getDbType()] ?? self::TYPE_STRING);
835
        }
836
837 167
        $column->phpType($this->getColumnPhpType($column));
838 167
        $column->defaultValue($this->normalizeDefaultValue($defaultValue, $column));
839
840 167
        if ($column->getType() === self::TYPE_COMPOSITE && $column->getDimension() === 0) {
841
            /** @psalm-var array|null $defaultValue */
842 5
            $defaultValue = $column->getDefaultValue();
843 5
            if (is_array($defaultValue)) {
844 5
                foreach ($column->getColumns() as $compositeColumnName => $compositeColumn) {
845 5
                    $compositeColumn->defaultValue($defaultValue[$compositeColumnName] ?? null);
846
                }
847
            }
848
        }
849
850 167
        return $column;
851
    }
852
853
    /**
854
     * Extracts the PHP type from an abstract DB type.
855
     *
856
     * @param ColumnSchemaInterface $column The column schema information.
857
     *
858
     * @return string The PHP type name.
859
     */
860 167
    protected function getColumnPhpType(ColumnSchemaInterface $column): string
861
    {
862 167
        return match ($column->getType()) {
863 167
            self::TYPE_BIT => self::PHP_TYPE_INTEGER,
864 167
            self::TYPE_COMPOSITE => self::PHP_TYPE_ARRAY,
865 167
            default => parent::getColumnPhpType($column),
866 167
        };
867
    }
868
869
    /**
870
     * Converts column's default value according to {@see ColumnSchema::phpType} after retrieval from the database.
871
     *
872
     * @param string|null $defaultValue The default value retrieved from the database.
873
     * @param ColumnSchemaInterface $column The column schema object.
874
     *
875
     * @return mixed The normalized default value.
876
     */
877 167
    private function normalizeDefaultValue(string|null $defaultValue, ColumnSchemaInterface $column): mixed
878
    {
879
        if (
880 167
            $defaultValue === null
881 128
            || $column->isPrimaryKey()
882 167
            || str_starts_with($defaultValue, 'NULL::')
883
        ) {
884 163
            return null;
885
        }
886
887 99
        if ($column->getType() === self::TYPE_BOOLEAN && in_array($defaultValue, ['true', 'false'], true)) {
888 71
            return $defaultValue === 'true';
889
        }
890
891
        if (
892 98
            in_array($column->getType(), [self::TYPE_TIMESTAMP, self::TYPE_DATE, self::TYPE_TIME], true)
893 98
            && in_array(strtoupper($defaultValue), ['NOW()', 'CURRENT_TIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIME'], true)
894
        ) {
895 39
            return new Expression($defaultValue);
896
        }
897
898 98
        $value = preg_replace("/^B?['(](.*?)[)'](?:::[^:]+)?$/s", '$1', $defaultValue);
899 98
        $value = str_replace("''", "'", $value);
900
901 98
        if ($column->getType() === self::TYPE_BINARY && str_starts_with($value, '\\x')) {
902 39
            return hex2bin(substr($value, 2));
903
        }
904
905 98
        return $column->phpTypecast($value);
906
    }
907
908
    /**
909
     * Loads multiple types of constraints and returns the specified ones.
910
     *
911
     * @param string $tableName The table name.
912
     * @param string $returnType The return type:
913
     * - primaryKey
914
     * - foreignKeys
915
     * - uniques
916
     * - checks
917
     *
918
     * @throws Exception
919
     * @throws InvalidConfigException
920
     * @throws Throwable
921
     *
922
     * @return array|Constraint|null Constraints.
923
     *
924
     * @psalm-return CheckConstraint[]|Constraint[]|ForeignKeyConstraint[]|Constraint|null
925
     */
926 85
    private function loadTableConstraints(string $tableName, string $returnType): array|Constraint|null
927
    {
928 85
        $sql = <<<SQL
929
        SELECT
930
            "c"."conname" AS "name",
931
            "a"."attname" AS "column_name",
932
            "c"."contype" AS "type",
933
            "ftcns"."nspname" AS "foreign_table_schema",
934
            "ftc"."relname" AS "foreign_table_name",
935
            "fa"."attname" AS "foreign_column_name",
936
            "c"."confupdtype" AS "on_update",
937
            "c"."confdeltype" AS "on_delete",
938
            pg_get_constraintdef("c"."oid") AS "check_expr"
939
        FROM "pg_class" AS "tc"
940
        INNER JOIN "pg_namespace" AS "tcns"
941
            ON "tcns"."oid" = "tc"."relnamespace"
942
        INNER JOIN "pg_attribute" AS "a"
943
            ON "a"."attrelid" = "tc"."oid"
944
        LEFT JOIN pg_rewrite AS rw
945
            ON "tc"."relkind" = 'v' AND "rw"."ev_class" = "tc"."oid" AND "rw"."rulename" = '_RETURN'
946
        INNER JOIN "pg_constraint" AS "c"
947
            ON "c"."conrelid" = "tc"."oid" AND "a"."attnum" = ANY ("c"."conkey")
948
                OR "rw"."ev_action" IS NOT NULL AND "c"."conrelid" != 0
949
                AND (ARRAY(
950
                    SELECT regexp_matches("rw"."ev_action", '{TARGETENTRY .*? :resorigtbl (\d+) :resorigcol (\d+) ', 'g')
951
                ))["a"."attnum":"a"."attnum"] <@ ("c"."conrelid"::text || "c"."conkey"::text[])
952
        LEFT JOIN "pg_class" AS "ftc"
953
            ON "ftc"."oid" = "c"."confrelid"
954
        LEFT JOIN "pg_namespace" AS "ftcns"
955
            ON "ftcns"."oid" = "ftc"."relnamespace"
956
        LEFT JOIN "pg_attribute" "fa"
957
            ON "fa"."attrelid" = "c"."confrelid" AND "fa"."attnum" = ANY ("c"."confkey")
958
        WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName
959
        ORDER BY "a"."attnum" ASC, "fa"."attnum" ASC
960 85
        SQL;
961
962
        /** @psalm-var string[] $actionTypes */
963 85
        $actionTypes = [
964 85
            'a' => 'NO ACTION',
965 85
            'r' => 'RESTRICT',
966 85
            'c' => 'CASCADE',
967 85
            'n' => 'SET NULL',
968 85
            'd' => 'SET DEFAULT',
969 85
        ];
970
971 85
        $resolvedName = $this->resolveTableName($tableName);
972 85
        $constraints = $this->db->createCommand($sql, [
973 85
            ':schemaName' => $resolvedName->getSchemaName(),
974 85
            ':tableName' => $resolvedName->getName(),
975 85
        ])->queryAll();
976
977
        /** @psalm-var array[][] $constraints */
978 85
        $constraints = $this->normalizeRowKeyCase($constraints, true);
979 85
        $constraints = DbArrayHelper::index($constraints, null, ['type', 'name']);
980
981 85
        $result = [
982 85
            self::PRIMARY_KEY => null,
983 85
            self::FOREIGN_KEYS => [],
984 85
            self::UNIQUES => [],
985 85
            self::CHECKS => [],
986 85
        ];
987
988
        /**
989
         * @psalm-var string $type
990
         * @psalm-var array $names
991
         */
992 85
        foreach ($constraints as $type => $names) {
993
            /**
994
             * @psalm-var object|string|null $name
995
             * @psalm-var ConstraintArray $constraint
996
             */
997 85
            foreach ($names as $name => $constraint) {
998
                switch ($type) {
999 85
                    case 'p':
1000 60
                        $result[self::PRIMARY_KEY] = (new Constraint())
1001 60
                            ->name($name)
1002 60
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'));
1003 60
                        break;
1004 75
                    case 'f':
1005 19
                        $onDelete = $actionTypes[$constraint[0]['on_delete']] ?? null;
1006 19
                        $onUpdate = $actionTypes[$constraint[0]['on_update']] ?? null;
1007
1008 19
                        $result[self::FOREIGN_KEYS][] = (new ForeignKeyConstraint())
1009 19
                            ->name($name)
1010 19
                            ->columnNames(array_values(
1011 19
                                array_unique(DbArrayHelper::getColumn($constraint, 'column_name'))
1012 19
                            ))
1013 19
                            ->foreignSchemaName($constraint[0]['foreign_table_schema'])
1014 19
                            ->foreignTableName($constraint[0]['foreign_table_name'])
1015 19
                            ->foreignColumnNames(array_values(
1016 19
                                array_unique(DbArrayHelper::getColumn($constraint, 'foreign_column_name'))
1017 19
                            ))
1018 19
                            ->onDelete($onDelete)
1019 19
                            ->onUpdate($onUpdate);
1020 19
                        break;
1021 62
                    case 'u':
1022 59
                        $result[self::UNIQUES][] = (new Constraint())
1023 59
                            ->name($name)
1024 59
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'));
1025 59
                        break;
1026 15
                    case 'c':
1027 15
                        $result[self::CHECKS][] = (new CheckConstraint())
1028 15
                            ->name($name)
1029 15
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'))
1030 15
                            ->expression($constraint[0]['check_expr']);
1031 15
                        break;
1032
                }
1033
            }
1034
        }
1035
1036 85
        foreach ($result as $type => $data) {
1037 85
            $this->setTableMetadata($tableName, $type, $data);
1038
        }
1039
1040 85
        return $result[$returnType];
1041
    }
1042
1043
    /**
1044
     * Creates a column schema for the database.
1045
     *
1046
     * This method may be overridden by child classes to create a DBMS-specific column schema.
1047
     *
1048
     * @param string $name Name of the column.
1049
     *
1050
     * @return ColumnSchema
1051
     */
1052 167
    private function createColumnSchema(string $name): ColumnSchema
1053
    {
1054 167
        return new ColumnSchema($name);
1055
    }
1056
1057
    /**
1058
     * Returns the cache key for the specified table name.
1059
     *
1060
     * @param string $name The table name.
1061
     *
1062
     * @return array The cache key.
1063
     */
1064 280
    protected function getCacheKey(string $name): array
1065
    {
1066 280
        return array_merge([self::class], $this->generateCacheKey(), [$this->getRawTableName($name)]);
1067
    }
1068
1069
    /**
1070
     * Returns the cache tag name.
1071
     *
1072
     * This allows {@see refresh()} to invalidate all cached table schemas.
1073
     *
1074
     * @return string The cache tag name.
1075
     */
1076 246
    protected function getCacheTag(): string
1077
    {
1078 246
        return md5(serialize(array_merge([self::class], $this->generateCacheKey())));
1079
    }
1080
}
1081