Passed
Push — master ( 640dd0...eecb1b )
by Wilmer
13:16 queued 10:55
created

Schema::findViewNames()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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

362
    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...
363
    {
364 12
        throw new NotSupportedException('PostgreSQL does not support default value constraints.');
365
    }
366
367
    /**
368
     * Creates a query builder for the PostgreSQL database.
369
     *
370
     * @return QueryBuilder query builder instance
371
     */
372 68
    public function createQueryBuilder(): QueryBuilder
373
    {
374 68
        return new QueryBuilder($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\QueryBuilder::__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

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