Passed
Pull Request — master (#32)
by Wilmer
11:57
created

PgsqlSchema::loadTableIndexes()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 43
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 34
nc 2
nop 1
dl 0
loc 43
rs 9.376
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Pgsql\Schema;
6
7
use PDO;
8
use Yiisoft\Arrays\ArrayHelper;
9
use Yiisoft\Db\Constraint\CheckConstraint;
10
use Yiisoft\Db\Constraint\Constraint;
11
use Yiisoft\Db\Constraint\ConstraintFinderInterface;
12
use Yiisoft\Db\Constraint\ConstraintFinderTrait;
13
use Yiisoft\Db\Constraint\DefaultValueConstraint;
14
use Yiisoft\Db\Constraint\ForeignKeyConstraint;
15
use Yiisoft\Db\Constraint\IndexConstraint;
16
use Yiisoft\Db\Exception\Exception;
17
use Yiisoft\Db\Exception\InvalidArgumentException;
18
use Yiisoft\Db\Exception\InvalidConfigException;
19
use Yiisoft\Db\Exception\NotSupportedException;
20
use Yiisoft\Db\Expression\Expression;
21
use Yiisoft\Db\Pgsql\Query\PgsqlQueryBuilder;
22
use Yiisoft\Db\Schema\Schema;
23
use Yiisoft\Db\View\ViewFinderTrait;
24
25
use function array_change_key_case;
26
use function array_merge;
27
use function array_unique;
28
use function array_values;
29
use function bindec;
30
use function explode;
31
use function implode;
32
use function preg_match;
33
use function preg_replace;
34
use function str_replace;
35
use function strncasecmp;
36
use function substr;
37
38
final class PgsqlSchema extends Schema implements ConstraintFinderInterface
39
{
40
    use ViewFinderTrait;
41
    use ConstraintFinderTrait;
42
43
    public const TYPE_JSONB = 'jsonb';
44
45
    /**
46
     * @var array mapping from physical column types (keys) to abstract column types (values).
47
     *
48
     * {@see http://www.postgresql.org/docs/current/static/datatype.html#DATATYPE-TABLE}
49
     */
50
    private array $typeMap = [
51
        'bit' => self::TYPE_INTEGER,
52
        'bit varying' => self::TYPE_INTEGER,
53
        'varbit' => self::TYPE_INTEGER,
54
        'bool' => self::TYPE_BOOLEAN,
55
        'boolean' => self::TYPE_BOOLEAN,
56
        'box' => self::TYPE_STRING,
57
        'circle' => self::TYPE_STRING,
58
        'point' => self::TYPE_STRING,
59
        'line' => self::TYPE_STRING,
60
        'lseg' => self::TYPE_STRING,
61
        'polygon' => self::TYPE_STRING,
62
        'path' => self::TYPE_STRING,
63
        'character' => self::TYPE_CHAR,
64
        'char' => self::TYPE_CHAR,
65
        'bpchar' => self::TYPE_CHAR,
66
        'character varying' => self::TYPE_STRING,
67
        'varchar' => self::TYPE_STRING,
68
        'text' => self::TYPE_TEXT,
69
        'bytea' => self::TYPE_BINARY,
70
        'cidr' => self::TYPE_STRING,
71
        'inet' => self::TYPE_STRING,
72
        'macaddr' => self::TYPE_STRING,
73
        'real' => self::TYPE_FLOAT,
74
        'float4' => self::TYPE_FLOAT,
75
        'double precision' => self::TYPE_DOUBLE,
76
        'float8' => self::TYPE_DOUBLE,
77
        'decimal' => self::TYPE_DECIMAL,
78
        'numeric' => self::TYPE_DECIMAL,
79
        'money' => self::TYPE_MONEY,
80
        'smallint' => self::TYPE_SMALLINT,
81
        'int2' => self::TYPE_SMALLINT,
82
        'int4' => self::TYPE_INTEGER,
83
        'int' => self::TYPE_INTEGER,
84
        'integer' => self::TYPE_INTEGER,
85
        'bigint' => self::TYPE_BIGINT,
86
        'int8' => self::TYPE_BIGINT,
87
        'oid' => self::TYPE_BIGINT, // should not be used. it's pg internal!
88
        'smallserial' => self::TYPE_SMALLINT,
89
        'serial2' => self::TYPE_SMALLINT,
90
        'serial4' => self::TYPE_INTEGER,
91
        'serial' => self::TYPE_INTEGER,
92
        'bigserial' => self::TYPE_BIGINT,
93
        'serial8' => self::TYPE_BIGINT,
94
        'pg_lsn' => self::TYPE_BIGINT,
95
        'date' => self::TYPE_DATE,
96
        'interval' => self::TYPE_STRING,
97
        'time without time zone' => self::TYPE_TIME,
98
        'time' => self::TYPE_TIME,
99
        'time with time zone' => self::TYPE_TIME,
100
        'timetz' => self::TYPE_TIME,
101
        'timestamp without time zone' => self::TYPE_TIMESTAMP,
102
        'timestamp' => self::TYPE_TIMESTAMP,
103
        'timestamp with time zone' => self::TYPE_TIMESTAMP,
104
        'timestamptz' => self::TYPE_TIMESTAMP,
105
        'abstime' => self::TYPE_TIMESTAMP,
106
        'tsquery' => self::TYPE_STRING,
107
        'tsvector' => self::TYPE_STRING,
108
        'txid_snapshot' => self::TYPE_STRING,
109
        'unknown' => self::TYPE_STRING,
110
        'uuid' => self::TYPE_STRING,
111
        'json' => self::TYPE_JSON,
112
        'jsonb' => self::TYPE_JSON,
113
        'xml' => self::TYPE_STRING,
114
    ];
115
116
    /**
117
     * @var string the default schema used for the current session.
118
     */
119
    protected ?string $defaultSchema = 'public';
120
121
    /**
122
     * @var string|string[] character used to quote schema, table, etc. names. An array of 2 characters can be used in
123
     * case starting and ending characters are different.
124
     */
125
    protected $tableQuoteCharacter = '"';
126
127
    /**
128
     * Resolves the table name and schema name (if any).
129
     *
130
     * @param string $name the table name.
131
     *
132
     * @return PgsqlTableSchema with resolved table, schema, etc. names.
133
     *
134
     * {@see \Yiisoft\Db\Schema\TableSchema}
135
     */
136
    protected function resolveTableName(string $name): PgsqlTableSchema
137
    {
138
        $resolvedName = new PgsqlTableSchema();
139
        $parts = explode('.', str_replace('"', '', $name));
140
141
        if (isset($parts[1])) {
142
            $resolvedName->schemaName($parts[0]);
143
            $resolvedName->name($parts[1]);
144
        } else {
145
            $resolvedName->schemaName($this->defaultSchema);
146
            $resolvedName->name($name);
147
        }
148
149
        $resolvedName->fullName(
150
            (
151
                $resolvedName->getSchemaName() !== $this->defaultSchema ? $resolvedName->getSchemaName() . '.' : ''
152
            ) . $resolvedName->getName()
153
        );
154
155
        return $resolvedName;
156
    }
157
158
    /**
159
     * Returns all schema names in the database, including the default one but not system schemas.
160
     *
161
     * This method should be overridden by child classes in order to support this feature because the default
162
     * implementation simply throws an exception.
163
     *
164
     * @throws Exception
165
     * @throws InvalidArgumentException
166
     * @throws InvalidConfigException
167
     *
168
     * @return array all schema names in the database, except system schemas.
169
     */
170
    protected function findSchemaNames(): array
171
    {
172
        static $sql = <<<'SQL'
173
SELECT "ns"."nspname"
174
FROM "pg_namespace" AS "ns"
175
WHERE "ns"."nspname" != 'information_schema' AND "ns"."nspname" NOT LIKE 'pg_%'
176
ORDER BY "ns"."nspname" ASC
177
SQL;
178
179
        return $this->getDb()->createCommand($sql)->queryColumn();
180
    }
181
182
    /**
183
     * Returns all table names in the database.
184
     *
185
     * This method should be overridden by child classes in order to support this feature because the default
186
     * implementation simply throws an exception.
187
     *
188
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
189
     *
190
     * @throws Exception
191
     * @throws InvalidArgumentException
192
     * @throws InvalidConfigException
193
     *
194
     * @return array all table names in the database. The names have NO schema name prefix.
195
     */
196
    protected function findTableNames(string $schema = ''): array
197
    {
198
        if ($schema === '') {
199
            $schema = $this->defaultSchema;
200
        }
201
202
        $sql = <<<'SQL'
203
SELECT c.relname AS table_name
204
FROM pg_class c
205
INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace
206
WHERE ns.nspname = :schemaName AND c.relkind IN ('r','v','m','f', 'p')
207
ORDER BY c.relname
208
SQL;
209
        return $this->getDb()->createCommand($sql, [':schemaName' => $schema])->queryColumn();
210
    }
211
212
    /**
213
     * Loads the metadata for the specified table.
214
     *
215
     * @param string $name table name.
216
     *
217
     * @throws Exception
218
     * @throws InvalidArgumentException
219
     * @throws InvalidConfigException
220
     * @throws NotSupportedException
221
     *
222
     * @return PgsqlTableSchema|null DBMS-dependent table metadata, `null` if the table does not exist.
223
     */
224
    protected function loadTableSchema(string $name): ?PgsqlTableSchema
225
    {
226
        $table = new PgsqlTableSchema();
227
228
        $this->resolveTableNames($table, $name);
229
230
        if ($this->findColumns($table)) {
231
            $this->findConstraints($table);
232
            return $table;
233
        }
234
235
        return null;
236
    }
237
238
    /**
239
     * Loads a primary key for the given table.
240
     *
241
     * @param string $tableName table name.
242
     *
243
     * @throws Exception
244
     * @throws InvalidArgumentException
245
     * @throws InvalidConfigException
246
     *
247
     * @return Constraint|null primary key for the given table, `null` if the table has no primary key.
248
     */
249
    protected function loadTablePrimaryKey(string $tableName): ?Constraint
250
    {
251
        return $this->loadTableConstraints($tableName, 'primaryKey');
252
    }
253
254
    /**
255
     * Loads all foreign keys for the given table.
256
     *
257
     * @param string $tableName table name.
258
     *
259
     * @throws Exception
260
     * @throws InvalidArgumentException
261
     * @throws InvalidConfigException
262
     *
263
     * @return ForeignKeyConstraint[] foreign keys for the given table.
264
     */
265
    protected function loadTableForeignKeys($tableName): array
266
    {
267
        return $this->loadTableConstraints($tableName, 'foreignKeys');
268
    }
269
270
    /**
271
     * Loads all indexes for the given table.
272
     *
273
     * @param string $tableName table name.
274
     *
275
     * @throws Exception
276
     * @throws InvalidArgumentException
277
     * @throws InvalidConfigException
278
     *
279
     * @return IndexConstraint[] indexes for the given table.
280
     */
281
    protected function loadTableIndexes(string $tableName): array
282
    {
283
        static $sql = <<<'SQL'
284
SELECT
285
    "ic"."relname" AS "name",
286
    "ia"."attname" AS "column_name",
287
    "i"."indisunique" AS "index_is_unique",
288
    "i"."indisprimary" AS "index_is_primary"
289
FROM "pg_class" AS "tc"
290
INNER JOIN "pg_namespace" AS "tcns"
291
    ON "tcns"."oid" = "tc"."relnamespace"
292
INNER JOIN "pg_index" AS "i"
293
    ON "i"."indrelid" = "tc"."oid"
294
INNER JOIN "pg_class" AS "ic"
295
    ON "ic"."oid" = "i"."indexrelid"
296
INNER JOIN "pg_attribute" AS "ia"
297
    ON "ia"."attrelid" = "i"."indrelid" AND "ia"."attnum" = ANY ("i"."indkey")
298
WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName
299
ORDER BY "ia"."attnum" ASC
300
SQL;
301
302
        $resolvedName = $this->resolveTableName($tableName);
303
304
        $indexes = $this->getDb()->createCommand($sql, [
305
            ':schemaName' => $resolvedName->getSchemaName(),
306
            ':tableName' => $resolvedName->getName(),
307
        ])->queryAll();
308
309
        $indexes = $this->normalizePdoRowKeyCase($indexes, true);
310
        $indexes = ArrayHelper::index($indexes, null, 'name');
311
        $result = [];
312
313
        foreach ($indexes as $name => $index) {
314
            $ic = (new IndexConstraint())
315
                ->name($name)
316
                ->columnNames(ArrayHelper::getColumn($index, 'column_name'))
317
                ->primary((bool) $index[0]['index_is_primary'])
318
                ->unique((bool) $index[0]['index_is_unique']);
319
320
            $result[] = $ic;
321
        }
322
323
        return $result;
324
    }
325
326
    /**
327
     * Loads all unique constraints for the given table.
328
     *
329
     * @param string $tableName table name.
330
     *
331
     * @throws Exception
332
     * @throws InvalidArgumentException
333
     * @throws InvalidConfigException
334
     *
335
     * @return Constraint[] unique constraints for the given table.
336
     */
337
    protected function loadTableUniques(string $tableName): array
338
    {
339
        return $this->loadTableConstraints($tableName, 'uniques');
340
    }
341
342
    /**
343
     * Loads all check constraints for the given table.
344
     *
345
     * @param string $tableName table name.
346
     *
347
     * @throws Exception
348
     * @throws InvalidArgumentException
349
     * @throws InvalidConfigException
350
     *
351
     * @return CheckConstraint[] check constraints for the given table.
352
     */
353
    protected function loadTableChecks(string $tableName): array
354
    {
355
        return $this->loadTableConstraints($tableName, 'checks');
356
    }
357
358
    /**
359
     * Loads all default value constraints for the given table.
360
     *
361
     * @param string $tableName table name.
362
     *
363
     * @throws NotSupportedException
364
     *
365
     * @return DefaultValueConstraint[] default value constraints for the given table.
366
     */
367
    protected function loadTableDefaultValues($tableName): array
0 ignored issues
show
Unused Code introduced by
The parameter $tableName is not used and could be removed. ( Ignorable by Annotation )

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

367
    protected function loadTableDefaultValues(/** @scrutinizer ignore-unused */ $tableName): array

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
368
    {
369
        throw new NotSupportedException('PostgreSQL does not support default value constraints.');
370
    }
371
372
    /**
373
     * Creates a query builder for the PostgreSQL database.
374
     *
375
     * @return PgsqlQueryBuilder query builder instance
376
     */
377
    public function createQueryBuilder(): PgsqlQueryBuilder
378
    {
379
        return new PgsqlQueryBuilder($this->getDb());
0 ignored issues
show
Bug introduced by
It seems like $this->getDb() can also be of type null; however, parameter $db of Yiisoft\Db\Pgsql\Query\P...yBuilder::__construct() does only seem to accept Yiisoft\Db\Connection\Connection, maybe add an additional type check? ( Ignorable by Annotation )

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

379
        return new PgsqlQueryBuilder(/** @scrutinizer ignore-type */ $this->getDb());
Loading history...
380
    }
381
382
    /**
383
     * Resolves the table name and schema name (if any).
384
     *
385
     * @param PgsqlTableSchema $table the table metadata object.
386
     * @param string $name the table name
387
     */
388
    protected function resolveTableNames(PgsqlTableSchema $table, string $name): void
389
    {
390
        $parts = explode('.', str_replace('"', '', $name));
391
392
        if (isset($parts[1])) {
393
            $table->schemaName($parts[0]);
394
            $table->name($parts[1]);
395
        } else {
396
            $table->schemaName($this->defaultSchema);
397
            $table->name($parts[0]);
398
        }
399
400
        $table->fullName($table->getSchemaName() !== $this->defaultSchema ? $table->getSchemaName() . '.'
401
            . $table->getName() : $table->getName());
402
    }
403
404
    protected function findViewNames(string $schema = ''): array
405
    {
406
        if ($schema === '') {
407
            $schema = $this->defaultSchema;
408
        }
409
        $sql = <<<'SQL'
410
SELECT c.relname AS table_name
411
FROM pg_class c
412
INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace
413
WHERE ns.nspname = :schemaName AND (c.relkind = 'v' OR c.relkind = 'm')
414
ORDER BY c.relname
415
SQL;
416
        return $this->getDb()->createCommand($sql, [':schemaName' => $schema])->queryColumn();
417
    }
418
419
    /**
420
     * Collects the foreign key column details for the given table.
421
     *
422
     * @param PgsqlTableSchema $table the table metadata
423
     *
424
     * @throws Exception
425
     * @throws InvalidArgumentException
426
     * @throws InvalidConfigException
427
     */
428
    protected function findConstraints(PgsqlTableSchema $table)
429
    {
430
        $tableName = $this->quoteValue($table->getName());
431
        $tableSchema = $this->quoteValue($table->getSchemaName());
432
433
        /**
434
         * We need to extract the constraints de hard way since:
435
         * {@see http://www.postgresql.org/message-id/[email protected]}
436
         */
437
438
        $sql = <<<SQL
439
select
440
    ct.conname as constraint_name,
441
    a.attname as column_name,
442
    fc.relname as foreign_table_name,
443
    fns.nspname as foreign_table_schema,
444
    fa.attname as foreign_column_name
445
from
446
    (SELECT ct.conname, ct.conrelid, ct.confrelid, ct.conkey, ct.contype, ct.confkey, generate_subscripts(ct.conkey, 1) AS s
447
       FROM pg_constraint ct
448
    ) AS ct
449
    inner join pg_class c on c.oid=ct.conrelid
450
    inner join pg_namespace ns on c.relnamespace=ns.oid
451
    inner join pg_attribute a on a.attrelid=ct.conrelid and a.attnum = ct.conkey[ct.s]
452
    left join pg_class fc on fc.oid=ct.confrelid
453
    left join pg_namespace fns on fc.relnamespace=fns.oid
454
    left join pg_attribute fa on fa.attrelid=ct.confrelid and fa.attnum = ct.confkey[ct.s]
455
where
456
    ct.contype='f'
457
    and c.relname={$tableName}
458
    and ns.nspname={$tableSchema}
459
order by
460
    fns.nspname, fc.relname, a.attnum
461
SQL;
462
463
        $constraints = [];
464
465
        foreach ($this->getDb()->createCommand($sql)->queryAll() as $constraint) {
466
            if ($this->getDb()->getSlavePdo()->getAttribute(PDO::ATTR_CASE) === PDO::CASE_UPPER) {
467
                $constraint = array_change_key_case($constraint, CASE_LOWER);
468
            }
469
470
            if ($constraint['foreign_table_schema'] !== $this->defaultSchema) {
471
                $foreignTable = $constraint['foreign_table_schema'] . '.' . $constraint['foreign_table_name'];
472
            } else {
473
                $foreignTable = $constraint['foreign_table_name'];
474
            }
475
476
            $name = $constraint['constraint_name'];
477
478
            if (!isset($constraints[$name])) {
479
                $constraints[$name] = [
480
                    'tableName' => $foreignTable,
481
                    'columns' => [],
482
                ];
483
            }
484
485
            $constraints[$name]['columns'][$constraint['column_name']] = $constraint['foreign_column_name'];
486
        }
487
488
        foreach ($constraints as $name => $constraint) {
489
            $table->foreignKey($name, array_merge([$constraint['tableName']], $constraint['columns']));
490
        }
491
    }
492
493
    /**
494
     * Gets information about given table unique indexes.
495
     *
496
     * @param PgsqlTableSchema $table the table metadata.
497
     *
498
     * @throws Exception
499
     * @throws InvalidArgumentException
500
     * @throws InvalidConfigException
501
     *
502
     * @return array with index and column names.
503
     */
504
    protected function getUniqueIndexInformation(PgsqlTableSchema $table): array
505
    {
506
        $sql = <<<'SQL'
507
SELECT
508
    i.relname as indexname,
509
    pg_get_indexdef(idx.indexrelid, k + 1, TRUE) AS columnname
510
FROM (
511
  SELECT *, generate_subscripts(indkey, 1) AS k
512
  FROM pg_index
513
) idx
514
INNER JOIN pg_class i ON i.oid = idx.indexrelid
515
INNER JOIN pg_class c ON c.oid = idx.indrelid
516
INNER JOIN pg_namespace ns ON c.relnamespace = ns.oid
517
WHERE idx.indisprimary = FALSE AND idx.indisunique = TRUE
518
AND c.relname = :tableName AND ns.nspname = :schemaName
519
ORDER BY i.relname, k
520
SQL;
521
522
        return $this->getDb()->createCommand($sql, [
523
            ':schemaName' => $table->getSchemaName(),
524
            ':tableName' => $table->getName(),
525
        ])->queryAll();
526
    }
527
528
    /**
529
     * Returns all unique indexes for the given table.
530
     *
531
     * Each array element is of the following structure:
532
     *
533
     * ```php
534
     * [
535
     *     'IndexName1' => ['col1' [, ...]],
536
     *     'IndexName2' => ['col2' [, ...]],
537
     * ]
538
     * ```
539
     *
540
     * @param PgsqlTableSchema $table the table metadata
541
     *
542
     * @throws Exception
543
     * @throws InvalidArgumentException
544
     * @throws InvalidConfigException
545
     *
546
     * @return array all unique indexes for the given table.
547
     */
548
    public function findUniqueIndexes($table): array
549
    {
550
        $uniqueIndexes = [];
551
552
        foreach ($this->getUniqueIndexInformation($table) as $row) {
553
            if ($this->getDb()->getSlavePdo()->getAttribute(PDO::ATTR_CASE) === PDO::CASE_UPPER) {
554
                $row = array_change_key_case($row, CASE_LOWER);
555
            }
556
557
            $column = $row['columnname'];
558
559
            if (!empty($column) && $column[0] === '"') {
560
                /**
561
                 * postgres will quote names that are not lowercase-only.
562
                 *
563
                 * {@see https://github.com/yiisoft/yii2/issues/10613}
564
                 */
565
                $column = substr($column, 1, -1);
566
            }
567
568
            $uniqueIndexes[$row['indexname']][] = $column;
569
        }
570
571
        return $uniqueIndexes;
572
    }
573
574
    /**
575
     * Collects the metadata of table columns.
576
     *
577
     * @param PgsqlTableSchema $table the table metadata.
578
     *
579
     * @throws Exception
580
     * @throws InvalidArgumentException
581
     * @throws InvalidConfigException
582
     * @throws NotSupportedException
583
     *
584
     * @return bool whether the table exists in the database.
585
     */
586
    protected function findColumns(PgsqlTableSchema $table): bool
587
    {
588
        $tableName = $this->getDb()->quoteValue($table->getName());
589
        $schemaName = $this->getDb()->quoteValue($table->getSchemaName());
590
591
        $orIdentity = '';
592
593
        if (version_compare($this->getDb()->getServerVersion(), '12.0', '>=')) {
594
            $orIdentity = 'OR a.attidentity != \'\'';
595
        }
596
597
        $sql = <<<SQL
598
SELECT
599
    d.nspname AS table_schema,
600
    c.relname AS table_name,
601
    a.attname AS column_name,
602
    COALESCE(td.typname, tb.typname, t.typname) AS data_type,
603
    COALESCE(td.typtype, tb.typtype, t.typtype) AS type_type,
604
    a.attlen AS character_maximum_length,
605
    pg_catalog.col_description(c.oid, a.attnum) AS column_comment,
606
    a.atttypmod AS modifier,
607
    a.attnotnull = false AS is_nullable,
608
    CAST(pg_get_expr(ad.adbin, ad.adrelid) AS varchar) AS column_default,
609
    coalesce(pg_get_expr(ad.adbin, ad.adrelid) ~ 'nextval',false) {$orIdentity} AS is_autoinc,
610
    pg_get_serial_sequence(quote_ident(d.nspname) || '.' || quote_ident(c.relname), a.attname) AS sequence_name,
611
    CASE WHEN COALESCE(td.typtype, tb.typtype, t.typtype) = 'e'::char
612
        THEN array_to_string((SELECT array_agg(enumlabel) FROM pg_enum WHERE enumtypid = COALESCE(td.oid, tb.oid, a.atttypid))::varchar[], ',')
613
        ELSE NULL
614
    END AS enum_values,
615
    CASE atttypid
616
         WHEN 21 /*int2*/ THEN 16
617
         WHEN 23 /*int4*/ THEN 32
618
         WHEN 20 /*int8*/ THEN 64
619
         WHEN 1700 /*numeric*/ THEN
620
              CASE WHEN atttypmod = -1
621
               THEN null
622
               ELSE ((atttypmod - 4) >> 16) & 65535
623
               END
624
         WHEN 700 /*float4*/ THEN 24 /*FLT_MANT_DIG*/
625
         WHEN 701 /*float8*/ THEN 53 /*DBL_MANT_DIG*/
626
         ELSE null
627
      END   AS numeric_precision,
628
      CASE
629
        WHEN atttypid IN (21, 23, 20) THEN 0
630
        WHEN atttypid IN (1700) THEN
631
        CASE
632
            WHEN atttypmod = -1 THEN null
633
            ELSE (atttypmod - 4) & 65535
634
        END
635
           ELSE null
636
      END AS numeric_scale,
637
    CAST(
638
             information_schema._pg_char_max_length(information_schema._pg_truetypid(a, t), information_schema._pg_truetypmod(a, t))
639
             AS numeric
640
    ) AS size,
641
    a.attnum = any (ct.conkey) as is_pkey,
642
    COALESCE(NULLIF(a.attndims, 0), NULLIF(t.typndims, 0), (t.typcategory='A')::int) AS dimension
643
FROM
644
    pg_class c
645
    LEFT JOIN pg_attribute a ON a.attrelid = c.oid
646
    LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum
647
    LEFT JOIN pg_type t ON a.atttypid = t.oid
648
    LEFT JOIN pg_type tb ON (a.attndims > 0 OR t.typcategory='A') AND t.typelem > 0 AND t.typelem = tb.oid OR t.typbasetype > 0 AND t.typbasetype = tb.oid
649
    LEFT JOIN pg_type td ON t.typndims > 0 AND t.typbasetype > 0 AND tb.typelem = td.oid
650
    LEFT JOIN pg_namespace d ON d.oid = c.relnamespace
651
    LEFT JOIN pg_constraint ct ON ct.conrelid = c.oid AND ct.contype = 'p'
652
WHERE
653
    a.attnum > 0 AND t.typname != '' AND NOT a.attisdropped
654
    AND c.relname = {$tableName}
655
    AND d.nspname = {$schemaName}
656
ORDER BY
657
    a.attnum;
658
SQL;
659
660
        $columns = $this->getDb()->createCommand($sql)->queryAll();
661
662
        if (empty($columns)) {
663
            return false;
664
        }
665
666
        foreach ($columns as $column) {
667
            if ($this->getDb()->getSlavePdo()->getAttribute(PDO::ATTR_CASE) === PDO::CASE_UPPER) {
668
                $column = array_change_key_case($column, CASE_LOWER);
669
            }
670
671
            $column = $this->loadColumnSchema($column);
672
            $table->columns($column->getName(), $column);
673
674
            if ($column->isPrimaryKey()) {
675
                $table->primaryKey($column->getName());
676
677
                if ($table->getSequenceName() === null) {
678
                    $table->sequenceName($column->getSequenceName());
679
                }
680
681
                $column->defaultValue(null);
682
            } elseif ($column->getDefaultValue()) {
683
                if (
684
                    in_array($column->getType(), [self::TYPE_TIMESTAMP, self::TYPE_DATE, self::TYPE_TIME], true) &&
685
                    in_array(
686
                        strtoupper($column->getDefaultValue()),
687
                        ['NOW()', 'CURRENT_TIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIME'],
688
                        true
689
                    )
690
                ) {
691
                    $column->defaultValue(new Expression($column->getDefaultValue()));
692
                } elseif ($column->getType() === 'boolean') {
693
                    $column->defaultValue(($column->getDefaultValue() === 'true'));
694
                } elseif (preg_match("/^B'(.*?)'::/", $column->getDefaultValue(), $matches)) {
695
                    $column->defaultValue(bindec($matches[1]));
696
                } elseif (preg_match("/^'(\d+)'::\"bit\"$/", $column->getDefaultValue(), $matches)) {
697
                    $column->defaultValue(bindec($matches[1]));
698
                } elseif (preg_match("/^'(.*?)'::/", $column->getDefaultValue(), $matches)) {
699
                    $column->defaultValue($column->phpTypecast($matches[1]));
700
                } elseif (preg_match('/^(\()?(.*?)(?(1)\))(?:::.+)?$/', $column->getDefaultValue(), $matches)) {
701
                    if ($matches[2] === 'NULL') {
702
                        $column->defaultValue(null);
703
                    } else {
704
                        $column->defaultValue($column->phpTypecast($matches[2]));
705
                    }
706
                } else {
707
                    $column->defaultValue($column->phpTypecast($column->getDefaultValue()));
708
                }
709
            }
710
        }
711
712
        return true;
713
    }
714
715
    /**
716
     * Loads the column information into a {@see PgsqlColumnSchema} object.
717
     *
718
     * @param array $info column information.
719
     *
720
     * @return PgsqlColumnSchema the column schema object.
721
     */
722
    protected function loadColumnSchema(array $info): PgsqlColumnSchema
723
    {
724
        /** @var PgsqlColumnSchema $column */
725
        $column = $this->createColumnSchema();
726
        $column->allowNull($info['is_nullable']);
727
        $column->autoIncrement($info['is_autoinc']);
728
        $column->comment($info['column_comment']);
729
        $column->dbType($info['data_type']);
730
        $column->defaultValue($info['column_default']);
731
        $column->enumValues(($info['enum_values'] !== null)
732
            ? explode(',', str_replace(["''"], ["'"], $info['enum_values'])) : null);
733
        $column->unsigned(false); // has no meaning in PG
734
        $column->primaryKey((bool) $info['is_pkey']);
735
        $column->name($info['column_name']);
736
        $column->precision($info['numeric_precision']);
737
        $column->scale($info['numeric_scale']);
738
        $column->size($info['size'] === null ? null : (int) $info['size']);
739
        $column->dimension((int) $info['dimension']);
740
741
        /**
742
         * pg_get_serial_sequence() doesn't track DEFAULT value change. GENERATED BY IDENTITY columns always have null
743
         * default value.
744
         */
745
746
        $defaultValue = $column->getDefaultValue();
747
        if (
748
            isset($defaultValue) &&
749
            preg_match("/nextval\\('\"?\\w+\"?\.?\"?\\w+\"?'(::regclass)?\\)/", $defaultValue) === 1
750
        ) {
751
            $column->sequenceName(preg_replace(
752
                ['/nextval/', '/::/', '/regclass/', '/\'\)/', '/\(\'/'],
753
                '',
754
                $defaultValue
755
            ));
756
        } elseif (isset($info['sequence_name'])) {
757
            $column->sequenceName($this->resolveTableName($info['sequence_name'])->getFullName());
758
        }
759
760
        if (isset($this->typeMap[$column->getDbType()])) {
761
            $column->type($this->typeMap[$column->getDbType()]);
762
        } else {
763
            $column->type(self::TYPE_STRING);
764
        }
765
766
        $column->phpType($this->getColumnPhpType($column));
767
768
        return $column;
769
    }
770
771
    /**
772
     * Executes the INSERT command, returning primary key values.
773
     *
774
     * @param string $table the table that new rows will be inserted into.
775
     * @param array $columns the column data (name => value) to be inserted into the table.
776
     *
777
     * @throws Exception
778
     * @throws InvalidArgumentException
779
     * @throws InvalidConfigException
780
     * @throws NotSupportedException
781
     *
782
     * @return array|false primary key values or false if the command fails.
783
     */
784
    public function insert(string $table, array $columns)
785
    {
786
        $params = [];
787
        $sql = $this->getDb()->getQueryBuilder()->insert($table, $columns, $params);
788
        $returnColumns = $this->getTableSchema($table)->getPrimaryKey();
789
790
        if (!empty($returnColumns)) {
791
            $returning = [];
792
            foreach ((array) $returnColumns as $name) {
793
                $returning[] = $this->quoteColumnName($name);
794
            }
795
            $sql .= ' RETURNING ' . implode(', ', $returning);
796
        }
797
798
        $command = $this->getDb()->createCommand($sql, $params);
799
        $command->prepare(false);
800
        $result = $command->queryOne();
801
802
        return !$command->getPdoStatement()->rowCount() ? false : $result;
803
    }
804
805
    /**
806
     * Loads multiple types of constraints and returns the specified ones.
807
     *
808
     * @param string $tableName table name.
809
     * @param string $returnType return type:
810
     * - primaryKey
811
     * - foreignKeys
812
     * - uniques
813
     * - checks
814
     *
815
     * @throws Exception
816
     * @throws InvalidArgumentException
817
     * @throws InvalidConfigException
818
     *
819
     * @return mixed constraints.
820
     */
821
    private function loadTableConstraints(string $tableName, string $returnType)
822
    {
823
        static $sql = <<<'SQL'
824
SELECT
825
    "c"."conname" AS "name",
826
    "a"."attname" AS "column_name",
827
    "c"."contype" AS "type",
828
    "ftcns"."nspname" AS "foreign_table_schema",
829
    "ftc"."relname" AS "foreign_table_name",
830
    "fa"."attname" AS "foreign_column_name",
831
    "c"."confupdtype" AS "on_update",
832
    "c"."confdeltype" AS "on_delete",
833
    pg_get_constraintdef("c"."oid") AS "check_expr"
834
FROM "pg_class" AS "tc"
835
INNER JOIN "pg_namespace" AS "tcns"
836
    ON "tcns"."oid" = "tc"."relnamespace"
837
INNER JOIN "pg_constraint" AS "c"
838
    ON "c"."conrelid" = "tc"."oid"
839
INNER JOIN "pg_attribute" AS "a"
840
    ON "a"."attrelid" = "c"."conrelid" AND "a"."attnum" = ANY ("c"."conkey")
841
LEFT JOIN "pg_class" AS "ftc"
842
    ON "ftc"."oid" = "c"."confrelid"
843
LEFT JOIN "pg_namespace" AS "ftcns"
844
    ON "ftcns"."oid" = "ftc"."relnamespace"
845
LEFT JOIN "pg_attribute" "fa"
846
    ON "fa"."attrelid" = "c"."confrelid" AND "fa"."attnum" = ANY ("c"."confkey")
847
WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName
848
ORDER BY "a"."attnum" ASC, "fa"."attnum" ASC
849
SQL;
850
        static $actionTypes = [
851
            'a' => 'NO ACTION',
852
            'r' => 'RESTRICT',
853
            'c' => 'CASCADE',
854
            'n' => 'SET NULL',
855
            'd' => 'SET DEFAULT',
856
        ];
857
858
        $resolvedName = $this->resolveTableName($tableName);
859
        $constraints = $this->getDb()->createCommand($sql, [
860
            ':schemaName' => $resolvedName->getSchemaName(),
861
            ':tableName' => $resolvedName->getName(),
862
        ])->queryAll();
863
        $constraints = $this->normalizePdoRowKeyCase($constraints, true);
864
        $constraints = ArrayHelper::index($constraints, null, ['type', 'name']);
865
        $result = [
866
            'primaryKey' => null,
867
            'foreignKeys' => [],
868
            'uniques' => [],
869
            'checks' => [],
870
        ];
871
872
        foreach ($constraints as $type => $names) {
873
            foreach ($names as $name => $constraint) {
874
                switch ($type) {
875
                    case 'p':
876
                        $ct = (new Constraint())
877
                            ->name($name)
878
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'));
879
880
                        $result['primaryKey'] = $ct;
881
                        break;
882
                    case 'f':
883
                        $fk = (new ForeignKeyConstraint())
884
                            ->name($name)
885
                            ->columnNames(array_values(
886
                                array_unique(ArrayHelper::getColumn($constraint, 'column_name'))
887
                            ))
888
                            ->foreignSchemaName($constraint[0]['foreign_table_schema'])
889
                            ->foreignTableName($constraint[0]['foreign_table_name'])
890
                            ->foreignColumnNames(array_values(
891
                                array_unique(ArrayHelper::getColumn($constraint, 'foreign_column_name'))
892
                            ))
893
                            ->onDelete($actionTypes[$constraint[0]['on_delete']] ?? null)
894
                            ->onUpdate($actionTypes[$constraint[0]['on_update']] ?? null);
895
896
                        $result['foreignKeys'][] = $fk;
897
                        break;
898
                    case 'u':
899
                        $ct = (new Constraint())
900
                            ->name($name)
901
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'));
902
903
                        $result['uniques'][] = $ct;
904
                        break;
905
                    case 'c':
906
                        $ck = (new CheckConstraint())
907
                            ->name($name)
908
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
909
                            ->expression($constraint[0]['check_expr']);
910
911
                        $result['checks'][] = $ck;
912
                        break;
913
                }
914
            }
915
        }
916
        foreach ($result as $type => $data) {
917
            $this->setTableMetadata($tableName, $type, $data);
918
        }
919
920
        return $result[$returnType];
921
    }
922
923
    /**
924
     * Creates a column schema for the database.
925
     *
926
     * This method may be overridden by child classes to create a DBMS-specific column schema.
927
     *
928
     * @return PgsqlColumnSchema column schema instance.
929
     */
930
    protected function createColumnSchema(): PgsqlColumnSchema
931
    {
932
        return new PgsqlColumnSchema();
933
    }
934
}
935