Passed
Pull Request — master (#307)
by
unknown
04:21
created

Schema::findConstraints()   B

Complexity

Conditions 5
Paths 10

Size

Total Lines 72
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 5

Importance

Changes 7
Bugs 0 Features 0
Metric Value
cc 5
eloc 46
c 7
b 0
f 0
nc 10
nop 1
dl 0
loc 72
ccs 24
cts 24
cp 1
crap 5
rs 8.867

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Pgsql;
6
7
use JsonException;
8
use Throwable;
9
use Yiisoft\Db\Constraint\CheckConstraint;
10
use Yiisoft\Db\Constraint\Constraint;
11
use Yiisoft\Db\Constraint\DefaultValueConstraint;
12
use Yiisoft\Db\Constraint\ForeignKeyConstraint;
13
use Yiisoft\Db\Constraint\IndexConstraint;
14
use Yiisoft\Db\Driver\Pdo\AbstractPdoSchema;
15
use Yiisoft\Db\Exception\Exception;
16
use Yiisoft\Db\Exception\InvalidConfigException;
17
use Yiisoft\Db\Exception\NotSupportedException;
18
use Yiisoft\Db\Expression\Expression;
19
use Yiisoft\Db\Helper\DbArrayHelper;
20
use Yiisoft\Db\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
        'jsonb' => self::TYPE_JSON,
175
        'xml' => self::TYPE_STRING,
176
    ];
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
    protected string|array $tableQuoteCharacter = '"';
189
190 14
    public function createColumn(string $type, array|int|string $length = null): ColumnInterface
191
    {
192 14
        return new Column($type, $length);
193
    }
194
195
    /**
196
     * Resolves the table name and schema name (if any).
197
     *
198
     * @param string $name The table name.
199
     *
200
     * @return TableSchemaInterface With resolved table, schema, etc. names.
201
     *
202
     * @see TableSchemaInterface
203
     */
204 234
    protected function resolveTableName(string $name): TableSchemaInterface
205
    {
206 234
        $resolvedName = new TableSchema();
207
208 234
        $parts = array_reverse($this->db->getQuoter()->getTableNameParts($name));
209 234
        $resolvedName->name($parts[0] ?? '');
210 234
        $resolvedName->schemaName($parts[1] ?? $this->defaultSchema);
211
212 234
        $resolvedName->fullName(
213 234
            $resolvedName->getSchemaName() !== $this->defaultSchema ?
214 234
            implode('.', array_reverse($parts)) : $resolvedName->getName()
215 234
        );
216
217 234
        return $resolvedName;
218
    }
219
220
    /**
221
     * Returns all schema names in the database, including the default one but not system schemas.
222
     *
223
     * This method should be overridden by child classes to support this feature because the default implementation
224
     * simply throws an exception.
225
     *
226
     * @throws Exception
227
     * @throws InvalidConfigException
228
     * @throws Throwable
229
     *
230
     * @return array All schemas name in the database, except system schemas.
231
     */
232 1
    protected function findSchemaNames(): array
233
    {
234 1
        $sql = <<<SQL
235
        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 1
        SQL;
240
241 1
        return $this->db->createCommand($sql)->queryColumn();
242
    }
243
244
    /**
245
     * @throws Exception
246
     * @throws InvalidConfigException
247
     * @throws Throwable
248
     */
249 182
    protected function findTableComment(TableSchemaInterface $tableSchema): void
250
    {
251 182
        $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 182
        SQL;
259
260 182
        $comment = $this->db->createCommand($sql, [
261 182
            ':schemaName' => $tableSchema->getSchemaName(),
262 182
            ':tableName' => $tableSchema->getName(),
263 182
        ])->queryScalar();
264
265 182
        $tableSchema->comment(is_string($comment) ? $comment : null);
266
    }
267
268
    /**
269
     * Returns all table names in the database.
270
     *
271
     * This method should be overridden by child classes to support this feature because the default implementation
272
     * simply throws an exception.
273
     *
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
     * @throws Throwable
280
     *
281
     * @return array All tables name in the database. The names have NO schema name prefix.
282
     */
283 12
    protected function findTableNames(string $schema = ''): array
284
    {
285 12
        if ($schema === '') {
286 11
            $schema = $this->defaultSchema;
287
        }
288
289 12
        $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 12
        SQL;
296
297 12
        return $this->db->createCommand($sql, [':schemaName' => $schema])->queryColumn();
298
    }
299
300
    /**
301
     * Loads the metadata for the specified table.
302
     *
303
     * @param string $name The table name.
304
     *
305
     * @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 182
    protected function loadTableSchema(string $name): TableSchemaInterface|null
312
    {
313 182
        $table = $this->resolveTableName($name);
314 182
        $this->findTableComment($table);
315
316 182
        if ($this->findColumns($table)) {
317 160
            $this->findConstraints($table);
318 160
            return $table;
319
        }
320
321 43
        return null;
322
    }
323
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 40
    protected function loadTablePrimaryKey(string $tableName): Constraint|null
336
    {
337 40
        $tablePrimaryKey = $this->loadTableConstraints($tableName, self::PRIMARY_KEY);
338
339 40
        return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
340
    }
341
342
    /**
343
     * 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 8
    protected function loadTableForeignKeys(string $tableName): array
356
    {
357 8
        $tableForeignKeys = $this->loadTableConstraints($tableName, self::FOREIGN_KEYS);
358
359 8
        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 38
    protected function loadTableIndexes(string $tableName): array
374
    {
375 38
        $sql = <<<SQL
376
        SELECT
377
            "ic"."relname" AS "name",
378
            "ia"."attname" AS "column_name",
379
            "i"."indisunique" AS "index_is_unique",
380
            "i"."indisprimary" AS "index_is_primary"
381
        FROM "pg_class" AS "tc"
382
        INNER JOIN "pg_namespace" AS "tcns"
383
            ON "tcns"."oid" = "tc"."relnamespace"
384
        INNER JOIN "pg_index" AS "i"
385
            ON "i"."indrelid" = "tc"."oid"
386
        INNER JOIN "pg_class" AS "ic"
387
            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 38
        SQL;
393
394 38
        $resolvedName = $this->resolveTableName($tableName);
395 38
        $indexes = $this->db->createCommand($sql, [
396 38
            ':schemaName' => $resolvedName->getSchemaName(),
397 38
            ':tableName' => $resolvedName->getName(),
398 38
        ])->queryAll();
399
400
        /** @psalm-var array[] $indexes */
401 38
        $indexes = $this->normalizeRowKeyCase($indexes, true);
402 38
        $indexes = DbArrayHelper::index($indexes, null, ['name']);
403 38
        $result = [];
404
405
        /**
406
         * @psalm-var object|string|null $name
407
         * @psalm-var array<
408
         *   array-key,
409
         *   array{
410
         *     name: string,
411
         *     column_name: string,
412
         *     index_is_unique: bool,
413
         *     index_is_primary: bool
414
         *   }
415
         * > $index
416
         */
417 38
        foreach ($indexes as $name => $index) {
418 35
            $ic = (new IndexConstraint())
419 35
                ->name($name)
420 35
                ->columnNames(DbArrayHelper::getColumn($index, 'column_name'))
421 35
                ->primary($index[0]['index_is_primary'])
422 35
                ->unique($index[0]['index_is_unique']);
423
424 35
            $result[] = $ic;
425
        }
426
427 38
        return $result;
428
    }
429
430
    /**
431
     * 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 17
    protected function loadTableUniques(string $tableName): array
444
    {
445 17
        $tableUniques = $this->loadTableConstraints($tableName, self::UNIQUES);
446
447 17
        return is_array($tableUniques) ? $tableUniques : [];
448
    }
449
450
    /**
451
     * 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 17
    protected function loadTableChecks(string $tableName): array
464
    {
465 17
        $tableChecks = $this->loadTableConstraints($tableName, self::CHECKS);
466
467 17
        return is_array($tableChecks) ? $tableChecks : [];
468
    }
469
470
    /**
471
     * Loads all default value constraints for the given table.
472
     *
473
     * @param string $tableName The table name.
474
     *
475
     * @throws NotSupportedException
476
     *
477
     * @return DefaultValueConstraint[] Default value constraints for the given table.
478
     */
479 13
    protected function loadTableDefaultValues(string $tableName): array
480
    {
481 13
        throw new NotSupportedException(__METHOD__ . ' is not supported by PostgreSQL.');
482
    }
483
484
    /**
485
     * @throws Exception
486
     * @throws InvalidConfigException
487
     * @throws Throwable
488
     */
489 3
    protected function findViewNames(string $schema = ''): array
490
    {
491 3
        if ($schema === '') {
492 1
            $schema = $this->defaultSchema;
493
        }
494
495 3
        $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
        WHERE ns.nspname = :schemaName AND (c.relkind = 'v' OR c.relkind = 'm')
500
        ORDER BY c.relname
501 3
        SQL;
502
503 3
        return $this->db->createCommand($sql, [':schemaName' => $schema])->queryColumn();
504
    }
505
506
    /**
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 160
    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 160
        $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
            (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
            ) 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
            inner join pg_attribute a on a.attrelid=ct.conrelid and a.attnum = ct.conkey[ct.s]
537
            left join pg_class fc on fc.oid=ct.confrelid
538
            left join pg_namespace fns on fc.relnamespace=fns.oid
539
            left join pg_attribute fa on fa.attrelid=ct.confrelid and fa.attnum = ct.confkey[ct.s]
540
        WHERE
541
            ct.contype='f'
542
            and c.relname=:tableName
543
            and ns.nspname=:schemaName
544
        ORDER BY
545
            fns.nspname, fc.relname, a.attnum
546 160
        SQL;
547
548
        /** @psalm-var array{array{tableName: string, columns: array}} $constraints */
549 160
        $constraints = [];
550
551
        /** @psalm-var array<FindConstraintArray> $rows */
552 160
        $rows = $this->db->createCommand($sql, [
553 160
            ':schemaName' => $table->getSchemaName(),
554 160
            ':tableName' => $table->getName(),
555 160
        ])->queryAll();
556
557 160
        foreach ($rows as $constraint) {
558
            /** @psalm-var FindConstraintArray $constraint */
559 16
            $constraint = $this->normalizeRowKeyCase($constraint, false);
560
561 16
            if ($constraint['foreign_table_schema'] !== $this->defaultSchema) {
562 3
                $foreignTable = $constraint['foreign_table_schema'] . '.' . $constraint['foreign_table_name'];
563
            } else {
564 16
                $foreignTable = $constraint['foreign_table_name'];
565
            }
566
567 16
            $name = $constraint['constraint_name'];
568
569 16
            if (!isset($constraints[$name])) {
570 16
                $constraints[$name] = [
571 16
                    'tableName' => $foreignTable,
572 16
                    'columns' => [],
573 16
                ];
574
            }
575
576 16
            $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 160
        foreach ($constraints as $foreingKeyName => $constraint) {
584 16
            $table->foreignKey(
585 16
                (string) $foreingKeyName,
586 16
                array_merge([$constraint['tableName']], $constraint['columns'])
587 16
            );
588
        }
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
        SELECT
606
            i.relname as indexname,
607
            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 1
        SQL;
619
620 1
        return $this->db->createCommand($sql, [
621 1
            ':schemaName' => $table->getSchemaName(),
622 1
            ':tableName' => $table->getName(),
623 1
        ])->queryAll();
624
    }
625
626
    /**
627
     * Returns all unique indexes for the given table.
628
     *
629
     * Each array element is of the following structure:
630
     *
631
     * ```php
632
     * [
633
     *     'IndexName1' => ['col1' [, ...]],
634
     *     'IndexName2' => ['col2' [, ...]],
635
     * ]
636
     * ```
637
     *
638
     * @param TableSchemaInterface $table The table metadata
639
     *
640
     * @throws Exception
641
     * @throws InvalidConfigException
642
     * @throws Throwable
643
     *
644
     * @return array All unique indexes for the given table.
645
     */
646 1
    public function findUniqueIndexes(TableSchemaInterface $table): array
647
    {
648 1
        $uniqueIndexes = [];
649
650
        /** @psalm-var array{indexname: string, columnname: string} $row */
651 1
        foreach ($this->getUniqueIndexInformation($table) as $row) {
652
            /** @psalm-var array{indexname: string, columnname: string} $row */
653 1
            $row = $this->normalizeRowKeyCase($row, false);
654
655 1
            $column = $row['columnname'];
656
657 1
            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 1
                $column = substr($column, 1, -1);
664
            }
665
666 1
            $uniqueIndexes[$row['indexname']][] = $column;
667
        }
668
669 1
        return $uniqueIndexes;
670
    }
671
672
    /**
673
     * Collects the metadata of table columns.
674
     *
675
     * @param TableSchemaInterface $table The table metadata.
676
     *
677
     * @throws Exception
678
     * @throws InvalidConfigException
679
     * @throws JsonException
680
     * @throws Throwable
681
     *
682
     * @return bool Whether the table exists in the database.
683
     */
684 182
    protected function findColumns(TableSchemaInterface $table): bool
685
    {
686 182
        $orIdentity = '';
687
688 182
        if (version_compare($this->db->getServerVersion(), '12.0', '>=')) {
689 175
            $orIdentity = 'OR a.attidentity != \'\'';
690
        }
691
692 182
        $sql = <<<SQL
693 182
        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 182
            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
        FROM
733
            pg_class c
734
            LEFT JOIN pg_attribute a ON a.attrelid = c.oid
735
            LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum
736
            LEFT JOIN pg_type t ON a.atttypid = t.oid
737
            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
            LEFT JOIN pg_type td ON t.typndims > 0 AND t.typbasetype > 0 AND tb.typelem = td.oid
740
            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
            AND c.relname = :tableName
745
            AND d.nspname = :schemaName
746
        ORDER BY
747
            a.attnum;
748 182
        SQL;
749
750 182
        $columns = $this->db->createCommand($sql, [
751 182
            ':schemaName' => $table->getSchemaName(),
752 182
            ':tableName' => $table->getName(),
753 182
        ])->queryAll();
754
755 182
        if (empty($columns)) {
756 43
            return false;
757
        }
758
759
        /** @psalm-var ColumnArray $info */
760 160
        foreach ($columns as $info) {
761
            /** @psalm-var ColumnArray $info */
762 160
            $info = $this->normalizeRowKeyCase($info, false);
763
764
            /** @psalm-var ColumnSchema $column */
765 160
            $column = $this->loadColumnSchema($info);
766
767 160
            $table->column($column->getName(), $column);
768
769 160
            if ($column->isPrimaryKey()) {
770 99
                $table->primaryKey($column->getName());
771
772 99
                if ($table->getSequenceName() === null) {
773 99
                    $table->sequenceName($column->getSequenceName());
774
                }
775
            }
776
        }
777
778 160
        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 160
    protected function loadColumnSchema(array $info): ColumnSchemaInterface
789
    {
790 160
        $column = $this->createColumnSchema($info['column_name']);
791 160
        $column->allowNull($info['is_nullable']);
792 160
        $column->autoIncrement($info['is_autoinc']);
793 160
        $column->comment($info['column_comment']);
794
795 160
        if (!in_array($info['type_scheme'], [$this->defaultSchema, 'pg_catalog'], true)) {
796 1
            $column->dbType($info['type_scheme'] . '.' . $info['data_type']);
797
        } else {
798 160
            $column->dbType($info['data_type']);
799
        }
800
801 160
        $column->enumValues($info['enum_values'] !== null
802 1
            ? explode(',', str_replace(["''"], ["'"], $info['enum_values']))
803 160
            : null);
804 160
        $column->unsigned(false); // has no meaning in PG
805 160
        $column->primaryKey((bool) $info['is_pkey']);
806 160
        $column->precision($info['numeric_precision']);
807 160
        $column->scale($info['numeric_scale']);
808 160
        $column->size($info['size'] === null ? null : (int) $info['size']);
809 160
        $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 160
        $defaultValue = $info['column_default'];
816
817
        if (
818 160
            $defaultValue !== null
819 160
            && preg_match("/nextval\\('\"?\\w+\"?\.?\"?\\w+\"?'(::regclass)?\\)/", $defaultValue) === 1
820
        ) {
821 82
            $column->sequenceName(preg_replace(
822 82
                ['/nextval/', '/::/', '/regclass/', '/\'\)/', '/\(\'/'],
823 82
                '',
824 82
                $defaultValue
825 82
            ));
826 160
        } elseif ($info['sequence_name'] !== null) {
827 5
            $column->sequenceName($this->resolveTableName($info['sequence_name'])->getFullName());
828
        }
829
830 160
        $column->type($this->typeMap[(string) $column->getDbType()] ?? self::TYPE_STRING);
831 160
        $column->phpType($this->getColumnPhpType($column));
832 160
        $column->defaultValue($this->normalizeDefaultValue($defaultValue, $column));
833
834 160
        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 160
    protected function getColumnPhpType(ColumnSchemaInterface $column): string
845
    {
846 160
        if ($column->getType() === self::TYPE_BIT) {
847 34
            return self::PHP_TYPE_INTEGER;
848
        }
849
850 160
        return parent::getColumnPhpType($column);
851
    }
852
853
    /**
854
     * Converts column's default value according to {@see ColumnSchema::phpType} after retrieval from the database.
855
     *
856
     * @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
     */
861 160
    private function normalizeDefaultValue(string|null $defaultValue, ColumnSchemaInterface $column): mixed
862
    {
863
        if (
864 160
            $defaultValue === null
865 124
            || $column->isPrimaryKey()
866 160
            || str_starts_with($defaultValue, 'NULL::')
867
        ) {
868 156
            return null;
869
        }
870
871 94
        if ($column->getType() === self::TYPE_BOOLEAN && in_array($defaultValue, ['true', 'false'], true)) {
872 66
            return $defaultValue === 'true';
873
        }
874
875
        if (
876 93
            in_array($column->getType(), [self::TYPE_TIMESTAMP, self::TYPE_DATE, self::TYPE_TIME], true)
877 93
            && in_array(strtoupper($defaultValue), ['NOW()', 'CURRENT_TIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIME'], true)
878
        ) {
879 34
            return new Expression($defaultValue);
880
        }
881
882 93
        $value = preg_replace("/^B?['(](.*?)[)'](?:::[^:]+)?$/s", '$1', $defaultValue);
883 93
        $value = str_replace("''", "'", $value);
884
885 93
        if ($column->getType() === self::TYPE_BINARY && str_starts_with($value, '\\x')) {
886 34
            return hex2bin(substr($value, 2));
887
        }
888
889 93
        return $column->phpTypecast($value);
890
    }
891
892
    /**
893
     * Loads multiple types of constraints and returns the specified ones.
894
     *
895
     * @param string $tableName The table name.
896
     * @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 82
    private function loadTableConstraints(string $tableName, string $returnType): array|Constraint|null
911
    {
912 82
        $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
            pg_get_constraintdef("c"."oid") AS "check_expr"
923
        FROM "pg_class" AS "tc"
924
        INNER JOIN "pg_namespace" AS "tcns"
925
            ON "tcns"."oid" = "tc"."relnamespace"
926
        INNER JOIN "pg_constraint" AS "c"
927
            ON "c"."conrelid" = "tc"."oid"
928
        INNER JOIN "pg_attribute" AS "a"
929
            ON "a"."attrelid" = "c"."conrelid" AND "a"."attnum" = ANY ("c"."conkey")
930
        LEFT JOIN "pg_class" AS "ftc"
931
            ON "ftc"."oid" = "c"."confrelid"
932
        LEFT JOIN "pg_namespace" AS "ftcns"
933
            ON "ftcns"."oid" = "ftc"."relnamespace"
934
        LEFT JOIN "pg_attribute" "fa"
935
            ON "fa"."attrelid" = "c"."confrelid" AND "fa"."attnum" = ANY ("c"."confkey")
936
        WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName
937
        ORDER BY "a"."attnum" ASC, "fa"."attnum" ASC
938 82
        SQL;
939
940
        /** @psalm-var string[] $actionTypes */
941 82
        $actionTypes = [
942 82
            'a' => 'NO ACTION',
943 82
            'r' => 'RESTRICT',
944 82
            'c' => 'CASCADE',
945 82
            'n' => 'SET NULL',
946 82
            'd' => 'SET DEFAULT',
947 82
        ];
948
949 82
        $resolvedName = $this->resolveTableName($tableName);
950 82
        $constraints = $this->db->createCommand($sql, [
951 82
            ':schemaName' => $resolvedName->getSchemaName(),
952 82
            ':tableName' => $resolvedName->getName(),
953 82
        ])->queryAll();
954
955
        /** @psalm-var array[][] $constraints */
956 82
        $constraints = $this->normalizeRowKeyCase($constraints, true);
957 82
        $constraints = DbArrayHelper::index($constraints, null, ['type', 'name']);
958
959 82
        $result = [
960 82
            self::PRIMARY_KEY => null,
961 82
            self::FOREIGN_KEYS => [],
962 82
            self::UNIQUES => [],
963 82
            self::CHECKS => [],
964 82
        ];
965
966
        /**
967
         * @psalm-var string $type
968
         * @psalm-var array $names
969
         */
970 82
        foreach ($constraints as $type => $names) {
971
            /**
972
             * @psalm-var object|string|null $name
973
             * @psalm-var ConstraintArray $constraint
974
             */
975 82
            foreach ($names as $name => $constraint) {
976
                switch ($type) {
977 82
                    case 'p':
978 57
                        $result[self::PRIMARY_KEY] = (new Constraint())
979 57
                            ->name($name)
980 57
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'));
981 57
                        break;
982 74
                    case 'f':
983 19
                        $onDelete = $actionTypes[$constraint[0]['on_delete']] ?? null;
984 19
                        $onUpdate = $actionTypes[$constraint[0]['on_update']] ?? null;
985
986 19
                        $result[self::FOREIGN_KEYS][] = (new ForeignKeyConstraint())
987 19
                            ->name($name)
988 19
                            ->columnNames(array_values(
989 19
                                array_unique(DbArrayHelper::getColumn($constraint, 'column_name'))
990 19
                            ))
991 19
                            ->foreignSchemaName($constraint[0]['foreign_table_schema'])
992 19
                            ->foreignTableName($constraint[0]['foreign_table_name'])
993 19
                            ->foreignColumnNames(array_values(
994 19
                                array_unique(DbArrayHelper::getColumn($constraint, 'foreign_column_name'))
995 19
                            ))
996 19
                            ->onDelete($onDelete)
997 19
                            ->onUpdate($onUpdate);
998 19
                        break;
999 61
                    case 'u':
1000 58
                        $result[self::UNIQUES][] = (new Constraint())
1001 58
                            ->name($name)
1002 58
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'));
1003 58
                        break;
1004 15
                    case 'c':
1005 15
                        $result[self::CHECKS][] = (new CheckConstraint())
1006 15
                            ->name($name)
1007 15
                            ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name'))
1008 15
                            ->expression($constraint[0]['check_expr']);
1009 15
                        break;
1010
                }
1011
            }
1012
        }
1013
1014 82
        foreach ($result as $type => $data) {
1015 82
            $this->setTableMetadata($tableName, $type, $data);
1016
        }
1017
1018 82
        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
     * @param string $name Name of the column.
1027
     *
1028
     * @return ColumnSchema
1029
     */
1030 160
    private function createColumnSchema(string $name): ColumnSchema
1031
    {
1032 160
        return new ColumnSchema($name);
1033
    }
1034
1035
    /**
1036
     * Returns the cache key for the specified table name.
1037
     *
1038
     * @param string $name The table name.
1039
     *
1040
     * @return array The cache key.
1041
     */
1042 273
    protected function getCacheKey(string $name): array
1043
    {
1044 273
        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 235
    protected function getCacheTag(): string
1055
    {
1056 235
        return md5(serialize(array_merge([self::class], $this->generateCacheKey())));
1057
    }
1058
}
1059