Passed
Pull Request — master (#16)
by Wilmer
11:25
created

Schema::loadTableUniques()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Pgsql;
6
7
use Yiisoft\Db\Constraint\CheckConstraint;
8
use Yiisoft\Db\Constraint\Constraint;
9
use Yiisoft\Db\Constraint\ConstraintFinderInterface;
10
use Yiisoft\Db\Constraint\ConstraintFinderTrait;
11
use Yiisoft\Db\Constraint\ForeignKeyConstraint;
12
use Yiisoft\Db\Constraint\IndexConstraint;
13
use Yiisoft\Db\Exception\NotSupportedException;
14
use Yiisoft\Db\Expression\Expression;
15
use Yiisoft\Db\Schema\TableSchema;
16
use Yiisoft\Db\View\ViewFinderTrait;
17
use Yiisoft\Arrays\ArrayHelper;
18
19
/**
20
 * Schema is the class for retrieving metadata from a Postgres SQL database
21
 * (version 9.x and above).
22
 */
23
class Schema extends \Yiisoft\Db\Schema\Schema implements ConstraintFinderInterface
24
{
25
    use ViewFinderTrait;
26
    use ConstraintFinderTrait;
27
28
    public const TYPE_JSONB = 'jsonb';
29
30
    /**
31
     * @var string the default schema used for the current session.
32
     */
33
    public ?string $defaultSchema = 'public';
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    public string $columnSchemaClass = ColumnSchema::class;
39
40
    /**
41
     * @var array mapping from physical column types (keys) to abstract
42
     * column types (values)
43
     *
44
     * {@see http://www.postgresql.org/docs/current/static/datatype.html#DATATYPE-TABLE}
45
     */
46
    public array $typeMap = [
47
        'bit' => self::TYPE_INTEGER,
48
        'bit varying' => self::TYPE_INTEGER,
49
        'varbit' => self::TYPE_INTEGER,
50
        'bool' => self::TYPE_BOOLEAN,
51
        'boolean' => self::TYPE_BOOLEAN,
52
        'box' => self::TYPE_STRING,
53
        'circle' => self::TYPE_STRING,
54
        'point' => self::TYPE_STRING,
55
        'line' => self::TYPE_STRING,
56
        'lseg' => self::TYPE_STRING,
57
        'polygon' => self::TYPE_STRING,
58
        'path' => self::TYPE_STRING,
59
        'character' => self::TYPE_CHAR,
60
        'char' => self::TYPE_CHAR,
61
        'bpchar' => self::TYPE_CHAR,
62
        'character varying' => self::TYPE_STRING,
63
        'varchar' => self::TYPE_STRING,
64
        'text' => self::TYPE_TEXT,
65
        'bytea' => self::TYPE_BINARY,
66
        'cidr' => self::TYPE_STRING,
67
        'inet' => self::TYPE_STRING,
68
        'macaddr' => self::TYPE_STRING,
69
        'real' => self::TYPE_FLOAT,
70
        'float4' => self::TYPE_FLOAT,
71
        'double precision' => self::TYPE_DOUBLE,
72
        'float8' => self::TYPE_DOUBLE,
73
        'decimal' => self::TYPE_DECIMAL,
74
        'numeric' => self::TYPE_DECIMAL,
75
        'money' => self::TYPE_MONEY,
76
        'smallint' => self::TYPE_SMALLINT,
77
        'int2' => self::TYPE_SMALLINT,
78
        'int4' => self::TYPE_INTEGER,
79
        'int' => self::TYPE_INTEGER,
80
        'integer' => self::TYPE_INTEGER,
81
        'bigint' => self::TYPE_BIGINT,
82
        'int8' => self::TYPE_BIGINT,
83
        'oid' => self::TYPE_BIGINT, // should not be used. it's pg internal!
84
        'smallserial' => self::TYPE_SMALLINT,
85
        'serial2' => self::TYPE_SMALLINT,
86
        'serial4' => self::TYPE_INTEGER,
87
        'serial' => self::TYPE_INTEGER,
88
        'bigserial' => self::TYPE_BIGINT,
89
        'serial8' => self::TYPE_BIGINT,
90
        'pg_lsn' => self::TYPE_BIGINT,
91
        'date' => self::TYPE_DATE,
92
        'interval' => self::TYPE_STRING,
93
        'time without time zone' => self::TYPE_TIME,
94
        'time' => self::TYPE_TIME,
95
        'time with time zone' => self::TYPE_TIME,
96
        'timetz' => self::TYPE_TIME,
97
        'timestamp without time zone' => self::TYPE_TIMESTAMP,
98
        'timestamp' => self::TYPE_TIMESTAMP,
99
        'timestamp with time zone' => self::TYPE_TIMESTAMP,
100
        'timestamptz' => self::TYPE_TIMESTAMP,
101
        'abstime' => self::TYPE_TIMESTAMP,
102
        'tsquery' => self::TYPE_STRING,
103
        'tsvector' => self::TYPE_STRING,
104
        'txid_snapshot' => self::TYPE_STRING,
105
        'unknown' => self::TYPE_STRING,
106
        'uuid' => self::TYPE_STRING,
107
        'json' => self::TYPE_JSON,
108
        'jsonb' => self::TYPE_JSON,
109
        'xml' => self::TYPE_STRING,
110
    ];
111
112
    /**
113
     * {@inheritdoc}
114
     */
115
    protected string $tableQuoteCharacter = '"';
116
117
    /**
118
     * {@inheritdoc}
119
     */
120 71
    protected function resolveTableName($name)
121
    {
122 71
        $resolvedName = new TableSchema();
123 71
        $parts = \explode('.', \str_replace('"', '', $name));
124
125 71
        if (isset($parts[1])) {
126
            $resolvedName->schemaName = $parts[0];
127
            $resolvedName->name = $parts[1];
128
        } else {
129 71
            $resolvedName->schemaName = $this->defaultSchema;
130 71
            $resolvedName->name = $name;
131
        }
132 71
        $resolvedName->fullName = ($resolvedName->schemaName !== $this->defaultSchema ? $resolvedName->schemaName . '.' : '')
133 71
            . $resolvedName->name;
134 71
        return $resolvedName;
135
    }
136
137
    /**
138
     * {@inheritdoc}
139
     */
140 2
    protected function findSchemaNames()
141
    {
142 2
        static $sql = <<<'SQL'
143
SELECT "ns"."nspname"
144
FROM "pg_namespace" AS "ns"
145
WHERE "ns"."nspname" != 'information_schema' AND "ns"."nspname" NOT LIKE 'pg_%'
146
ORDER BY "ns"."nspname" ASC
147
SQL;
148
149 2
        return $this->db->createCommand($sql)->queryColumn();
0 ignored issues
show
Bug introduced by
The method createCommand() does not exist on null. ( Ignorable by Annotation )

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

149
        return $this->db->/** @scrutinizer ignore-call */ createCommand($sql)->queryColumn();

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

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

Loading history...
150
    }
151
152
    /**
153
     * {@inheritdoc}
154
     */
155 5
    protected function findTableNames($schema = '')
156
    {
157 5
        if ($schema === '') {
158 5
            $schema = $this->defaultSchema;
159
        }
160
        $sql = <<<'SQL'
161 5
SELECT c.relname AS table_name
162
FROM pg_class c
163
INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace
164
WHERE ns.nspname = :schemaName AND c.relkind IN ('r','v','m','f', 'p')
165
ORDER BY c.relname
166
SQL;
167 5
        return $this->db->createCommand($sql, [':schemaName' => $schema])->queryColumn();
168
    }
169
170
    /**
171
     * {@inheritdoc}
172
     */
173 98
    protected function loadTableSchema(string $name): ?TableSchema
174
    {
175 98
        $table = new TableSchema();
176 98
        $this->resolveTableNames($table, $name);
177
178 98
        if ($this->findColumns($table)) {
179 91
            $this->findConstraints($table);
180 91
            return $table;
181
        }
182
183 18
        return null;
184
    }
185
186
    /**
187
     * {@inheritdoc}
188
     */
189 31
    protected function loadTablePrimaryKey($tableName)
190
    {
191 31
        return $this->loadTableConstraints($tableName, 'primaryKey');
192
    }
193
194
    /**
195
     * {@inheritdoc}
196
     */
197 4
    protected function loadTableForeignKeys($tableName)
198
    {
199 4
        return $this->loadTableConstraints($tableName, 'foreignKeys');
200
    }
201
202
    /**
203
     * {@inheritdoc}
204
     */
205 28
    protected function loadTableIndexes($tableName)
206
    {
207 28
        static $sql = <<<'SQL'
208
SELECT
209
    "ic"."relname" AS "name",
210
    "ia"."attname" AS "column_name",
211
    "i"."indisunique" AS "index_is_unique",
212
    "i"."indisprimary" AS "index_is_primary"
213
FROM "pg_class" AS "tc"
214
INNER JOIN "pg_namespace" AS "tcns"
215
    ON "tcns"."oid" = "tc"."relnamespace"
216
INNER JOIN "pg_index" AS "i"
217
    ON "i"."indrelid" = "tc"."oid"
218
INNER JOIN "pg_class" AS "ic"
219
    ON "ic"."oid" = "i"."indexrelid"
220
INNER JOIN "pg_attribute" AS "ia"
221
    ON "ia"."attrelid" = "i"."indrelid" AND "ia"."attnum" = ANY ("i"."indkey")
222
WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName
223
ORDER BY "ia"."attnum" ASC
224
SQL;
225
226 28
        $resolvedName = $this->resolveTableName($tableName);
227
228 28
        $indexes = $this->db->createCommand($sql, [
229 28
            ':schemaName' => $resolvedName->schemaName,
230 28
            ':tableName' => $resolvedName->name,
231 28
        ])->queryAll();
232
233 28
        $indexes = $this->normalizePdoRowKeyCase($indexes, true);
234 28
        $indexes = ArrayHelper::index($indexes, null, 'name');
235 28
        $result = [];
236
237 28
        foreach ($indexes as $name => $index) {
238 25
            $ic = new IndexConstraint();
239
240 25
            $ic->setName($name);
241 25
            $ic->setColumnNames(ArrayHelper::getColumn($index, 'column_name'));
242 25
            $ic->setIsPrimary((bool) $index[0]['index_is_primary']);
243 25
            $ic->setIsUnique((bool) $index[0]['index_is_unique']);
244
245 25
            $result[] = $ic;
246
        }
247
248 28
        return $result;
249
    }
250
251
    /**
252
     * {@inheritdoc}
253
     */
254 13
    protected function loadTableUniques($tableName)
255
    {
256 13
        return $this->loadTableConstraints($tableName, 'uniques');
257
    }
258
259
    /**
260
     * {@inheritdoc}
261
     */
262 13
    protected function loadTableChecks($tableName)
263
    {
264 13
        return $this->loadTableConstraints($tableName, 'checks');
265
    }
266
267
    /**
268
     * {@inheritdoc}
269
     *
270
     * @throws NotSupportedException if this method is called.
271
     */
272 12
    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

272
    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...
273
    {
274 12
        throw new NotSupportedException('PostgreSQL does not support default value constraints.');
275
    }
276
277
    /**
278
     * Creates a query builder for the PostgreSQL database.
279
     *
280
     * @return QueryBuilder query builder instance
281
     */
282 68
    public function createQueryBuilder()
283
    {
284 68
        return new QueryBuilder($this->db);
0 ignored issues
show
Bug introduced by
It seems like $this->db can also be of type null; however, parameter $db of Yiisoft\Db\Pgsql\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

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