Test Failed
Pull Request — master (#315)
by Sergei
03:10
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\Pgsql\Column\ArrayColumnSchema;
21
use Yiisoft\Db\Pgsql\Column\BigIntColumnSchema;
22
use Yiisoft\Db\Pgsql\Column\BinaryColumnSchema;
23
use Yiisoft\Db\Pgsql\Column\BitColumnSchema;
24
use Yiisoft\Db\Pgsql\Column\BooleanColumnSchema;
25
use Yiisoft\Db\Pgsql\Column\IntegerColumnSchema;
26
use Yiisoft\Db\Pgsql\Column\IntegerColumnSchemaInterface;
27
use Yiisoft\Db\Schema\Builder\ColumnInterface;
28
use Yiisoft\Db\Schema\Column\ColumnSchemaInterface;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Schema\Column\ColumnSchemaInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1020
            return parent::/** @scrutinizer ignore-call */ createColumnSchema($type, $name);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

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