Passed
Push — 9718-fix-authKey-invalidation ( 18311b...e14d07 )
by Alexander
53:49 queued 33:39
created

Schema::loadTableConstraints()   C

Complexity

Conditions 10
Paths 14

Size

Total Lines 91
Code Lines 77

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 77
nc 14
nop 2
dl 0
loc 91
rs 6.6351
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db\pgsql;
9
10
use yii\base\NotSupportedException;
11
use yii\db\CheckConstraint;
12
use yii\db\Constraint;
13
use yii\db\ConstraintFinderInterface;
14
use yii\db\ConstraintFinderTrait;
15
use yii\db\Expression;
16
use yii\db\ForeignKeyConstraint;
17
use yii\db\IndexConstraint;
18
use yii\db\TableSchema;
19
use yii\db\ViewFinderTrait;
20
use yii\helpers\ArrayHelper;
21
22
/**
23
 * Schema is the class for retrieving metadata from a PostgreSQL database
24
 * (version 9.x and above).
25
 *
26
 * @author Gevik Babakhani <[email protected]>
27
 * @since 2.0
28
 */
29
class Schema extends \yii\db\Schema implements ConstraintFinderInterface
30
{
31
    use ViewFinderTrait;
32
    use ConstraintFinderTrait;
33
34
    const TYPE_JSONB = 'jsonb';
35
36
    /**
37
     * @var string the default schema used for the current session.
38
     */
39
    public $defaultSchema = 'public';
40
    /**
41
     * {@inheritdoc}
42
     */
43
    public $columnSchemaClass = 'yii\db\pgsql\ColumnSchema';
44
    /**
45
     * @var array mapping from physical column types (keys) to abstract
46
     * column types (values)
47
     * @see http://www.postgresql.org/docs/current/static/datatype.html#DATATYPE-TABLE
48
     */
49
    public $typeMap = [
50
        'bit' => self::TYPE_INTEGER,
51
        'bit varying' => self::TYPE_INTEGER,
52
        'varbit' => self::TYPE_INTEGER,
53
54
        'bool' => self::TYPE_BOOLEAN,
55
        'boolean' => self::TYPE_BOOLEAN,
56
57
        'box' => self::TYPE_STRING,
58
        'circle' => self::TYPE_STRING,
59
        'point' => self::TYPE_STRING,
60
        'line' => self::TYPE_STRING,
61
        'lseg' => self::TYPE_STRING,
62
        'polygon' => self::TYPE_STRING,
63
        'path' => self::TYPE_STRING,
64
65
        'character' => self::TYPE_CHAR,
66
        'char' => self::TYPE_CHAR,
67
        'bpchar' => self::TYPE_CHAR,
68
        'character varying' => self::TYPE_STRING,
69
        'varchar' => self::TYPE_STRING,
70
        'text' => self::TYPE_TEXT,
71
72
        'bytea' => self::TYPE_BINARY,
73
74
        'cidr' => self::TYPE_STRING,
75
        'inet' => self::TYPE_STRING,
76
        'macaddr' => self::TYPE_STRING,
77
78
        'real' => self::TYPE_FLOAT,
79
        'float4' => self::TYPE_FLOAT,
80
        'double precision' => self::TYPE_DOUBLE,
81
        'float8' => self::TYPE_DOUBLE,
82
        'decimal' => self::TYPE_DECIMAL,
83
        'numeric' => self::TYPE_DECIMAL,
84
85
        'money' => self::TYPE_MONEY,
86
87
        'smallint' => self::TYPE_SMALLINT,
88
        'int2' => self::TYPE_SMALLINT,
89
        'int4' => self::TYPE_INTEGER,
90
        'int' => self::TYPE_INTEGER,
91
        'integer' => self::TYPE_INTEGER,
92
        'bigint' => self::TYPE_BIGINT,
93
        'int8' => self::TYPE_BIGINT,
94
        'oid' => self::TYPE_BIGINT, // should not be used. it's pg internal!
95
96
        'smallserial' => self::TYPE_SMALLINT,
97
        'serial2' => self::TYPE_SMALLINT,
98
        'serial4' => self::TYPE_INTEGER,
99
        'serial' => self::TYPE_INTEGER,
100
        'bigserial' => self::TYPE_BIGINT,
101
        'serial8' => self::TYPE_BIGINT,
102
        'pg_lsn' => self::TYPE_BIGINT,
103
104
        'date' => self::TYPE_DATE,
105
        'interval' => self::TYPE_STRING,
106
        'time without time zone' => self::TYPE_TIME,
107
        'time' => self::TYPE_TIME,
108
        'time with time zone' => self::TYPE_TIME,
109
        'timetz' => self::TYPE_TIME,
110
        'timestamp without time zone' => self::TYPE_TIMESTAMP,
111
        'timestamp' => self::TYPE_TIMESTAMP,
112
        'timestamp with time zone' => self::TYPE_TIMESTAMP,
113
        'timestamptz' => self::TYPE_TIMESTAMP,
114
        'abstime' => self::TYPE_TIMESTAMP,
115
116
        'tsquery' => self::TYPE_STRING,
117
        'tsvector' => self::TYPE_STRING,
118
        'txid_snapshot' => self::TYPE_STRING,
119
120
        'unknown' => self::TYPE_STRING,
121
122
        'uuid' => self::TYPE_STRING,
123
        'json' => self::TYPE_JSON,
124
        'jsonb' => self::TYPE_JSON,
125
        'xml' => self::TYPE_STRING,
126
    ];
127
128
    /**
129
     * {@inheritdoc}
130
     */
131
    protected $tableQuoteCharacter = '"';
132
133
134
    /**
135
     * {@inheritdoc}
136
     */
137
    protected function resolveTableName($name)
138
    {
139
        $resolvedName = new TableSchema();
140
        $parts = explode('.', str_replace('"', '', $name));
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
        $resolvedName->fullName = ($resolvedName->schemaName !== $this->defaultSchema ? $resolvedName->schemaName . '.' : '') . $resolvedName->name;
149
        return $resolvedName;
150
    }
151
152
    /**
153
     * {@inheritdoc}
154
     */
155
    protected function findSchemaNames()
156
    {
157
        static $sql = <<<'SQL'
158
SELECT "ns"."nspname"
159
FROM "pg_namespace" AS "ns"
160
WHERE "ns"."nspname" != 'information_schema' AND "ns"."nspname" NOT LIKE 'pg_%'
161
ORDER BY "ns"."nspname" ASC
162
SQL;
163
164
        return $this->db->createCommand($sql)->queryColumn();
165
    }
166
167
    /**
168
     * {@inheritdoc}
169
     */
170
    protected function findTableNames($schema = '')
171
    {
172
        if ($schema === '') {
173
            $schema = $this->defaultSchema;
174
        }
175
        $sql = <<<'SQL'
176
SELECT c.relname AS table_name
177
FROM pg_class c
178
INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace
179
WHERE ns.nspname = :schemaName AND c.relkind IN ('r','v','m','f', 'p')
180
ORDER BY c.relname
181
SQL;
182
        return $this->db->createCommand($sql, [':schemaName' => $schema])->queryColumn();
183
    }
184
185
    /**
186
     * {@inheritdoc}
187
     */
188
    protected function loadTableSchema($name)
189
    {
190
        $table = new TableSchema();
191
        $this->resolveTableNames($table, $name);
192
        if ($this->findColumns($table)) {
193
            $this->findConstraints($table);
194
            return $table;
195
        }
196
197
        return null;
198
    }
199
200
    /**
201
     * {@inheritdoc}
202
     */
203
    protected function loadTablePrimaryKey($tableName)
204
    {
205
        return $this->loadTableConstraints($tableName, 'primaryKey');
206
    }
207
208
    /**
209
     * {@inheritdoc}
210
     */
211
    protected function loadTableForeignKeys($tableName)
212
    {
213
        return $this->loadTableConstraints($tableName, 'foreignKeys');
214
    }
215
216
    /**
217
     * {@inheritdoc}
218
     */
219
    protected function loadTableIndexes($tableName)
220
    {
221
        static $sql = <<<'SQL'
222
SELECT
223
    "ic"."relname" AS "name",
224
    "ia"."attname" AS "column_name",
225
    "i"."indisunique" AS "index_is_unique",
226
    "i"."indisprimary" AS "index_is_primary"
227
FROM "pg_class" AS "tc"
228
INNER JOIN "pg_namespace" AS "tcns"
229
    ON "tcns"."oid" = "tc"."relnamespace"
230
INNER JOIN "pg_index" AS "i"
231
    ON "i"."indrelid" = "tc"."oid"
232
INNER JOIN "pg_class" AS "ic"
233
    ON "ic"."oid" = "i"."indexrelid"
234
INNER JOIN "pg_attribute" AS "ia"
235
    ON "ia"."attrelid" = "i"."indexrelid"
236
WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName
237
ORDER BY "ia"."attnum" ASC
238
SQL;
239
240
        $resolvedName = $this->resolveTableName($tableName);
241
        $indexes = $this->db->createCommand($sql, [
242
            ':schemaName' => $resolvedName->schemaName,
243
            ':tableName' => $resolvedName->name,
244
        ])->queryAll();
245
        $indexes = $this->normalizePdoRowKeyCase($indexes, true);
246
        $indexes = ArrayHelper::index($indexes, null, 'name');
247
        $result = [];
248
        foreach ($indexes as $name => $index) {
249
            $result[] = new IndexConstraint([
250
                'isPrimary' => (bool) $index[0]['index_is_primary'],
251
                'isUnique' => (bool) $index[0]['index_is_unique'],
252
                'name' => $name,
253
                'columnNames' => ArrayHelper::getColumn($index, 'column_name'),
254
            ]);
255
        }
256
257
        return $result;
258
    }
259
260
    /**
261
     * {@inheritdoc}
262
     */
263
    protected function loadTableUniques($tableName)
264
    {
265
        return $this->loadTableConstraints($tableName, 'uniques');
266
    }
267
268
    /**
269
     * {@inheritdoc}
270
     */
271
    protected function loadTableChecks($tableName)
272
    {
273
        return $this->loadTableConstraints($tableName, 'checks');
274
    }
275
276
    /**
277
     * {@inheritdoc}
278
     * @throws NotSupportedException if this method is called.
279
     */
280
    protected function loadTableDefaultValues($tableName)
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

280
    protected function loadTableDefaultValues(/** @scrutinizer ignore-unused */ $tableName)

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...
281
    {
282
        throw new NotSupportedException('PostgreSQL does not support default value constraints.');
283
    }
284
285
    /**
286
     * Creates a query builder for the PostgreSQL database.
287
     * @return QueryBuilder query builder instance
288
     */
289
    public function createQueryBuilder()
290
    {
291
        return new QueryBuilder($this->db);
292
    }
293
294
    /**
295
     * Resolves the table name and schema name (if any).
296
     * @param TableSchema $table the table metadata object
297
     * @param string $name the table name
298
     */
299
    protected function resolveTableNames($table, $name)
300
    {
301
        $parts = explode('.', str_replace('"', '', $name));
302
303
        if (isset($parts[1])) {
304
            $table->schemaName = $parts[0];
305
            $table->name = $parts[1];
306
        } else {
307
            $table->schemaName = $this->defaultSchema;
308
            $table->name = $parts[0];
309
        }
310
311
        $table->fullName = $table->schemaName !== $this->defaultSchema ? $table->schemaName . '.' . $table->name : $table->name;
312
    }
313
314
    /**
315
     * {@inheritdoc]
316
     */
317
    protected function findViewNames($schema = '')
318
    {
319
        if ($schema === '') {
320
            $schema = $this->defaultSchema;
321
        }
322
        $sql = <<<'SQL'
323
SELECT c.relname AS table_name
324
FROM pg_class c
325
INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace
326
WHERE ns.nspname = :schemaName AND (c.relkind = 'v' OR c.relkind = 'm')
327
ORDER BY c.relname
328
SQL;
329
        return $this->db->createCommand($sql, [':schemaName' => $schema])->queryColumn();
330
    }
331
332
    /**
333
     * Collects the foreign key column details for the given table.
334
     * @param TableSchema $table the table metadata
335
     */
336
    protected function findConstraints($table)
337
    {
338
        $tableName = $this->quoteValue($table->name);
339
        $tableSchema = $this->quoteValue($table->schemaName);
340
341
        //We need to extract the constraints de hard way since:
342
        //http://www.postgresql.org/message-id/[email protected]
343
344
        $sql = <<<SQL
345
select
346
    ct.conname as constraint_name,
347
    a.attname as column_name,
348
    fc.relname as foreign_table_name,
349
    fns.nspname as foreign_table_schema,
350
    fa.attname as foreign_column_name
351
from
352
    (SELECT ct.conname, ct.conrelid, ct.confrelid, ct.conkey, ct.contype, ct.confkey, generate_subscripts(ct.conkey, 1) AS s
353
       FROM pg_constraint ct
354
    ) AS ct
355
    inner join pg_class c on c.oid=ct.conrelid
356
    inner join pg_namespace ns on c.relnamespace=ns.oid
357
    inner join pg_attribute a on a.attrelid=ct.conrelid and a.attnum = ct.conkey[ct.s]
358
    left join pg_class fc on fc.oid=ct.confrelid
359
    left join pg_namespace fns on fc.relnamespace=fns.oid
360
    left join pg_attribute fa on fa.attrelid=ct.confrelid and fa.attnum = ct.confkey[ct.s]
361
where
362
    ct.contype='f'
363
    and c.relname={$tableName}
364
    and ns.nspname={$tableSchema}
365
order by
366
    fns.nspname, fc.relname, a.attnum
367
SQL;
368
369
        $constraints = [];
370
        foreach ($this->db->createCommand($sql)->queryAll() as $constraint) {
371
            if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) === \PDO::CASE_UPPER) {
372
                $constraint = array_change_key_case($constraint, CASE_LOWER);
373
            }
374
            if ($constraint['foreign_table_schema'] !== $this->defaultSchema) {
375
                $foreignTable = $constraint['foreign_table_schema'] . '.' . $constraint['foreign_table_name'];
376
            } else {
377
                $foreignTable = $constraint['foreign_table_name'];
378
            }
379
            $name = $constraint['constraint_name'];
380
            if (!isset($constraints[$name])) {
381
                $constraints[$name] = [
382
                    'tableName' => $foreignTable,
383
                    'columns' => [],
384
                ];
385
            }
386
            $constraints[$name]['columns'][$constraint['column_name']] = $constraint['foreign_column_name'];
387
        }
388
        foreach ($constraints as $name => $constraint) {
389
            $table->foreignKeys[$name] = array_merge([$constraint['tableName']], $constraint['columns']);
390
        }
391
    }
392
393
    /**
394
     * Gets information about given table unique indexes.
395
     * @param TableSchema $table the table metadata
396
     * @return array with index and column names
397
     */
398
    protected function getUniqueIndexInformation($table)
399
    {
400
        $sql = <<<'SQL'
401
SELECT
402
    i.relname as indexname,
403
    pg_get_indexdef(idx.indexrelid, k + 1, TRUE) AS columnname
404
FROM (
405
  SELECT *, generate_subscripts(indkey, 1) AS k
406
  FROM pg_index
407
) idx
408
INNER JOIN pg_class i ON i.oid = idx.indexrelid
409
INNER JOIN pg_class c ON c.oid = idx.indrelid
410
INNER JOIN pg_namespace ns ON c.relnamespace = ns.oid
411
WHERE idx.indisprimary = FALSE AND idx.indisunique = TRUE
412
AND c.relname = :tableName AND ns.nspname = :schemaName
413
ORDER BY i.relname, k
414
SQL;
415
416
        return $this->db->createCommand($sql, [
417
            ':schemaName' => $table->schemaName,
418
            ':tableName' => $table->name,
419
        ])->queryAll();
420
    }
421
422
    /**
423
     * Returns all unique indexes for the given table.
424
     *
425
     * Each array element is of the following structure:
426
     *
427
     * ```php
428
     * [
429
     *     'IndexName1' => ['col1' [, ...]],
430
     *     'IndexName2' => ['col2' [, ...]],
431
     * ]
432
     * ```
433
     *
434
     * @param TableSchema $table the table metadata
435
     * @return array all unique indexes for the given table.
436
     */
437
    public function findUniqueIndexes($table)
438
    {
439
        $uniqueIndexes = [];
440
441
        foreach ($this->getUniqueIndexInformation($table) as $row) {
442
            if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) === \PDO::CASE_UPPER) {
443
                $row = array_change_key_case($row, CASE_LOWER);
444
            }
445
            $column = $row['columnname'];
446
            if (strpos($column, '"') === 0) {
447
                // postgres will quote names that are not lowercase-only
448
                // https://github.com/yiisoft/yii2/issues/10613
449
                $column = substr($column, 1, -1);
450
            }
451
            $uniqueIndexes[$row['indexname']][] = $column;
452
        }
453
454
        return $uniqueIndexes;
455
    }
456
457
    /**
458
     * Collects the metadata of table columns.
459
     * @param TableSchema $table the table metadata
460
     * @return bool whether the table exists in the database
461
     */
462
    protected function findColumns($table)
463
    {
464
        $tableName = $this->db->quoteValue($table->name);
465
        $schemaName = $this->db->quoteValue($table->schemaName);
466
467
        $orIdentity = '';
468
        if (version_compare($this->db->serverVersion, '12.0', '>=')) {
469
            $orIdentity = 'OR attidentity != \'\'';
470
        }
471
472
        $sql = <<<SQL
473
SELECT
474
    d.nspname AS table_schema,
475
    c.relname AS table_name,
476
    a.attname AS column_name,
477
    COALESCE(td.typname, tb.typname, t.typname) AS data_type,
478
    COALESCE(td.typtype, tb.typtype, t.typtype) AS type_type,
479
    a.attlen AS character_maximum_length,
480
    pg_catalog.col_description(c.oid, a.attnum) AS column_comment,
481
    a.atttypmod AS modifier,
482
    a.attnotnull = false AS is_nullable,
483
    CAST(pg_get_expr(ad.adbin, ad.adrelid) AS varchar) AS column_default,
484
    coalesce(pg_get_expr(ad.adbin, ad.adrelid) ~ 'nextval',false) {$orIdentity} AS is_autoinc,
485
    pg_get_serial_sequence(quote_ident(d.nspname) || '.' || quote_ident(c.relname), a.attname) AS sequence_name,
486
    CASE WHEN COALESCE(td.typtype, tb.typtype, t.typtype) = 'e'::char
487
        THEN array_to_string((SELECT array_agg(enumlabel) FROM pg_enum WHERE enumtypid = COALESCE(td.oid, tb.oid, a.atttypid))::varchar[], ',')
488
        ELSE NULL
489
    END AS enum_values,
490
    CASE atttypid
491
         WHEN 21 /*int2*/ THEN 16
492
         WHEN 23 /*int4*/ THEN 32
493
         WHEN 20 /*int8*/ THEN 64
494
         WHEN 1700 /*numeric*/ THEN
495
              CASE WHEN atttypmod = -1
496
               THEN null
497
               ELSE ((atttypmod - 4) >> 16) & 65535
498
               END
499
         WHEN 700 /*float4*/ THEN 24 /*FLT_MANT_DIG*/
500
         WHEN 701 /*float8*/ THEN 53 /*DBL_MANT_DIG*/
501
         ELSE null
502
      END   AS numeric_precision,
503
      CASE
504
        WHEN atttypid IN (21, 23, 20) THEN 0
505
        WHEN atttypid IN (1700) THEN
506
        CASE
507
            WHEN atttypmod = -1 THEN null
508
            ELSE (atttypmod - 4) & 65535
509
        END
510
           ELSE null
511
      END AS numeric_scale,
512
    CAST(
513
             information_schema._pg_char_max_length(information_schema._pg_truetypid(a, t), information_schema._pg_truetypmod(a, t))
514
             AS numeric
515
    ) AS size,
516
    a.attnum = any (ct.conkey) as is_pkey,
517
    COALESCE(NULLIF(a.attndims, 0), NULLIF(t.typndims, 0), (t.typcategory='A')::int) AS dimension
518
FROM
519
    pg_class c
520
    LEFT JOIN pg_attribute a ON a.attrelid = c.oid
521
    LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum
522
    LEFT JOIN pg_type t ON a.atttypid = t.oid
523
    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
524
    LEFT JOIN pg_type td ON t.typndims > 0 AND t.typbasetype > 0 AND tb.typelem = td.oid
525
    LEFT JOIN pg_namespace d ON d.oid = c.relnamespace
526
    LEFT JOIN pg_constraint ct ON ct.conrelid = c.oid AND ct.contype = 'p'
527
WHERE
528
    a.attnum > 0 AND t.typname != '' AND NOT a.attisdropped
529
    AND c.relname = {$tableName}
530
    AND d.nspname = {$schemaName}
531
ORDER BY
532
    a.attnum;
533
SQL;
534
        $columns = $this->db->createCommand($sql)->queryAll();
535
        if (empty($columns)) {
536
            return false;
537
        }
538
        foreach ($columns as $column) {
539
            if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) === \PDO::CASE_UPPER) {
540
                $column = array_change_key_case($column, CASE_LOWER);
541
            }
542
            $column = $this->loadColumnSchema($column);
543
            $table->columns[$column->name] = $column;
544
            if ($column->isPrimaryKey) {
545
                $table->primaryKey[] = $column->name;
546
                if ($table->sequenceName === null) {
547
                    $table->sequenceName = $column->sequenceName;
548
                }
549
                $column->defaultValue = null;
550
            } elseif ($column->defaultValue) {
551
                if (
552
                    in_array($column->type, [self::TYPE_TIMESTAMP, self::TYPE_DATE, self::TYPE_TIME], true) &&
553
                    in_array(
554
                        strtoupper($column->defaultValue),
555
                        ['NOW()', 'CURRENT_TIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIME'],
556
                        true
557
                    )
558
                ) {
559
                    $column->defaultValue = new Expression($column->defaultValue);
560
                } elseif ($column->type === 'boolean') {
561
                    $column->defaultValue = ($column->defaultValue === 'true');
562
                } elseif (preg_match("/^B'(.*?)'::/", $column->defaultValue, $matches)) {
563
                    $column->defaultValue = bindec($matches[1]);
564
                } elseif (preg_match("/^'(\d+)'::\"bit\"$/", $column->defaultValue, $matches)) {
565
                    $column->defaultValue = bindec($matches[1]);
566
                } elseif (preg_match("/^'(.*?)'::/", $column->defaultValue, $matches)) {
567
                    $column->defaultValue = $column->phpTypecast($matches[1]);
568
                } elseif (preg_match('/^(\()?(.*?)(?(1)\))(?:::.+)?$/', $column->defaultValue, $matches)) {
569
                    if ($matches[2] === 'NULL') {
570
                        $column->defaultValue = null;
571
                    } else {
572
                        $column->defaultValue = $column->phpTypecast($matches[2]);
573
                    }
574
                } else {
575
                    $column->defaultValue = $column->phpTypecast($column->defaultValue);
576
                }
577
            }
578
        }
579
580
        return true;
581
    }
582
583
    /**
584
     * Loads the column information into a [[ColumnSchema]] object.
585
     * @param array $info column information
586
     * @return ColumnSchema the column schema object
587
     */
588
    protected function loadColumnSchema($info)
589
    {
590
        /** @var ColumnSchema $column */
591
        $column = $this->createColumnSchema();
592
        $column->allowNull = $info['is_nullable'];
593
        $column->autoIncrement = $info['is_autoinc'];
594
        $column->comment = $info['column_comment'];
595
        $column->dbType = $info['data_type'];
596
        $column->defaultValue = $info['column_default'];
597
        $column->enumValues = ($info['enum_values'] !== null) ? explode(',', str_replace(["''"], ["'"], $info['enum_values'])) : null;
598
        $column->unsigned = false; // has no meaning in PG
599
        $column->isPrimaryKey = $info['is_pkey'];
600
        $column->name = $info['column_name'];
601
        $column->precision = $info['numeric_precision'];
602
        $column->scale = $info['numeric_scale'];
603
        $column->size = $info['size'] === null ? null : (int) $info['size'];
604
        $column->dimension = (int)$info['dimension'];
605
        // pg_get_serial_sequence() doesn't track DEFAULT value change. GENERATED BY IDENTITY columns always have null default value
606
        if (isset($column->defaultValue) && preg_match("/nextval\\('\"?\\w+\"?\.?\"?\\w+\"?'(::regclass)?\\)/", $column->defaultValue) === 1) {
607
            $column->sequenceName = preg_replace(['/nextval/', '/::/', '/regclass/', '/\'\)/', '/\(\'/'], '', $column->defaultValue);
608
        } elseif (isset($info['sequence_name'])) {
609
            $column->sequenceName = $this->resolveTableName($info['sequence_name'])->fullName;
610
        }
611
612
        if (isset($this->typeMap[$column->dbType])) {
613
            $column->type = $this->typeMap[$column->dbType];
614
        } else {
615
            $column->type = self::TYPE_STRING;
616
        }
617
        $column->phpType = $this->getColumnPhpType($column);
618
619
        return $column;
620
    }
621
622
    /**
623
     * {@inheritdoc}
624
     */
625
    public function insert($table, $columns)
626
    {
627
        $params = [];
628
        $sql = $this->db->getQueryBuilder()->insert($table, $columns, $params);
629
        $returnColumns = $this->getTableSchema($table)->primaryKey;
630
        if (!empty($returnColumns)) {
631
            $returning = [];
632
            foreach ((array) $returnColumns as $name) {
633
                $returning[] = $this->quoteColumnName($name);
634
            }
635
            $sql .= ' RETURNING ' . implode(', ', $returning);
636
        }
637
638
        $command = $this->db->createCommand($sql, $params);
639
        $command->prepare(false);
640
        $result = $command->queryOne();
641
642
        return !$command->pdoStatement->rowCount() ? false : $result;
643
    }
644
645
    /**
646
     * Loads multiple types of constraints and returns the specified ones.
647
     * @param string $tableName table name.
648
     * @param string $returnType return type:
649
     * - primaryKey
650
     * - foreignKeys
651
     * - uniques
652
     * - checks
653
     * @return mixed constraints.
654
     */
655
    private function loadTableConstraints($tableName, $returnType)
656
    {
657
        static $sql = <<<'SQL'
658
SELECT
659
    "c"."conname" AS "name",
660
    "a"."attname" AS "column_name",
661
    "c"."contype" AS "type",
662
    "ftcns"."nspname" AS "foreign_table_schema",
663
    "ftc"."relname" AS "foreign_table_name",
664
    "fa"."attname" AS "foreign_column_name",
665
    "c"."confupdtype" AS "on_update",
666
    "c"."confdeltype" AS "on_delete",
667
    pg_get_constraintdef("c"."oid") AS "check_expr"
668
FROM "pg_class" AS "tc"
669
INNER JOIN "pg_namespace" AS "tcns"
670
    ON "tcns"."oid" = "tc"."relnamespace"
671
INNER JOIN "pg_constraint" AS "c"
672
    ON "c"."conrelid" = "tc"."oid"
673
INNER JOIN "pg_attribute" AS "a"
674
    ON "a"."attrelid" = "c"."conrelid" AND "a"."attnum" = ANY ("c"."conkey")
675
LEFT JOIN "pg_class" AS "ftc"
676
    ON "ftc"."oid" = "c"."confrelid"
677
LEFT JOIN "pg_namespace" AS "ftcns"
678
    ON "ftcns"."oid" = "ftc"."relnamespace"
679
LEFT JOIN "pg_attribute" "fa"
680
    ON "fa"."attrelid" = "c"."confrelid" AND "fa"."attnum" = ANY ("c"."confkey")
681
WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName
682
ORDER BY "a"."attnum" ASC, "fa"."attnum" ASC
683
SQL;
684
        static $actionTypes = [
685
            'a' => 'NO ACTION',
686
            'r' => 'RESTRICT',
687
            'c' => 'CASCADE',
688
            'n' => 'SET NULL',
689
            'd' => 'SET DEFAULT',
690
        ];
691
692
        $resolvedName = $this->resolveTableName($tableName);
693
        $constraints = $this->db->createCommand($sql, [
694
            ':schemaName' => $resolvedName->schemaName,
695
            ':tableName' => $resolvedName->name,
696
        ])->queryAll();
697
        $constraints = $this->normalizePdoRowKeyCase($constraints, true);
698
        $constraints = ArrayHelper::index($constraints, null, ['type', 'name']);
699
        $result = [
700
            'primaryKey' => null,
701
            'foreignKeys' => [],
702
            'uniques' => [],
703
            'checks' => [],
704
        ];
705
        foreach ($constraints as $type => $names) {
706
            foreach ($names as $name => $constraint) {
707
                switch ($type) {
708
                    case 'p':
709
                        $result['primaryKey'] = new Constraint([
710
                            'name' => $name,
711
                            'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
712
                        ]);
713
                        break;
714
                    case 'f':
715
                        $result['foreignKeys'][] = new ForeignKeyConstraint([
716
                            'name' => $name,
717
                            'columnNames' => array_keys(array_count_values(ArrayHelper::getColumn($constraint, 'column_name'))),
718
                            'foreignSchemaName' => $constraint[0]['foreign_table_schema'],
719
                            'foreignTableName' => $constraint[0]['foreign_table_name'],
720
                            'foreignColumnNames' => array_keys(array_count_values(ArrayHelper::getColumn($constraint, 'foreign_column_name'))),
721
                            'onDelete' => isset($actionTypes[$constraint[0]['on_delete']]) ? $actionTypes[$constraint[0]['on_delete']] : null,
722
                            'onUpdate' => isset($actionTypes[$constraint[0]['on_update']]) ? $actionTypes[$constraint[0]['on_update']] : null,
723
                        ]);
724
                        break;
725
                    case 'u':
726
                        $result['uniques'][] = new Constraint([
727
                            'name' => $name,
728
                            'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
729
                        ]);
730
                        break;
731
                    case 'c':
732
                        $result['checks'][] = new CheckConstraint([
733
                            'name' => $name,
734
                            'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
735
                            'expression' => $constraint[0]['check_expr'],
736
                        ]);
737
                        break;
738
                }
739
            }
740
        }
741
        foreach ($result as $type => $data) {
742
            $this->setTableMetadata($tableName, $type, $data);
743
        }
744
745
        return $result[$returnType];
746
    }
747
}
748