Passed
Push — master ( 90b3f8...427eea )
by mark
03:38 queued 12s
created

PostgresAdapter::getChangeColumnInstructions()   C

Complexity

Conditions 9
Paths 256

Size

Total Lines 81
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 39
CRAP Score 9.2855

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 50
c 1
b 0
f 0
dl 0
loc 81
ccs 39
cts 46
cp 0.8478
rs 6.3086
cc 9
nc 256
nop 3
crap 9.2855

How to fix   Long Method   

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
/**
4
 * MIT License
5
 * For full license information, please view the LICENSE file that was distributed with this source code.
6
 */
7
8
namespace Phinx\Db\Adapter;
9
10
use Cake\Database\Connection;
11
use Cake\Database\Driver\Postgres as PostgresDriver;
12
use InvalidArgumentException;
13
use PDO;
14
use PDOException;
15
use Phinx\Db\Table\Column;
16
use Phinx\Db\Table\ForeignKey;
17
use Phinx\Db\Table\Index;
18
use Phinx\Db\Table\Table;
19
use Phinx\Db\Util\AlterInstructions;
20
use Phinx\Util\Literal;
21
use RuntimeException;
22
23
class PostgresAdapter extends PdoAdapter
24
{
25
    /**
26
     * @var string[]
27
     */
28
    protected static $specificColumnTypes = [
29
        self::PHINX_TYPE_JSON,
30
        self::PHINX_TYPE_JSONB,
31
        self::PHINX_TYPE_CIDR,
32
        self::PHINX_TYPE_INET,
33
        self::PHINX_TYPE_MACADDR,
34
        self::PHINX_TYPE_INTERVAL,
35
        self::PHINX_TYPE_BINARYUUID,
36
    ];
37
38
    /**
39
     * Columns with comments
40
     *
41
     * @var \Phinx\Db\Table\Column[]
42
     */
43
    protected $columnsWithComments = [];
44
45
    /**
46
     * {@inheritDoc}
47
     *
48
     * @throws \RuntimeException
49
     * @throws \InvalidArgumentException
50 68
     *
51
     * @return void
52 68
     */
53 68
    public function connect()
54
    {
55
        if ($this->connection === null) {
56
            if (!class_exists('PDO') || !in_array('pgsql', PDO::getAvailableDrivers(), true)) {
57
                // @codeCoverageIgnoreStart
58
                throw new RuntimeException('You need to enable the PDO_Pgsql extension for Phinx to run properly.');
59 68
                // @codeCoverageIgnoreEnd
60 68
            }
61
62
            $options = $this->getOptions();
63 68
64 68
            $dsn = 'pgsql:dbname=' . $options['name'];
65 68
66 1
            if (isset($options['host'])) {
67
                $dsn .= ';host=' . $options['host'];
68
            }
69
70 68
            // if custom port is specified use it
71 68
            if (isset($options['port'])) {
72 1
                $dsn .= ';port=' . $options['port'];
73 1
            }
74 1
75 1
            $driverOptions = [];
76
77
            // use custom data fetch mode
78 68
            if (!empty($options['fetch_mode'])) {
79 68
                $driverOptions[PDO::ATTR_DEFAULT_FETCH_MODE] = constant('\PDO::FETCH_' . strtoupper($options['fetch_mode']));
80 68
            }
81
82
            $db = $this->createPdoConnection($dsn, $options['user'] ?? null, $options['pass'] ?? null, $driverOptions);
83
84
            try {
85 68
                if (isset($options['schema'])) {
86
                    $db->exec('SET search_path TO ' . $this->quoteSchemaName($options['schema']));
87 68
                }
88 68
            } catch (PDOException $exception) {
89
                throw new InvalidArgumentException(
90
                    sprintf('Schema does not exists: %s', $options['schema']),
91
                    $exception->getCode(),
92
                    $exception
93
                );
94
            }
95
96
            $this->setConnection($db);
97
        }
98
    }
99
100
    /**
101
     * @inheritDoc
102
     */
103
    public function disconnect()
104
    {
105
        $this->connection = null;
106
    }
107
108
    /**
109
     * @inheritDoc
110
     */
111
    public function hasTransactions()
112
    {
113
        return true;
114
    }
115
116
    /**
117
     * @inheritDoc
118
     */
119
    public function beginTransaction()
120
    {
121
        $this->execute('BEGIN');
122
    }
123
124
    /**
125
     * @inheritDoc
126
     */
127
    public function commitTransaction()
128 68
    {
129
        $this->execute('COMMIT');
130 68
    }
131
132
    /**
133
     * @inheritDoc
134
     */
135
    public function rollbackTransaction()
136 68
    {
137
        $this->execute('ROLLBACK');
138 68
    }
139
140
    /**
141
     * Quotes a schema name for use in a query.
142
     *
143
     * @param string $schemaName Schema Name
144 68
     *
145
     * @return string
146 68
     */
147
    public function quoteSchemaName($schemaName)
148
    {
149
        return $this->quoteColumnName($schemaName);
150
    }
151
152 68
    /**
153
     * @inheritDoc
154 68
     */
155 68
    public function quoteTableName($tableName)
156
    {
157
        $parts = $this->getSchemaName($tableName);
158
159 68
        return $this->quoteSchemaName($parts['schema']) . '.' . $this->quoteColumnName($parts['table']);
160 68
    }
161 68
162 68
    /**
163 68
     * @inheritDoc
164
     */
165 68
    public function quoteColumnName($columnName)
166
    {
167
        return '"' . $columnName . '"';
168
    }
169
170
    /**
171 68
     * @inheritDoc
172
     */
173 68
    public function hasTable($tableName)
174
    {
175
        if ($this->hasCreatedTable($tableName)) {
176 68
            return true;
177 68
        }
178 48
179 48
        $parts = $this->getSchemaName($tableName);
180 48
        $result = $this->getConnection()->query(
181 48
            sprintf(
182
                'SELECT *
183 48
                FROM information_schema.tables
184 48
                WHERE table_schema = %s
185 68
                AND table_name = %s',
186
                $this->getConnection()->quote($parts['schema']),
187 2
                $this->getConnection()->quote($parts['table'])
188 2
            )
189 2
        );
190 2
191
        return $result->rowCount() === 1;
192 2
    }
193 2
194 2
    /**
195
     * @inheritDoc
196
     */
197 68
    public function createTable(Table $table, array $columns = [], array $indexes = [])
198 68
    {
199
        $queries = [];
200 68
201 68
        $options = $table->getOptions();
202 68
        $parts = $this->getSchemaName($table->getName());
203
204
         // Add the default primary key
205 68
        if (!isset($options['id']) || (isset($options['id']) && $options['id'] === true)) {
206 6
            $options['id'] = 'id';
207 6
        }
208 68
209
        if (isset($options['id']) && is_string($options['id'])) {
210
            // Handle id => "field_name" to support AUTO_INCREMENT
211 68
            $column = new Column();
212 68
            $column->setName($options['id'])
213 68
                   ->setType('integer')
214 68
                   ->setIdentity(true);
215 68
216 68
            array_unshift($columns, $column);
217
            if (isset($options['primary_key']) && (array)$options['id'] !== (array)$options['primary_key']) {
218
                throw new InvalidArgumentException('You cannot enable an auto incrementing ID field and a primary key');
219 1
            }
220 1
            $options['primary_key'] = $options['id'];
221 1
        }
222 1
223 1
        // TODO - process table options like collation etc
224 1
        $sql = 'CREATE TABLE ';
225 1
        $sql .= $this->quoteTableName($table->getName()) . ' (';
226 1
227 1
        $this->columnsWithComments = [];
228 1
        foreach ($columns as $column) {
229 68
            $sql .= $this->quoteColumnName($column->getName()) . ' ' . $this->getColumnSqlDefinition($column) . ', ';
230 68
231 2
            // set column comments, if needed
232
            if ($column->getComment()) {
233
                $this->columnsWithComments[] = $column;
234
            }
235 68
        }
236 68
237 1
         // set the primary key(s)
238 1
        if (isset($options['primary_key'])) {
239 1
            $sql = rtrim($sql);
240 1
            $sql .= sprintf(' CONSTRAINT %s PRIMARY KEY (', $this->quoteColumnName($parts['table'] . '_pkey'));
241
            if (is_string($options['primary_key'])) { // handle primary_key => 'id'
242 68
                $sql .= $this->quoteColumnName($options['primary_key']);
243
            } elseif (is_array($options['primary_key'])) { // handle primary_key => array('tag_id', 'resource_id')
244
                $sql .= implode(',', array_map([$this, 'quoteColumnName'], $options['primary_key']));
245 68
            }
246 6
            $sql .= ')';
247 6
        } else {
248 6
            $sql = rtrim($sql, ', '); // no primary keys
249 6
        }
250
251
        $sql .= ')';
252
        $queries[] = $sql;
253 68
254 68
        // process column comments
255 5
        if (!empty($this->columnsWithComments)) {
256 5
            foreach ($this->columnsWithComments as $column) {
257 5
                $queries[] = $this->getColumnCommentSqlDefinition($column, $table->getName());
258 5
            }
259
        }
260
261 68
        // set the indexes
262
        if (!empty($indexes)) {
263
            foreach ($indexes as $index) {
264 68
                $queries[] = $this->getIndexSqlDefinition($index, $table->getName());
265 1
            }
266 1
        }
267 1
268 1
        // process table comments
269 1
        if (isset($options['comment'])) {
270 1
            $queries[] = sprintf(
271 1
                'COMMENT ON TABLE %s IS %s',
272 68
                $this->quoteTableName($table->getName()),
273
                $this->getConnection()->quote($options['comment'])
274
            );
275
        }
276
277 1
        foreach ($queries as $query) {
278
            $this->execute($query);
279 1
        }
280 1
281 1
        $this->addCreatedTable($table->getName());
282 1
    }
283 1
284 1
    /**
285 1
     * {@inheritDoc}
286
     *
287
     * @throws \InvalidArgumentException
288
     */
289
    protected function getChangePrimaryKeyInstructions(Table $table, $newColumns)
290 1
    {
291
        $parts = $this->getSchemaName($table->getName());
292 1
293 1
        $instructions = new AlterInstructions();
294
295
        // Drop the existing primary key
296
        $primaryKey = $this->getPrimaryKey($table->getName());
297
        if (!empty($primaryKey['constraint'])) {
298 1
            $sql = sprintf(
299
                'DROP CONSTRAINT %s',
300 1
                $this->quoteColumnName($primaryKey['constraint'])
301 1
            );
302 1
            $instructions->addAlter($sql);
303 1
        }
304
305 1
        // Add the new primary key
306 1
        if (!empty($newColumns)) {
307
            $sql = sprintf(
308
                'ADD CONSTRAINT %s PRIMARY KEY (',
309
                $this->quoteColumnName($parts['table'] . '_pkey')
310
            );
311 9
            if (is_string($newColumns)) { // handle primary_key => 'id'
312
                $sql .= $this->quoteColumnName($newColumns);
313 9
            } elseif (is_array($newColumns)) { // handle primary_key => array('tag_id', 'resource_id')
314 9
                $sql .= implode(',', array_map([$this, 'quoteColumnName'], $newColumns));
315
            } else {
316
                throw new InvalidArgumentException(sprintf(
317
                    'Invalid value for primary key: %s',
318 9
                    json_encode($newColumns)
319
                ));
320 9
            }
321 9
            $sql .= ')';
322
            $instructions->addAlter($sql);
323 9
        }
324 9
325 9
        return $instructions;
326 9
    }
327 9
328 9
    /**
329 9
     * @inheritDoc
330 9
     */
331 9
    protected function getChangeCommentInstructions(Table $table, $newComment)
332
    {
333 9
        $instructions = new AlterInstructions();
334 1
335 1
        // passing 'null' is to remove table comment
336
        $newComment = ($newComment !== null)
337 9
            ? $this->getConnection()->quote($newComment)
338 5
            : 'NULL';
339 5
        $sql = sprintf(
340 9
            'COMMENT ON TABLE %s IS %s',
341 9
            $this->quoteTableName($table->getName()),
342 9
            $newComment
343
        );
344
        $instructions->addPostStep($sql);
345
346
        return $instructions;
347
    }
348 24
349
    /**
350 24
     * @inheritDoc
351
     */
352
    protected function getRenameTableInstructions($tableName, $newTableName)
353 24
    {
354 24
        $this->updateCreatedTableName($tableName, $newTableName);
355 24
        $sql = sprintf(
356
            'ALTER TABLE %s RENAME TO %s',
357 24
            $this->quoteTableName($tableName),
358
            $this->quoteColumnName($newTableName)
359 24
        );
360 24
361
        return new AlterInstructions([], [$sql]);
362
    }
363
364
    /**
365
     * @inheritDoc
366 18
     */
367
    protected function getDropTableInstructions($tableName)
368 18
    {
369 18
        $this->removeCreatedTable($tableName);
370 18
        $sql = sprintf('DROP TABLE %s', $this->quoteTableName($tableName));
371 18
372 18
        return new AlterInstructions([], [$sql]);
373 18
    }
374
375 18
    /**
376 18
     * @inheritDoc
377
     */
378
    public function truncateTable($tableName)
379
    {
380
        $sql = sprintf(
381 3
            'TRUNCATE TABLE %s RESTART IDENTITY',
382
            $this->quoteTableName($tableName)
383 3
        );
384
385
        $this->execute($sql);
386 3
    }
387 3
388
    /**
389 3
     * @inheritDoc
390 3
     */
391 3
    public function getColumns($tableName)
392 1
    {
393
        $parts = $this->getSchemaName($tableName);
394 2
        $columns = [];
395 2
        $sql = sprintf(
396 2
            'SELECT column_name, data_type, udt_name, is_identity, is_nullable,
397 2
             column_default, character_maximum_length, numeric_precision, numeric_scale,
398 2
             datetime_precision
399 2
             FROM information_schema.columns
400 2
             WHERE table_schema = %s AND table_name = %s
401 2
             ORDER BY ordinal_position',
402 2
            $this->getConnection()->quote($parts['schema']),
403
            $this->getConnection()->quote($parts['table'])
404
        );
405
        $columnsInfo = $this->fetchAll($sql);
406
407 5
        foreach ($columnsInfo as $columnInfo) {
408
            $isUserDefined = strtoupper(trim($columnInfo['data_type'])) === 'USER-DEFINED';
409
410
            if ($isUserDefined) {
411 5
                $columnType = Literal::from($columnInfo['udt_name']);
412 5
            } else {
413 5
                $columnType = $this->getPhinxType($columnInfo['data_type']);
414 5
            }
415 5
416 5
            // If the default value begins with a ' or looks like a function mark it as literal
417
            if (isset($columnInfo['column_default'][0]) && $columnInfo['column_default'][0] === "'") {
418 5
                if (preg_match('/^\'(.*)\'::[^:]+$/', $columnInfo['column_default'], $match)) {
419 5
                    // '' and \' are replaced with a single '
420
                    $columnDefault = preg_replace('/[\'\\\\]\'/', "'", $match[1]);
421 5
                } else {
422 5
                    $columnDefault = Literal::from($columnInfo['column_default']);
423
                }
424 5
            } elseif (preg_match('/^\D[a-z_\d]*\(.*\)$/', $columnInfo['column_default'])) {
425 5
                $columnDefault = Literal::from($columnInfo['column_default']);
426 5
            } else {
427 5
                $columnDefault = $columnInfo['column_default'];
428 5
            }
429 5
430 2
            $column = new Column();
431 2
            $column->setName($columnInfo['column_name'])
432 4
                   ->setType($columnType)
433
                   ->setNull($columnInfo['is_nullable'] === 'YES')
434 5
                   ->setDefault($columnDefault)
435 5
                   ->setIdentity($columnInfo['is_identity'] === 'YES')
436
                   ->setScale($columnInfo['numeric_scale']);
437 1
438 1
            if (preg_match('/\bwith time zone$/', $columnInfo['data_type'])) {
439 1
                $column->setTimezone(true);
440 1
            }
441 1
442 1
            if (isset($columnInfo['character_maximum_length'])) {
443 1
                $column->setLimit($columnInfo['character_maximum_length']);
444 1
            }
445 1
446
            if (in_array($columnType, [static::PHINX_TYPE_TIME, static::PHINX_TYPE_DATETIME], true)) {
447 4
                $column->setPrecision($columnInfo['datetime_precision']);
448 4
            } elseif (
449 4
                !in_array($columnType, [
450 4
                    self::PHINX_TYPE_SMALL_INTEGER,
451 4
                    self::PHINX_TYPE_INTEGER,
452 4
                    self::PHINX_TYPE_BIG_INTEGER,
453 4
                ], true)
454
            ) {
455
                $column->setPrecision($columnInfo['numeric_precision']);
456 5
            }
457 1
            $columns[] = $column;
458 1
        }
459 1
460 1
        return $columns;
461 1
    }
462 1
463 1
    /**
464 1
     * @inheritDoc
465 1
     */
466
    public function hasColumn($tableName, $columnName)
467
    {
468 5
        $parts = $this->getSchemaName($tableName);
469 2
        $sql = sprintf(
470 2
            'SELECT count(*)
471 2
            FROM information_schema.columns
472 5
            WHERE table_schema = %s AND table_name = %s AND column_name = %s',
473
            $this->getConnection()->quote($parts['schema']),
474
            $this->getConnection()->quote($parts['table']),
475
            $this->getConnection()->quote($columnName)
476
        );
477 1
478
        $result = $this->fetchRow($sql);
479 1
480 1
        return $result['count'] > 0;
481 1
    }
482 1
483 1
    /**
484 1
     * @inheritDoc
485 1
     */
486 1
    protected function getAddColumnInstructions(Table $table, Column $column)
487
    {
488
        $instructions = new AlterInstructions();
489
        $instructions->addAlter(sprintf(
490
            'ADD %s %s',
491
            $this->quoteColumnName($column->getName()),
492
            $this->getColumnSqlDefinition($column)
493
        ));
494 9
495
        if ($column->getComment()) {
496 9
            $instructions->addPostStep($this->getColumnCommentSqlDefinition($column, $table->getName()));
497
        }
498
499
        return $instructions;
500
    }
501
502
    /**
503
     * {@inheritDoc}
504
     *
505
     * @throws \InvalidArgumentException
506
     */
507
    protected function getRenameColumnInstructions($tableName, $columnName, $newColumnName)
508
    {
509
        $parts = $this->getSchemaName($tableName);
510
        $sql = sprintf(
511
            'SELECT CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END AS column_exists
512
             FROM information_schema.columns
513
             WHERE table_schema = %s AND table_name = %s AND column_name = %s',
514 9
            $this->getConnection()->quote($parts['schema']),
515 9
            $this->getConnection()->quote($parts['table']),
516 9
            $this->getConnection()->quote($columnName)
517 9
        );
518 9
519 9
        $result = $this->fetchRow($sql);
520 9
        if (!(bool)$result['column_exists']) {
521 9
            throw new InvalidArgumentException("The specified column does not exist: $columnName");
522 9
        }
523
524
        $instructions = new AlterInstructions();
525
        $instructions->addPostStep(
526
            sprintf(
527
                'ALTER TABLE %s RENAME COLUMN %s TO %s',
528 9
                $this->quoteTableName($tableName),
529
                $this->quoteColumnName($columnName),
530 9
                $this->quoteColumnName($newColumnName)
531 4
            )
532 4
        );
533 9
534 9
        return $instructions;
535 9
    }
536 9
537 9
    /**
538
     * @inheritDoc
539 8
     */
540 8
    protected function getChangeColumnInstructions($tableName, $columnName, Column $newColumn)
541
    {
542
        $instructions = new AlterInstructions();
543
        if ($newColumn->getType() === 'boolean') {
544
            $sql = sprintf('ALTER COLUMN %s DROP DEFAULT', $this->quoteColumnName($columnName));
545
            $instructions->addAlter($sql);
546 1
        }
547
        $sql = sprintf(
548 1
            'ALTER COLUMN %s TYPE %s',
549 1
            $this->quoteColumnName($columnName),
550 1
            $this->getColumnSqlDefinition($newColumn)
551 1
        );
552
        if (in_array($newColumn->getType(), ['smallinteger', 'integer', 'biginteger'], true)) {
553
            $sql .= sprintf(
554
                ' USING (%s::bigint)',
555
                $this->quoteColumnName($columnName)
556
            );
557
        }
558
        if ($newColumn->getType() === 'uuid') {
559
            $sql .= sprintf(
560 2
                ' USING (%s::uuid)',
561
                $this->quoteColumnName($columnName)
562 2
            );
563 2
        }
564 2
        //NULL and DEFAULT cannot be set while changing column type
565
        $sql = preg_replace('/ NOT NULL/', '', $sql);
566
        $sql = preg_replace('/ NULL/', '', $sql);
567
        //If it is set, DEFAULT is the last definition
568
        $sql = preg_replace('/DEFAULT .*/', '', $sql);
569 1
        if ($newColumn->getType() === 'boolean') {
570
            $sql .= sprintf(
571 1
                ' USING (CASE WHEN %s=0 THEN FALSE ELSE TRUE END)',
572 1
                $this->quoteColumnName($columnName)
573 1
            );
574
        }
575 1
        $instructions->addAlter($sql);
576 1
577
        // process null
578 1
        $sql = sprintf(
579 1
            'ALTER COLUMN %s',
580 1
            $this->quoteColumnName($columnName)
581 1
        );
582 1
583 1
        if ($newColumn->isNull()) {
584 1
            $sql .= ' DROP NOT NULL';
585 1
        } else {
586 1
            $sql .= ' SET NOT NULL';
587
        }
588 1
589
        $instructions->addAlter($sql);
590
591
        if ($newColumn->getDefault() !== null) {
592
            $instructions->addAlter(sprintf(
593
                'ALTER COLUMN %s SET %s',
594
                $this->quoteColumnName($columnName),
595
                $this->getDefaultValueDefinition($newColumn->getDefault(), $newColumn->getType())
596 1
            ));
597
        } else {
598 1
            //drop default
599 1
            $instructions->addAlter(sprintf(
600
                'ALTER COLUMN %s DROP DEFAULT',
601 1
                $this->quoteColumnName($columnName)
602 1
            ));
603 1
        }
604
605
        // rename column
606
        if ($columnName !== $newColumn->getName()) {
607
            $instructions->addPostStep(sprintf(
608 3
                'ALTER TABLE %s RENAME COLUMN %s TO %s',
609
                $this->quoteTableName($tableName),
610 3
                $this->quoteColumnName($columnName),
611 1
                $this->quoteColumnName($newColumn->getName())
612 1
            ));
613 3
        }
614 3
615
        // change column comment if needed
616
        if ($newColumn->getComment()) {
617
            $instructions->addPostStep($this->getColumnCommentSqlDefinition($newColumn, $tableName));
618
        }
619
620 3
        return $instructions;
621 3
    }
622 3
623 3
    /**
624
     * @inheritDoc
625 1
     */
626 1
    protected function getDropColumnInstructions($tableName, $columnName)
627
    {
628
        $alter = sprintf(
629
            'DROP COLUMN %s',
630
            $this->quoteColumnName($columnName)
631
        );
632
633
        return new AlterInstructions([$alter]);
634
    }
635
636 3
    /**
637
     * Get an array of indexes from a particular table.
638 3
     *
639 3
     * @param string $tableName Table name
640
     *
641
     * @return array
642
     */
643
    protected function getIndexes($tableName)
644
    {
645
        $parts = $this->getSchemaName($tableName);
646
647
        $indexes = [];
648
        $sql = sprintf(
649
            "SELECT
650 3
                i.relname AS index_name,
651
                a.attname AS column_name
652 3
            FROM
653 3
                pg_class t,
654 3
                pg_class i,
655 3
                pg_index ix,
656 3
                pg_attribute a,
657 3
                pg_namespace nsp
658 3
            WHERE
659 3
                t.oid = ix.indrelid
660
                AND i.oid = ix.indexrelid
661
                AND a.attrelid = t.oid
662
                AND a.attnum = ANY(ix.indkey)
663
                AND t.relnamespace = nsp.oid
664
                AND nsp.nspname = %s
665 2
                AND t.relkind = 'r'
666
                AND t.relname = %s
667 2
            ORDER BY
668 2
                t.relname,
669 2
                i.relname",
670 2
            $this->getConnection()->quote($parts['schema']),
671 2
            $this->getConnection()->quote($parts['table'])
672 2
        );
673 2
        $rows = $this->fetchAll($sql);
674
        foreach ($rows as $row) {
675
            if (!isset($indexes[$row['index_name']])) {
676
                $indexes[$row['index_name']] = ['columns' => []];
677
            }
678 1
            $indexes[$row['index_name']]['columns'][] = $row['column_name'];
679
        }
680 1
681
        return $indexes;
682
    }
683
684 1
    /**
685 1
     * @inheritDoc
686 1
     */
687 1
    public function hasIndex($tableName, $columns)
688 1
    {
689
        if (is_string($columns)) {
690 1
            $columns = [$columns];
691 1
        }
692 1
        $indexes = $this->getIndexes($tableName);
693 1
        foreach ($indexes as $index) {
694 1
            if (array_diff($index['columns'], $columns) === array_diff($columns, $index['columns'])) {
695
                return true;
696
            }
697
        }
698
699
        return false;
700
    }
701 1
702 1
    /**
703
     * @inheritDoc
704 1
     */
705
    public function hasIndexByName($tableName, $indexName)
706 1
    {
707 1
        $indexes = $this->getIndexes($tableName);
708 1
        foreach ($indexes as $name => $index) {
709 1
            if ($name === $indexName) {
710
                return true;
711 1
            }
712
        }
713
714
        return false;
715
    }
716 68
717
    /**
718
     * @inheritDoc
719 68
     */
720 14
    protected function getAddIndexInstructions(Table $table, Index $index)
721
    {
722 1
        $instructions = new AlterInstructions();
723
        $instructions->addPostStep($this->getIndexSqlDefinition($index, $table->getName()));
724 1
725
        return $instructions;
726 14
    }
727 68
728 68
    /**
729 68
     * {@inheritDoc}
730 68
     *
731 68
     * @throws \InvalidArgumentException
732 68
     */
733 68
    protected function getDropIndexByColumnsInstructions($tableName, $columns)
734 68
    {
735 68
        $parts = $this->getSchemaName($tableName);
736 68
737 68
        if (is_string($columns)) {
738 68
            $columns = [$columns]; // str to array
739 2
        }
740 68
741 68
        $indexes = $this->getIndexes($tableName);
742 68
        foreach ($indexes as $indexName => $index) {
743
            $a = array_diff($columns, $index['columns']);
744 68
            if (empty($a)) {
745 68
                return new AlterInstructions([], [sprintf(
746 68
                    'DROP INDEX IF EXISTS %s',
747 1
                    '"' . ($parts['schema'] . '".' . $this->quoteColumnName($indexName))
748 68
                )]);
749 68
            }
750 68
        }
751 15
752 15
        throw new InvalidArgumentException(sprintf(
753 1
            "The specified index on columns '%s' does not exist",
754
            implode(',', $columns)
755
        ));
756
    }
757
758 14
    /**
759
     * @inheritDoc
760
     */
761 14
    protected function getDropIndexByNameInstructions($tableName, $indexName)
762
    {
763
        $parts = $this->getSchemaName($tableName);
764 14
765
        $sql = sprintf(
766
            'DROP INDEX IF EXISTS %s',
767 14
            '"' . ($parts['schema'] . '".' . $this->quoteColumnName($indexName))
768
        );
769
770 14
        return new AlterInstructions([], [$sql]);
771 14
    }
772 13
773
    /**
774
     * @inheritDoc
775 1
     */
776 14
    public function hasPrimaryKey($tableName, $columns, $constraint = null)
777
    {
778
        $primaryKey = $this->getPrimaryKey($tableName);
779
780
        if (empty($primaryKey)) {
781
            return false;
782
        }
783
784
        if ($constraint) {
785 10
            return ($primaryKey['constraint'] === $constraint);
786
        } else {
787
            if (is_string($columns)) {
788 10
                $columns = [$columns]; // str to array
789 10
            }
790 6
            $missingColumns = array_diff($columns, $primaryKey['columns']);
791 10
792 10
            return empty($missingColumns);
793
        }
794 10
    }
795 2
796 10
    /**
797
     * Get the primary key from a particular table.
798 10
     *
799
     * @param string $tableName Table name
800 10
     *
801
     * @return array
802 1
     */
803
    public function getPrimaryKey($tableName)
804 1
    {
805 10
        $parts = $this->getSchemaName($tableName);
806 10
        $rows = $this->fetchAll(sprintf(
807 10
            "SELECT
808 9
                    tc.constraint_name,
809 5
                    kcu.column_name
810 5
                FROM information_schema.table_constraints AS tc
811 3
                JOIN information_schema.key_column_usage AS kcu
812 4
                    ON tc.constraint_name = kcu.constraint_name
813 4
                WHERE constraint_type = 'PRIMARY KEY'
814 2
                    AND tc.table_schema = %s
815 4
                    AND tc.table_name = %s
816 4
                ORDER BY kcu.position_in_unique_constraint",
817 2
            $this->getConnection()->quote($parts['schema']),
818 4
            $this->getConnection()->quote($parts['table'])
819 1
        ));
820
821 4
        $primaryKey = [
822 4
            'columns' => [],
823 4
        ];
824 4
        foreach ($rows as $row) {
825 3
            $primaryKey['constraint'] = $row['constraint_name'];
826 4
            $primaryKey['columns'][] = $row['column_name'];
827 2
        }
828 4
829 4
        return $primaryKey;
830 4
    }
831 4
832 3
    /**
833 3
     * @inheritDoc
834 3
     */
835 3
    public function hasForeignKey($tableName, $columns, $constraint = null)
836 1
    {
837 1
        if (is_string($columns)) {
838
            $columns = [$columns]; // str to array
839
        }
840
        $foreignKeys = $this->getForeignKeys($tableName);
841
        if ($constraint) {
842
            if (isset($foreignKeys[$constraint])) {
843
                return !empty($foreignKeys[$constraint]);
844
            }
845
846
            return false;
847
        }
848
849
        foreach ($foreignKeys as $key) {
850
            $a = array_diff($columns, $key['columns']);
851
            if (empty($a)) {
852 1
                return true;
853
            }
854 1
        }
855 1
856 1
        return false;
857
    }
858
859
    /**
860
     * Get an array of foreign keys from a particular table.
861 2
     *
862
     * @param string $tableName Table name
863 2
     *
864 2
     * @return array
865 2
     */
866
    protected function getForeignKeys($tableName)
867
    {
868
        $parts = $this->getSchemaName($tableName);
869
        $foreignKeys = [];
870
        $rows = $this->fetchAll(sprintf(
871 1
            "SELECT
872
                    tc.constraint_name,
873 1
                    tc.table_name, kcu.column_name,
874 1
                    ccu.table_name AS referenced_table_name,
875 1
                    ccu.column_name AS referenced_column_name
876 1
                FROM
877
                    information_schema.table_constraints AS tc
878
                    JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name
879
                    JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name
880
                WHERE constraint_type = 'FOREIGN KEY' AND tc.table_schema = %s AND tc.table_name = %s
881
                ORDER BY kcu.position_in_unique_constraint",
882
            $this->getConnection()->quote($parts['schema']),
883
            $this->getConnection()->quote($parts['table'])
884 68
        ));
885
        foreach ($rows as $row) {
886 68
            $foreignKeys[$row['constraint_name']]['table'] = $row['table_name'];
887 4
            $foreignKeys[$row['constraint_name']]['columns'][] = $row['column_name'];
888 68
            $foreignKeys[$row['constraint_name']]['referenced_table'] = $row['referenced_table_name'];
889 68
            $foreignKeys[$row['constraint_name']]['referenced_columns'][] = $row['referenced_column_name'];
890 68
        }
891 68
892
        return $foreignKeys;
893
    }
894
895
    /**
896
     * @inheritDoc
897
     */
898
    protected function getAddForeignKeyInstructions(Table $table, ForeignKey $foreignKey)
899
    {
900 68
        $alter = sprintf(
901
            'ADD %s',
902 68
            $this->getForeignKeySqlDefinition($foreignKey, $table->getName())
903 68
        );
904 50
905 50
        return new AlterInstructions([$alter]);
906 68
    }
907 68
908
    /**
909 68
     * @inheritDoc
910 1
     */
911 1
    protected function getDropForeignKeyInstructions($tableName, $constraint)
912 1
    {
913 1
        $alter = sprintf(
914 1
            'DROP CONSTRAINT %s',
915 68
            $this->quoteColumnName($constraint)
916
        );
917
918
        return new AlterInstructions([$alter]);
919
    }
920
921
    /**
922 68
     * @inheritDoc
923 68
     */
924 68
    protected function getDropForeignKeyByColumnsInstructions($tableName, $columns)
925 68
    {
926 68
        $instructions = new AlterInstructions();
927
928
        $parts = $this->getSchemaName($tableName);
929 68
        $sql = 'SELECT c.CONSTRAINT_NAME
930 68
                FROM (
931 68
                    SELECT CONSTRAINT_NAME, array_agg(COLUMN_NAME::varchar) as columns
932 68
                    FROM information_schema.KEY_COLUMN_USAGE
933 1
                    WHERE TABLE_SCHEMA = %s
934 1
                    AND TABLE_NAME IS NOT NULL
935
                    AND TABLE_NAME = %s
936
                    AND POSITION_IN_UNIQUE_CONSTRAINT IS NOT NULL
937 68
                    GROUP BY CONSTRAINT_NAME
938
                ) c
939 68
                WHERE
940 68
                    ARRAY[%s]::varchar[] <@ c.columns AND
941 68
                    ARRAY[%s]::varchar[] @> c.columns';
942
943 68
        $array = [];
944
        foreach ($columns as $col) {
945
            $array[] = "'$col'";
946
        }
947
948
        $rows = $this->fetchAll(sprintf(
949
            $sql,
950
            $this->getConnection()->quote($parts['schema']),
951
            $this->getConnection()->quote($parts['table']),
952
            implode(',', $array),
953 6
            implode(',', $array)
954
        ));
955
956 6
        foreach ($rows as $row) {
957 6
            $newInstr = $this->getDropForeignKeyInstructions($tableName, $row['constraint_name']);
958 6
            $instructions->merge($newInstr);
959
        }
960 6
961 6
        return $instructions;
962 6
    }
963 6
964
    /**
965 6
     * {@inheritDoc}
966
     *
967
     * @throws \Phinx\Db\Adapter\UnsupportedColumnTypeException
968
     */
969
    public function getSqlType($type, $limit = null)
970
    {
971
        switch ($type) {
972
            case static::PHINX_TYPE_TEXT:
973
            case static::PHINX_TYPE_TIME:
974
            case static::PHINX_TYPE_DATE:
975 7
            case static::PHINX_TYPE_BOOLEAN:
976
            case static::PHINX_TYPE_JSON:
977 7
            case static::PHINX_TYPE_JSONB:
978 3
            case static::PHINX_TYPE_UUID:
979 3
            case static::PHINX_TYPE_CIDR:
980 5
            case static::PHINX_TYPE_INET:
981 5
            case static::PHINX_TYPE_MACADDR:
982
            case static::PHINX_TYPE_TIMESTAMP:
983
            case static::PHINX_TYPE_INTEGER:
984 5
                return ['name' => $type];
985
            case static::PHINX_TYPE_TINY_INTEGER:
986 7
                return ['name' => 'smallint'];
987 7
            case static::PHINX_TYPE_SMALL_INTEGER:
988 7
                return ['name' => 'smallint'];
989 7
            case static::PHINX_TYPE_DECIMAL:
990 7
                return ['name' => $type, 'precision' => 18, 'scale' => 0];
991 7
            case static::PHINX_TYPE_DOUBLE:
992 7
                return ['name' => 'double precision'];
993 7
            case static::PHINX_TYPE_STRING:
994
                return ['name' => 'character varying', 'limit' => 255];
995
            case static::PHINX_TYPE_CHAR:
996
                return ['name' => 'character', 'limit' => 255];
997
            case static::PHINX_TYPE_BIG_INTEGER:
998
                return ['name' => 'bigint'];
999
            case static::PHINX_TYPE_FLOAT:
1000
                return ['name' => 'real'];
1001
            case static::PHINX_TYPE_DATETIME:
1002
                return ['name' => 'timestamp'];
1003 3
            case static::PHINX_TYPE_BINARYUUID:
1004
                return ['name' => 'uuid'];
1005 3
            case static::PHINX_TYPE_BLOB:
1006 3
            case static::PHINX_TYPE_BINARY:
1007 3
                return ['name' => 'bytea'];
1008 3
            case static::PHINX_TYPE_INTERVAL:
1009
                return ['name' => 'interval'];
1010
            // Geospatial database types
1011 3
            // Spatial storage in Postgres is done via the PostGIS extension,
1012
            // which enables the use of the "geography" type in combination
1013
            // with SRID 4326.
1014 3
            case static::PHINX_TYPE_GEOMETRY:
1015
                return ['name' => 'geography', 'type' => 'geometry', 'srid' => 4326];
1016
            case static::PHINX_TYPE_POINT:
1017
                return ['name' => 'geography', 'type' => 'point', 'srid' => 4326];
1018
            case static::PHINX_TYPE_LINESTRING:
1019
                return ['name' => 'geography', 'type' => 'linestring', 'srid' => 4326];
1020 68
            case static::PHINX_TYPE_POLYGON:
1021
                return ['name' => 'geography', 'type' => 'polygon', 'srid' => 4326];
1022
            default:
1023 68
                if ($this->isArrayType($type)) {
1024 67
                    return ['name' => $type];
1025 67
                }
1026
                // Return array type
1027 68
                throw new UnsupportedColumnTypeException('Column type "' . $type . '" is not supported by Postgresql.');
1028
        }
1029 68
    }
1030 68
1031
    /**
1032
     * Returns Phinx type by SQL type
1033
     *
1034
     * @param string $sqlType SQL type
1035
     *
1036
     * @throws \Phinx\Db\Adapter\UnsupportedColumnTypeException
1037
     *
1038 68
     * @return string Phinx type
1039
     */
1040 68
    public function getPhinxType($sqlType)
1041 68
    {
1042 68
        switch ($sqlType) {
1043
            case 'character varying':
1044
            case 'varchar':
1045
                return static::PHINX_TYPE_STRING;
1046
            case 'character':
1047
            case 'char':
1048
                return static::PHINX_TYPE_CHAR;
1049
            case 'text':
1050 68
                return static::PHINX_TYPE_TEXT;
1051
            case 'json':
1052 68
                return static::PHINX_TYPE_JSON;
1053
            case 'jsonb':
1054
                return static::PHINX_TYPE_JSONB;
1055 68
            case 'smallint':
1056
                return static::PHINX_TYPE_SMALL_INTEGER;
1057 68
            case 'int':
1058 68
            case 'int4':
1059 68
            case 'integer':
1060
                return static::PHINX_TYPE_INTEGER;
1061
            case 'decimal':
1062
            case 'numeric':
1063
                return static::PHINX_TYPE_DECIMAL;
1064
            case 'bigint':
1065
            case 'int8':
1066
                return static::PHINX_TYPE_BIG_INTEGER;
1067
            case 'real':
1068 68
            case 'float4':
1069
                return static::PHINX_TYPE_FLOAT;
1070 68
            case 'double precision':
1071 68
                return static::PHINX_TYPE_DOUBLE;
1072 68
            case 'bytea':
1073
                return static::PHINX_TYPE_BINARY;
1074
            case 'interval':
1075
                return static::PHINX_TYPE_INTERVAL;
1076
            case 'time':
1077
            case 'timetz':
1078
            case 'time with time zone':
1079 68
            case 'time without time zone':
1080
                return static::PHINX_TYPE_TIME;
1081 68
            case 'date':
1082 68
                return static::PHINX_TYPE_DATE;
1083 68
            case 'timestamp':
1084 68
            case 'timestamptz':
1085
            case 'timestamp with time zone':
1086
            case 'timestamp without time zone':
1087
                return static::PHINX_TYPE_DATETIME;
1088
            case 'bool':
1089
            case 'boolean':
1090
                return static::PHINX_TYPE_BOOLEAN;
1091 68
            case 'uuid':
1092
                return static::PHINX_TYPE_UUID;
1093
            case 'cidr':
1094
                return static::PHINX_TYPE_CIDR;
1095 68
            case 'inet':
1096 68
                return static::PHINX_TYPE_INET;
1097 68
            case 'macaddr':
1098 68
                return static::PHINX_TYPE_MACADDR;
1099 68
            default:
1100 68
                throw new UnsupportedColumnTypeException('Column type "' . $sqlType . '" is not supported by Postgresql.');
1101 68
        }
1102
    }
1103
1104
    /**
1105
     * @inheritDoc
1106
     */
1107 73
    public function createDatabase($name, $options = [])
1108
    {
1109 73
        $charset = $options['charset'] ?? 'utf8';
1110
        $this->execute(sprintf("CREATE DATABASE %s WITH ENCODING = '%s'", $name, $charset));
1111
    }
1112
1113
    /**
1114
     * @inheritDoc
1115 73
     */
1116
    public function hasDatabase($name)
1117
    {
1118 73
        $sql = sprintf("SELECT count(*) FROM pg_database WHERE datname = '%s'", $name);
1119
        $result = $this->fetchRow($sql);
1120
1121
        return $result['count'] > 0;
1122
    }
1123
1124
    /**
1125
     * @inheritDoc
1126
     */
1127 14
    public function dropDatabase($name)
1128
    {
1129 14
        $this->disconnect();
1130 1
        $this->execute(sprintf('DROP DATABASE IF EXISTS %s', $name));
1131
        $this->createdTables = [];
1132
        $this->connect();
1133 13
    }
1134 13
1135
    /**
1136
     * Get the defintion for a `DEFAULT` statement.
1137
     *
1138
     * @param mixed $default default value
1139
     * @param string|null $columnType column type added
1140
     *
1141
     * @return string
1142 68
     */
1143
    protected function getDefaultValueDefinition($default, $columnType = null)
1144 68
    {
1145 68
        if (is_string($default) && $default !== 'CURRENT_TIMESTAMP') {
1146
            $default = $this->getConnection()->quote($default);
1147
        } elseif (is_bool($default)) {
1148
            $default = $this->castToBool($default);
1149
        } elseif ($columnType === static::PHINX_TYPE_BOOLEAN) {
1150
            $default = $this->castToBool((bool)$default);
1151 68
        }
1152
1153 68
        return isset($default) ? 'DEFAULT ' . $default : '';
1154
    }
1155
1156
    /**
1157
     * Gets the PostgreSQL Column Definition for a Column object.
1158
     *
1159
     * @param \Phinx\Db\Table\Column $column Column
1160
     *
1161
     * @return string
1162
     */
1163
    protected function getColumnSqlDefinition(Column $column)
1164
    {
1165
        $buffer = [];
1166
        if ($column->isIdentity()) {
1167
            $buffer[] = $column->getType() === 'biginteger' ? 'BIGSERIAL' : 'SERIAL';
1168
        } elseif ($column->getType() instanceof Literal) {
1169
            $buffer[] = (string)$column->getType();
1170
        } else {
1171
            $sqlType = $this->getSqlType($column->getType(), $column->getLimit());
1172
            $buffer[] = strtoupper($sqlType['name']);
1173
1174
            // integers cant have limits in postgres
1175
            if ($sqlType['name'] === static::PHINX_TYPE_DECIMAL && ($column->getPrecision() || $column->getScale())) {
1176
                $buffer[] = sprintf(
1177
                    '(%s, %s)',
1178
                    $column->getPrecision() ?: $sqlType['precision'],
1179
                    $column->getScale() ?: $sqlType['scale']
1180
                );
1181
            } elseif ($sqlType['name'] === self::PHINX_TYPE_GEOMETRY) {
1182
                // geography type must be written with geometry type and srid, like this: geography(POLYGON,4326)
1183
                $buffer[] = sprintf(
1184
                    '(%s,%s)',
1185
                    strtoupper($sqlType['type']),
1186
                    $column->getSrid() ?: $sqlType['srid']
1187
                );
1188
            } elseif (in_array($sqlType['name'], [self::PHINX_TYPE_TIME, self::PHINX_TYPE_TIMESTAMP], true)) {
1189
                if (is_numeric($column->getPrecision())) {
0 ignored issues
show
introduced by
The condition is_numeric($column->getPrecision()) is always true.
Loading history...
1190
                    $buffer[] = sprintf('(%s)', $column->getPrecision());
1191
                }
1192
1193
                if ($column->isTimezone()) {
1194
                    $buffer[] = strtoupper('with time zone');
1195
                }
1196
            } elseif (
1197
                !in_array($column->getType(), [
1198
                    self::PHINX_TYPE_TINY_INTEGER,
1199
                    self::PHINX_TYPE_SMALL_INTEGER,
1200
                    self::PHINX_TYPE_INTEGER,
1201
                    self::PHINX_TYPE_BIG_INTEGER,
1202
                    self::PHINX_TYPE_BOOLEAN,
1203
                    self::PHINX_TYPE_TEXT,
1204
                    self::PHINX_TYPE_BINARY,
1205
                ], true)
1206
            ) {
1207
                if ($column->getLimit() || isset($sqlType['limit'])) {
1208
                    $buffer[] = sprintf('(%s)', $column->getLimit() ?: $sqlType['limit']);
1209
                }
1210
            }
1211
        }
1212
1213
        $buffer[] = $column->isNull() ? 'NULL' : 'NOT NULL';
1214
1215
        if ($column->getDefault() !== null) {
1216
            $buffer[] = $this->getDefaultValueDefinition($column->getDefault(), $column->getType());
1217
        }
1218
1219
        return implode(' ', $buffer);
1220
    }
1221
1222
    /**
1223
     * Gets the PostgreSQL Column Comment Definition for a column object.
1224
     *
1225
     * @param \Phinx\Db\Table\Column $column Column
1226
     * @param string $tableName Table name
1227
     *
1228
     * @return string
1229
     */
1230
    protected function getColumnCommentSqlDefinition(Column $column, $tableName)
1231
    {
1232
        // passing 'null' is to remove column comment
1233
        $comment = (strcasecmp($column->getComment(), 'NULL') !== 0)
1234
                 ? $this->getConnection()->quote($column->getComment())
1235
                 : 'NULL';
1236
1237
        return sprintf(
1238
            'COMMENT ON COLUMN %s.%s IS %s;',
1239
            $this->quoteTableName($tableName),
1240
            $this->quoteColumnName($column->getName()),
1241
            $comment
1242
        );
1243
    }
1244
1245
    /**
1246
     * Gets the PostgreSQL Index Definition for an Index object.
1247
     *
1248
     * @param \Phinx\Db\Table\Index $index Index
1249
     * @param string $tableName Table name
1250
     *
1251
     * @return string
1252
     */
1253
    protected function getIndexSqlDefinition(Index $index, $tableName)
1254
    {
1255
        $parts = $this->getSchemaName($tableName);
1256
        $columnNames = $index->getColumns();
1257
1258
        if (is_string($index->getName())) {
1259
            $indexName = $index->getName();
1260
        } else {
1261
            $indexName = sprintf('%s_%s', $parts['table'], implode('_', $columnNames));
1262
        }
1263
1264
        $order = $index->getOrder() ?? [];
1265
        $columnNames = array_map(function ($columnName) use ($order) {
1266
            $ret = '"' . $columnName . '"';
1267
            if (isset($order[$columnName])) {
1268
                $ret .= ' ' . $order[$columnName];
1269
            }
1270
1271
            return $ret;
1272
        }, $columnNames);
1273
1274
        $includedColumns = $index->getInclude() ? sprintf('INCLUDE ("%s")', implode('","', $index->getInclude())) : '';
1275
1276
        return sprintf(
1277
            'CREATE %s INDEX %s ON %s (%s) %s;',
1278
            ($index->getType() === Index::UNIQUE ? 'UNIQUE' : ''),
1279
            $this->quoteColumnName($indexName),
1280
            $this->quoteTableName($tableName),
1281
            implode(',', $columnNames),
1282
            $includedColumns
1283
        );
1284
    }
1285
1286
    /**
1287
     * Gets the MySQL Foreign Key Definition for an ForeignKey object.
1288
     *
1289
     * @param \Phinx\Db\Table\ForeignKey $foreignKey Foreign key
1290
     * @param string $tableName Table name
1291
     *
1292
     * @return string
1293
     */
1294
    protected function getForeignKeySqlDefinition(ForeignKey $foreignKey, $tableName)
1295
    {
1296
        $parts = $this->getSchemaName($tableName);
1297
1298
        $constraintName = $foreignKey->getConstraint() ?: ($parts['table'] . '_' . implode('_', $foreignKey->getColumns()) . '_fkey');
1299
        $def = ' CONSTRAINT ' . $this->quoteColumnName($constraintName) .
1300
        ' FOREIGN KEY ("' . implode('", "', $foreignKey->getColumns()) . '")' .
1301
        " REFERENCES {$this->quoteTableName($foreignKey->getReferencedTable()->getName())} (\"" .
1302
        implode('", "', $foreignKey->getReferencedColumns()) . '")';
1303
        if ($foreignKey->getOnDelete()) {
1304
            $def .= " ON DELETE {$foreignKey->getOnDelete()}";
1305
        }
1306
        if ($foreignKey->getOnUpdate()) {
1307
            $def .= " ON UPDATE {$foreignKey->getOnUpdate()}";
1308
        }
1309
1310
        return $def;
1311
    }
1312
1313
    /**
1314
     * @inheritDoc
1315
     */
1316
    public function createSchemaTable()
1317
    {
1318
        // Create the public/custom schema if it doesn't already exist
1319
        if ($this->hasSchema($this->getGlobalSchemaName()) === false) {
1320
            $this->createSchema($this->getGlobalSchemaName());
1321
        }
1322
1323
        $this->setSearchPath();
1324
1325
        parent::createSchemaTable();
1326
    }
1327
1328
    /**
1329
     * @inheritDoc
1330
     */
1331
    public function getVersions()
1332
    {
1333
        $this->setSearchPath();
1334
1335
        return parent::getVersions();
1336
    }
1337
1338
    /**
1339
     * @inheritDoc
1340
     */
1341
    public function getVersionLog()
1342
    {
1343
        $this->setSearchPath();
1344
1345
        return parent::getVersionLog();
1346
    }
1347
1348
    /**
1349
     * Creates the specified schema.
1350
     *
1351
     * @param string $schemaName Schema Name
1352
     *
1353
     * @return void
1354
     */
1355
    public function createSchema($schemaName = 'public')
1356
    {
1357
        // from postgres 9.3 we can use "CREATE SCHEMA IF NOT EXISTS schema_name"
1358
        $sql = sprintf('CREATE SCHEMA IF NOT EXISTS %s', $this->quoteSchemaName($schemaName));
1359
        $this->execute($sql);
1360
    }
1361
1362
    /**
1363
     * Checks to see if a schema exists.
1364
     *
1365
     * @param string $schemaName Schema Name
1366
     *
1367
     * @return bool
1368
     */
1369
    public function hasSchema($schemaName)
1370
    {
1371
        $sql = sprintf(
1372
            'SELECT count(*)
1373
             FROM pg_namespace
1374
             WHERE nspname = %s',
1375
            $this->getConnection()->quote($schemaName)
1376
        );
1377
        $result = $this->fetchRow($sql);
1378
1379
        return $result['count'] > 0;
1380
    }
1381
1382
    /**
1383
     * Drops the specified schema table.
1384
     *
1385
     * @param string $schemaName Schema name
1386
     *
1387
     * @return void
1388
     */
1389
    public function dropSchema($schemaName)
1390
    {
1391
        $sql = sprintf('DROP SCHEMA IF EXISTS %s CASCADE', $this->quoteSchemaName($schemaName));
1392
        $this->execute($sql);
1393
1394
        foreach ($this->createdTables as $idx => $createdTable) {
1395
            if ($this->getSchemaName($createdTable)['schema'] === $this->quoteSchemaName($schemaName)) {
1396
                unset($this->createdTables[$idx]);
1397
            }
1398
        }
1399
    }
1400
1401
    /**
1402
     * Drops all schemas.
1403
     *
1404
     * @return void
1405
     */
1406
    public function dropAllSchemas()
1407
    {
1408
        foreach ($this->getAllSchemas() as $schema) {
1409
            $this->dropSchema($schema);
1410
        }
1411
    }
1412
1413
    /**
1414
     * Returns schemas.
1415
     *
1416
     * @return array
1417
     */
1418
    public function getAllSchemas()
1419
    {
1420
        $sql = "SELECT schema_name
1421
                FROM information_schema.schemata
1422
                WHERE schema_name <> 'information_schema' AND schema_name !~ '^pg_'";
1423
        $items = $this->fetchAll($sql);
1424
        $schemaNames = [];
1425
        foreach ($items as $item) {
1426
            $schemaNames[] = $item['schema_name'];
1427
        }
1428
1429
        return $schemaNames;
1430
    }
1431
1432
    /**
1433
     * @inheritDoc
1434
     */
1435
    public function getColumnTypes()
1436
    {
1437
        return array_merge(parent::getColumnTypes(), static::$specificColumnTypes);
1438
    }
1439
1440
    /**
1441
     * @inheritDoc
1442
     */
1443
    public function isValidColumnType(Column $column)
1444
    {
1445
        // If not a standard column type, maybe it is array type?
1446
        return (parent::isValidColumnType($column) || $this->isArrayType($column->getType()));
1447
    }
1448
1449
    /**
1450
     * Check if the given column is an array of a valid type.
1451
     *
1452
     * @param string $columnType Column type
1453
     *
1454
     * @return bool
1455
     */
1456
    protected function isArrayType($columnType)
1457
    {
1458
        if (!preg_match('/^([a-z]+)(?:\[\]){1,}$/', $columnType, $matches)) {
1459
            return false;
1460
        }
1461
1462
        $baseType = $matches[1];
1463
1464
        return in_array($baseType, $this->getColumnTypes(), true);
1465
    }
1466
1467
    /**
1468
     * @param string $tableName Table name
1469
     *
1470
     * @return array
1471
     */
1472
    protected function getSchemaName($tableName)
1473
    {
1474
        $schema = $this->getGlobalSchemaName();
1475
        $table = $tableName;
1476
        if (strpos($tableName, '.') !== false) {
1477
            [$schema, $table] = explode('.', $tableName);
1478
        }
1479
1480
        return [
1481
            'schema' => $schema,
1482
            'table' => $table,
1483
        ];
1484
    }
1485
1486
    /**
1487
     * Gets the schema name.
1488
     *
1489
     * @return string
1490
     */
1491
    protected function getGlobalSchemaName()
1492
    {
1493
        $options = $this->getOptions();
1494
1495
        return empty($options['schema']) ? 'public' : $options['schema'];
1496
    }
1497
1498
    /**
1499
     * @inheritDoc
1500
     */
1501
    public function castToBool($value)
1502
    {
1503
        return (bool)$value ? 'TRUE' : 'FALSE';
1504
    }
1505
1506
    /**
1507
     * @inheritDoc
1508
     */
1509
    public function getDecoratedConnection()
1510
    {
1511
        $options = $this->getOptions();
1512
        $options = [
1513
            'username' => $options['user'] ?? null,
1514
            'password' => $options['pass'] ?? null,
1515
            'database' => $options['name'],
1516
            'quoteIdentifiers' => true,
1517
        ] + $options;
1518
1519
        $driver = new PostgresDriver($options);
1520
1521
        $driver->setConnection($this->connection);
1522
1523
        return new Connection(['driver' => $driver] + $options);
1524
    }
1525
1526
    /**
1527
     * Sets search path of schemas to look through for a table
1528
     *
1529
     * @return void
1530
     */
1531
    public function setSearchPath()
1532
    {
1533
        $this->execute(
1534
            sprintf(
1535
                'SET search_path TO %s,"$user",public',
1536
                $this->quoteSchemaName($this->getGlobalSchemaName())
1537
            )
1538
        );
1539
    }
1540
}
1541