Passed
Pull Request — master (#1941)
by Vania
02:34
created

PostgresAdapter::getChangeColumnInstructions()   B

Complexity

Conditions 6
Paths 32

Size

Total Lines 69
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 33
CRAP Score 6.0454

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 39
c 1
b 0
f 0
dl 0
loc 69
ccs 33
cts 37
cp 0.8919
rs 8.6737
cc 6
nc 32
nop 3
crap 6.0454

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
544
        $sql = sprintf(
545
            'ALTER COLUMN %s TYPE %s',
546 1
            $this->quoteColumnName($columnName),
547
            $this->getColumnSqlDefinition($newColumn)
548 1
        );
549 1
550 1
        if (in_array($newColumn->getType(), ['smallinteger', 'integer', 'biginteger'], true)) {
551 1
            $sql .= sprintf(
552
                ' USING (%s::bigint)',
553
                $this->quoteColumnName($columnName)
554
            );
555
        }
556
557
        //NULL and DEFAULT cannot be set while changing column type
558
        $sql = preg_replace('/ NOT NULL/', '', $sql);
559
        $sql = preg_replace('/ NULL/', '', $sql);
560 2
        //If it is set, DEFAULT is the last definition
561
        $sql = preg_replace('/DEFAULT .*/', '', $sql);
562 2
563 2
        $instructions->addAlter($sql);
564 2
565
        // process null
566
        $sql = sprintf(
567
            'ALTER COLUMN %s',
568
            $this->quoteColumnName($columnName)
569 1
        );
570
571 1
        if ($newColumn->isNull()) {
572 1
            $sql .= ' DROP NOT NULL';
573 1
        } else {
574
            $sql .= ' SET NOT NULL';
575 1
        }
576 1
577
        $instructions->addAlter($sql);
578 1
579 1
        if ($newColumn->getDefault() !== null) {
580 1
            $instructions->addAlter(sprintf(
581 1
                'ALTER COLUMN %s SET %s',
582 1
                $this->quoteColumnName($columnName),
583 1
                $this->getDefaultValueDefinition($newColumn->getDefault(), $newColumn->getType())
584 1
            ));
585 1
        } else {
586 1
            //drop default
587
            $instructions->addAlter(sprintf(
588 1
                'ALTER COLUMN %s DROP DEFAULT',
589
                $this->quoteColumnName($columnName)
590
            ));
591
        }
592
593
        // rename column
594
        if ($columnName !== $newColumn->getName()) {
595
            $instructions->addPostStep(sprintf(
596 1
                'ALTER TABLE %s RENAME COLUMN %s TO %s',
597
                $this->quoteTableName($tableName),
598 1
                $this->quoteColumnName($columnName),
599 1
                $this->quoteColumnName($newColumn->getName())
600
            ));
601 1
        }
602 1
603 1
        // change column comment if needed
604
        if ($newColumn->getComment()) {
605
            $instructions->addPostStep($this->getColumnCommentSqlDefinition($newColumn, $tableName));
606
        }
607
608 3
        return $instructions;
609
    }
610 3
611 1
    /**
612 1
     * @inheritDoc
613 3
     */
614 3
    protected function getDropColumnInstructions($tableName, $columnName)
615
    {
616
        $alter = sprintf(
617
            'DROP COLUMN %s',
618
            $this->quoteColumnName($columnName)
619
        );
620 3
621 3
        return new AlterInstructions([$alter]);
622 3
    }
623 3
624
    /**
625 1
     * Get an array of indexes from a particular table.
626 1
     *
627
     * @param string $tableName Table name
628
     *
629
     * @return array
630
     */
631
    protected function getIndexes($tableName)
632
    {
633
        $parts = $this->getSchemaName($tableName);
634
635
        $indexes = [];
636 3
        $sql = sprintf(
637
            "SELECT
638 3
                i.relname AS index_name,
639 3
                a.attname AS column_name
640
            FROM
641
                pg_class t,
642
                pg_class i,
643
                pg_index ix,
644
                pg_attribute a,
645
                pg_namespace nsp
646
            WHERE
647
                t.oid = ix.indrelid
648
                AND i.oid = ix.indexrelid
649
                AND a.attrelid = t.oid
650 3
                AND a.attnum = ANY(ix.indkey)
651
                AND t.relnamespace = nsp.oid
652 3
                AND nsp.nspname = %s
653 3
                AND t.relkind = 'r'
654 3
                AND t.relname = %s
655 3
            ORDER BY
656 3
                t.relname,
657 3
                i.relname",
658 3
            $this->getConnection()->quote($parts['schema']),
659 3
            $this->getConnection()->quote($parts['table'])
660
        );
661
        $rows = $this->fetchAll($sql);
662
        foreach ($rows as $row) {
663
            if (!isset($indexes[$row['index_name']])) {
664
                $indexes[$row['index_name']] = ['columns' => []];
665 2
            }
666
            $indexes[$row['index_name']]['columns'][] = $row['column_name'];
667 2
        }
668 2
669 2
        return $indexes;
670 2
    }
671 2
672 2
    /**
673 2
     * @inheritDoc
674
     */
675
    public function hasIndex($tableName, $columns)
676
    {
677
        if (is_string($columns)) {
678 1
            $columns = [$columns];
679
        }
680 1
        $indexes = $this->getIndexes($tableName);
681
        foreach ($indexes as $index) {
682
            if (array_diff($index['columns'], $columns) === array_diff($columns, $index['columns'])) {
683
                return true;
684 1
            }
685 1
        }
686 1
687 1
        return false;
688 1
    }
689
690 1
    /**
691 1
     * @inheritDoc
692 1
     */
693 1
    public function hasIndexByName($tableName, $indexName)
694 1
    {
695
        $indexes = $this->getIndexes($tableName);
696
        foreach ($indexes as $name => $index) {
697
            if ($name === $indexName) {
698
                return true;
699
            }
700
        }
701 1
702 1
        return false;
703
    }
704 1
705
    /**
706 1
     * @inheritDoc
707 1
     */
708 1
    protected function getAddIndexInstructions(Table $table, Index $index)
709 1
    {
710
        $instructions = new AlterInstructions();
711 1
        $instructions->addPostStep($this->getIndexSqlDefinition($index, $table->getName()));
712
713
        return $instructions;
714
    }
715
716 68
    /**
717
     * {@inheritDoc}
718
     *
719 68
     * @throws \InvalidArgumentException
720 14
     */
721
    protected function getDropIndexByColumnsInstructions($tableName, $columns)
722 1
    {
723
        $parts = $this->getSchemaName($tableName);
724 1
725
        if (is_string($columns)) {
726 14
            $columns = [$columns]; // str to array
727 68
        }
728 68
729 68
        $indexes = $this->getIndexes($tableName);
730 68
        foreach ($indexes as $indexName => $index) {
731 68
            $a = array_diff($columns, $index['columns']);
732 68
            if (empty($a)) {
733 68
                return new AlterInstructions([], [sprintf(
734 68
                    'DROP INDEX IF EXISTS %s',
735 68
                    '"' . ($parts['schema'] . '".' . $this->quoteColumnName($indexName))
736 68
                )]);
737 68
            }
738 68
        }
739 2
740 68
        throw new InvalidArgumentException(sprintf(
741 68
            "The specified index on columns '%s' does not exist",
742 68
            implode(',', $columns)
743
        ));
744 68
    }
745 68
746 68
    /**
747 1
     * @inheritDoc
748 68
     */
749 68
    protected function getDropIndexByNameInstructions($tableName, $indexName)
750 68
    {
751 15
        $parts = $this->getSchemaName($tableName);
752 15
753 1
        $sql = sprintf(
754
            'DROP INDEX IF EXISTS %s',
755
            '"' . ($parts['schema'] . '".' . $this->quoteColumnName($indexName))
756
        );
757
758 14
        return new AlterInstructions([], [$sql]);
759
    }
760
761 14
    /**
762
     * @inheritDoc
763
     */
764 14
    public function hasPrimaryKey($tableName, $columns, $constraint = null)
765
    {
766
        $primaryKey = $this->getPrimaryKey($tableName);
767 14
768
        if (empty($primaryKey)) {
769
            return false;
770 14
        }
771 14
772 13
        if ($constraint) {
773
            return ($primaryKey['constraint'] === $constraint);
774
        } else {
775 1
            if (is_string($columns)) {
776 14
                $columns = [$columns]; // str to array
777
            }
778
            $missingColumns = array_diff($columns, $primaryKey['columns']);
779
780
            return empty($missingColumns);
781
        }
782
    }
783
784
    /**
785 10
     * Get the primary key from a particular table.
786
     *
787
     * @param string $tableName Table name
788 10
     *
789 10
     * @return array
790 6
     */
791 10
    public function getPrimaryKey($tableName)
792 10
    {
793
        $parts = $this->getSchemaName($tableName);
794 10
        $rows = $this->fetchAll(sprintf(
795 2
            "SELECT
796 10
                    tc.constraint_name,
797
                    kcu.column_name
798 10
                FROM information_schema.table_constraints AS tc
799
                JOIN information_schema.key_column_usage AS kcu
800 10
                    ON tc.constraint_name = kcu.constraint_name
801
                WHERE constraint_type = 'PRIMARY KEY'
802 1
                    AND tc.table_schema = %s
803
                    AND tc.table_name = %s
804 1
                ORDER BY kcu.position_in_unique_constraint",
805 10
            $this->getConnection()->quote($parts['schema']),
806 10
            $this->getConnection()->quote($parts['table'])
807 10
        ));
808 9
809 5
        $primaryKey = [
810 5
            'columns' => [],
811 3
        ];
812 4
        foreach ($rows as $row) {
813 4
            $primaryKey['constraint'] = $row['constraint_name'];
814 2
            $primaryKey['columns'][] = $row['column_name'];
815 4
        }
816 4
817 2
        return $primaryKey;
818 4
    }
819 1
820
    /**
821 4
     * @inheritDoc
822 4
     */
823 4
    public function hasForeignKey($tableName, $columns, $constraint = null)
824 4
    {
825 3
        if (is_string($columns)) {
826 4
            $columns = [$columns]; // str to array
827 2
        }
828 4
        $foreignKeys = $this->getForeignKeys($tableName);
829 4
        if ($constraint) {
830 4
            if (isset($foreignKeys[$constraint])) {
831 4
                return !empty($foreignKeys[$constraint]);
832 3
            }
833 3
834 3
            return false;
835 3
        }
836 1
837 1
        foreach ($foreignKeys as $key) {
838
            $a = array_diff($columns, $key['columns']);
839
            if (empty($a)) {
840
                return true;
841
            }
842
        }
843
844
        return false;
845
    }
846
847
    /**
848
     * Get an array of foreign keys from a particular table.
849
     *
850
     * @param string $tableName Table name
851
     *
852 1
     * @return array
853
     */
854 1
    protected function getForeignKeys($tableName)
855 1
    {
856 1
        $parts = $this->getSchemaName($tableName);
857
        $foreignKeys = [];
858
        $rows = $this->fetchAll(sprintf(
859
            "SELECT
860
                    tc.constraint_name,
861 2
                    tc.table_name, kcu.column_name,
862
                    ccu.table_name AS referenced_table_name,
863 2
                    ccu.column_name AS referenced_column_name
864 2
                FROM
865 2
                    information_schema.table_constraints AS tc
866
                    JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name
867
                    JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name
868
                WHERE constraint_type = 'FOREIGN KEY' AND tc.table_schema = %s AND tc.table_name = %s
869
                ORDER BY kcu.position_in_unique_constraint",
870
            $this->getConnection()->quote($parts['schema']),
871 1
            $this->getConnection()->quote($parts['table'])
872
        ));
873 1
        foreach ($rows as $row) {
874 1
            $foreignKeys[$row['constraint_name']]['table'] = $row['table_name'];
875 1
            $foreignKeys[$row['constraint_name']]['columns'][] = $row['column_name'];
876 1
            $foreignKeys[$row['constraint_name']]['referenced_table'] = $row['referenced_table_name'];
877
            $foreignKeys[$row['constraint_name']]['referenced_columns'][] = $row['referenced_column_name'];
878
        }
879
880
        return $foreignKeys;
881
    }
882
883
    /**
884 68
     * @inheritDoc
885
     */
886 68
    protected function getAddForeignKeyInstructions(Table $table, ForeignKey $foreignKey)
887 4
    {
888 68
        $alter = sprintf(
889 68
            'ADD %s',
890 68
            $this->getForeignKeySqlDefinition($foreignKey, $table->getName())
891 68
        );
892
893
        return new AlterInstructions([$alter]);
894
    }
895
896
    /**
897
     * @inheritDoc
898
     */
899
    protected function getDropForeignKeyInstructions($tableName, $constraint)
900 68
    {
901
        $alter = sprintf(
902 68
            'DROP CONSTRAINT %s',
903 68
            $this->quoteColumnName($constraint)
904 50
        );
905 50
906 68
        return new AlterInstructions([$alter]);
907 68
    }
908
909 68
    /**
910 1
     * @inheritDoc
911 1
     */
912 1
    protected function getDropForeignKeyByColumnsInstructions($tableName, $columns)
913 1
    {
914 1
        $instructions = new AlterInstructions();
915 68
916
        $parts = $this->getSchemaName($tableName);
917
        $sql = 'SELECT c.CONSTRAINT_NAME
918
                FROM (
919
                    SELECT CONSTRAINT_NAME, array_agg(COLUMN_NAME::varchar) as columns
920
                    FROM information_schema.KEY_COLUMN_USAGE
921
                    WHERE TABLE_SCHEMA = %s
922 68
                    AND TABLE_NAME IS NOT NULL
923 68
                    AND TABLE_NAME = %s
924 68
                    AND POSITION_IN_UNIQUE_CONSTRAINT IS NOT NULL
925 68
                    GROUP BY CONSTRAINT_NAME
926 68
                ) c
927
                WHERE
928
                    ARRAY[%s]::varchar[] <@ c.columns AND
929 68
                    ARRAY[%s]::varchar[] @> c.columns';
930 68
931 68
        $array = [];
932 68
        foreach ($columns as $col) {
933 1
            $array[] = "'$col'";
934 1
        }
935
936
        $rows = $this->fetchAll(sprintf(
937 68
            $sql,
938
            $this->getConnection()->quote($parts['schema']),
939 68
            $this->getConnection()->quote($parts['table']),
940 68
            implode(',', $array),
941 68
            implode(',', $array)
942
        ));
943 68
944
        foreach ($rows as $row) {
945
            $newInstr = $this->getDropForeignKeyInstructions($tableName, $row['constraint_name']);
946
            $instructions->merge($newInstr);
947
        }
948
949
        return $instructions;
950
    }
951
952
    /**
953 6
     * {@inheritDoc}
954
     *
955
     * @throws \Phinx\Db\Adapter\UnsupportedColumnTypeException
956 6
     */
957 6
    public function getSqlType($type, $limit = null)
958 6
    {
959
        switch ($type) {
960 6
            case static::PHINX_TYPE_TEXT:
961 6
            case static::PHINX_TYPE_TIME:
962 6
            case static::PHINX_TYPE_DATE:
963 6
            case static::PHINX_TYPE_BOOLEAN:
964
            case static::PHINX_TYPE_JSON:
965 6
            case static::PHINX_TYPE_JSONB:
966
            case static::PHINX_TYPE_UUID:
967
            case static::PHINX_TYPE_CIDR:
968
            case static::PHINX_TYPE_INET:
969
            case static::PHINX_TYPE_MACADDR:
970
            case static::PHINX_TYPE_TIMESTAMP:
971
            case static::PHINX_TYPE_INTEGER:
972
                return ['name' => $type];
973
            case static::PHINX_TYPE_TINY_INTEGER:
974
                return ['name' => 'smallint'];
975 7
            case static::PHINX_TYPE_SMALL_INTEGER:
976
                return ['name' => 'smallint'];
977 7
            case static::PHINX_TYPE_DECIMAL:
978 3
                return ['name' => $type, 'precision' => 18, 'scale' => 0];
979 3
            case static::PHINX_TYPE_DOUBLE:
980 5
                return ['name' => 'double precision'];
981 5
            case static::PHINX_TYPE_STRING:
982
                return ['name' => 'character varying', 'limit' => 255];
983
            case static::PHINX_TYPE_CHAR:
984 5
                return ['name' => 'character', 'limit' => 255];
985
            case static::PHINX_TYPE_BIG_INTEGER:
986 7
                return ['name' => 'bigint'];
987 7
            case static::PHINX_TYPE_FLOAT:
988 7
                return ['name' => 'real'];
989 7
            case static::PHINX_TYPE_DATETIME:
990 7
                return ['name' => 'timestamp'];
991 7
            case static::PHINX_TYPE_BINARYUUID:
992 7
                return ['name' => 'uuid'];
993 7
            case static::PHINX_TYPE_BLOB:
994
            case static::PHINX_TYPE_BINARY:
995
                return ['name' => 'bytea'];
996
            case static::PHINX_TYPE_INTERVAL:
997
                return ['name' => 'interval'];
998
            // Geospatial database types
999
            // Spatial storage in Postgres is done via the PostGIS extension,
1000
            // which enables the use of the "geography" type in combination
1001
            // with SRID 4326.
1002
            case static::PHINX_TYPE_GEOMETRY:
1003 3
                return ['name' => 'geography', 'type' => 'geometry', 'srid' => 4326];
1004
            case static::PHINX_TYPE_POINT:
1005 3
                return ['name' => 'geography', 'type' => 'point', 'srid' => 4326];
1006 3
            case static::PHINX_TYPE_LINESTRING:
1007 3
                return ['name' => 'geography', 'type' => 'linestring', 'srid' => 4326];
1008 3
            case static::PHINX_TYPE_POLYGON:
1009
                return ['name' => 'geography', 'type' => 'polygon', 'srid' => 4326];
1010
            default:
1011 3
                if ($this->isArrayType($type)) {
1012
                    return ['name' => $type];
1013
                }
1014 3
                // Return array type
1015
                throw new UnsupportedColumnTypeException('Column type "' . $type . '" is not supported by Postgresql.');
1016
        }
1017
    }
1018
1019
    /**
1020 68
     * Returns Phinx type by SQL type
1021
     *
1022
     * @param string $sqlType SQL type
1023 68
     *
1024 67
     * @throws \Phinx\Db\Adapter\UnsupportedColumnTypeException
1025 67
     *
1026
     * @return string Phinx type
1027 68
     */
1028
    public function getPhinxType($sqlType)
1029 68
    {
1030 68
        switch ($sqlType) {
1031
            case 'character varying':
1032
            case 'varchar':
1033
                return static::PHINX_TYPE_STRING;
1034
            case 'character':
1035
            case 'char':
1036
                return static::PHINX_TYPE_CHAR;
1037
            case 'text':
1038 68
                return static::PHINX_TYPE_TEXT;
1039
            case 'json':
1040 68
                return static::PHINX_TYPE_JSON;
1041 68
            case 'jsonb':
1042 68
                return static::PHINX_TYPE_JSONB;
1043
            case 'smallint':
1044
                return static::PHINX_TYPE_SMALL_INTEGER;
1045
            case 'int':
1046
            case 'int4':
1047
            case 'integer':
1048
                return static::PHINX_TYPE_INTEGER;
1049
            case 'decimal':
1050 68
            case 'numeric':
1051
                return static::PHINX_TYPE_DECIMAL;
1052 68
            case 'bigint':
1053
            case 'int8':
1054
                return static::PHINX_TYPE_BIG_INTEGER;
1055 68
            case 'real':
1056
            case 'float4':
1057 68
                return static::PHINX_TYPE_FLOAT;
1058 68
            case 'double precision':
1059 68
                return static::PHINX_TYPE_DOUBLE;
1060
            case 'bytea':
1061
                return static::PHINX_TYPE_BINARY;
1062
            case 'interval':
1063
                return static::PHINX_TYPE_INTERVAL;
1064
            case 'time':
1065
            case 'timetz':
1066
            case 'time with time zone':
1067
            case 'time without time zone':
1068 68
                return static::PHINX_TYPE_TIME;
1069
            case 'date':
1070 68
                return static::PHINX_TYPE_DATE;
1071 68
            case 'timestamp':
1072 68
            case 'timestamptz':
1073
            case 'timestamp with time zone':
1074
            case 'timestamp without time zone':
1075
                return static::PHINX_TYPE_DATETIME;
1076
            case 'bool':
1077
            case 'boolean':
1078
                return static::PHINX_TYPE_BOOLEAN;
1079 68
            case 'uuid':
1080
                return static::PHINX_TYPE_UUID;
1081 68
            case 'cidr':
1082 68
                return static::PHINX_TYPE_CIDR;
1083 68
            case 'inet':
1084 68
                return static::PHINX_TYPE_INET;
1085
            case 'macaddr':
1086
                return static::PHINX_TYPE_MACADDR;
1087
            default:
1088
                throw new UnsupportedColumnTypeException('Column type "' . $sqlType . '" is not supported by Postgresql.');
1089
        }
1090
    }
1091 68
1092
    /**
1093
     * @inheritDoc
1094
     */
1095 68
    public function createDatabase($name, $options = [])
1096 68
    {
1097 68
        $charset = $options['charset'] ?? 'utf8';
1098 68
        $this->execute(sprintf("CREATE DATABASE %s WITH ENCODING = '%s'", $name, $charset));
1099 68
    }
1100 68
1101 68
    /**
1102
     * @inheritDoc
1103
     */
1104
    public function hasDatabase($name)
1105
    {
1106
        $sql = sprintf("SELECT count(*) FROM pg_database WHERE datname = '%s'", $name);
1107 73
        $result = $this->fetchRow($sql);
1108
1109 73
        return $result['count'] > 0;
1110
    }
1111
1112
    /**
1113
     * @inheritDoc
1114
     */
1115 73
    public function dropDatabase($name)
1116
    {
1117
        $this->disconnect();
1118 73
        $this->execute(sprintf('DROP DATABASE IF EXISTS %s', $name));
1119
        $this->createdTables = [];
1120
        $this->connect();
1121
    }
1122
1123
    /**
1124
     * Get the defintion for a `DEFAULT` statement.
1125
     *
1126
     * @param mixed $default default value
1127 14
     * @param string|null $columnType column type added
1128
     *
1129 14
     * @return string
1130 1
     */
1131
    protected function getDefaultValueDefinition($default, $columnType = null)
1132
    {
1133 13
        if (is_string($default) && $default !== 'CURRENT_TIMESTAMP') {
1134 13
            $default = $this->getConnection()->quote($default);
1135
        } elseif (is_bool($default)) {
1136
            $default = $this->castToBool($default);
1137
        } elseif ($columnType === static::PHINX_TYPE_BOOLEAN) {
1138
            $default = $this->castToBool((bool)$default);
1139
        }
1140
1141
        return isset($default) ? 'DEFAULT ' . $default : '';
1142 68
    }
1143
1144 68
    /**
1145 68
     * Gets the PostgreSQL Column Definition for a Column object.
1146
     *
1147
     * @param \Phinx\Db\Table\Column $column Column
1148
     *
1149
     * @return string
1150
     */
1151 68
    protected function getColumnSqlDefinition(Column $column)
1152
    {
1153 68
        $buffer = [];
1154
        if ($column->isIdentity()) {
1155
            $buffer[] = $column->getType() === 'biginteger' ? 'BIGSERIAL' : 'SERIAL';
1156
        } elseif ($column->getType() instanceof Literal) {
1157
            $buffer[] = (string)$column->getType();
1158
        } else {
1159
            $sqlType = $this->getSqlType($column->getType(), $column->getLimit());
1160
            $buffer[] = strtoupper($sqlType['name']);
1161
1162
            // integers cant have limits in postgres
1163
            if ($sqlType['name'] === static::PHINX_TYPE_DECIMAL && ($column->getPrecision() || $column->getScale())) {
1164
                $buffer[] = sprintf(
1165
                    '(%s, %s)',
1166
                    $column->getPrecision() ?: $sqlType['precision'],
1167
                    $column->getScale() ?: $sqlType['scale']
1168
                );
1169
            } elseif ($sqlType['name'] === self::PHINX_TYPE_GEOMETRY) {
1170
                // geography type must be written with geometry type and srid, like this: geography(POLYGON,4326)
1171
                $buffer[] = sprintf(
1172
                    '(%s,%s)',
1173
                    strtoupper($sqlType['type']),
1174
                    $column->getSrid() ?: $sqlType['srid']
1175
                );
1176
            } elseif (in_array($sqlType['name'], [self::PHINX_TYPE_TIME, self::PHINX_TYPE_TIMESTAMP], true)) {
1177
                if (is_numeric($column->getPrecision())) {
0 ignored issues
show
introduced by
The condition is_numeric($column->getPrecision()) is always true.
Loading history...
1178
                    $buffer[] = sprintf('(%s)', $column->getPrecision());
1179
                }
1180
1181
                if ($column->isTimezone()) {
1182
                    $buffer[] = strtoupper('with time zone');
1183
                }
1184
            } elseif (
1185
                !in_array($column->getType(), [
1186
                    self::PHINX_TYPE_TINY_INTEGER,
1187
                    self::PHINX_TYPE_SMALL_INTEGER,
1188
                    self::PHINX_TYPE_INTEGER,
1189
                    self::PHINX_TYPE_BIG_INTEGER,
1190
                    self::PHINX_TYPE_BOOLEAN,
1191
                    self::PHINX_TYPE_TEXT,
1192
                    self::PHINX_TYPE_BINARY,
1193
                ], true)
1194
            ) {
1195
                if ($column->getLimit() || isset($sqlType['limit'])) {
1196
                    $buffer[] = sprintf('(%s)', $column->getLimit() ?: $sqlType['limit']);
1197
                }
1198
            }
1199
        }
1200
1201
        $buffer[] = $column->isNull() ? 'NULL' : 'NOT NULL';
1202
1203
        if ($column->getDefault() !== null) {
1204
            $buffer[] = $this->getDefaultValueDefinition($column->getDefault(), $column->getType());
1205
        }
1206
1207
        return implode(' ', $buffer);
1208
    }
1209
1210
    /**
1211
     * Gets the PostgreSQL Column Comment Definition for a column object.
1212
     *
1213
     * @param \Phinx\Db\Table\Column $column Column
1214
     * @param string $tableName Table name
1215
     *
1216
     * @return string
1217
     */
1218
    protected function getColumnCommentSqlDefinition(Column $column, $tableName)
1219
    {
1220
        // passing 'null' is to remove column comment
1221
        $comment = (strcasecmp($column->getComment(), 'NULL') !== 0)
1222
                 ? $this->getConnection()->quote($column->getComment())
1223
                 : 'NULL';
1224
1225
        return sprintf(
1226
            'COMMENT ON COLUMN %s.%s IS %s;',
1227
            $this->quoteTableName($tableName),
1228
            $this->quoteColumnName($column->getName()),
1229
            $comment
1230
        );
1231
    }
1232
1233
    /**
1234
     * Gets the PostgreSQL Index Definition for an Index object.
1235
     *
1236
     * @param \Phinx\Db\Table\Index $index Index
1237
     * @param string $tableName Table name
1238
     *
1239
     * @return string
1240
     */
1241
    protected function getIndexSqlDefinition(Index $index, $tableName)
1242
    {
1243
        $parts = $this->getSchemaName($tableName);
1244
        $columnNames = $index->getColumns();
1245
1246
        if (is_string($index->getName())) {
1247
            $indexName = $index->getName();
1248
        } else {
1249
            $indexName = sprintf('%s_%s', $parts['table'], implode('_', $columnNames));
1250
        }
1251
1252
        $order = $index->getOrder() ?? [];
1253
        $columnNames = array_map(function ($columnName) use ($order) {
1254
            $ret = '"' . $columnName . '"';
1255
            if (isset($order[$columnName])) {
1256
                $ret .= ' ' . $order[$columnName];
1257
            }
1258
1259
            return $ret;
1260
        }, $columnNames);
1261
1262
        $includedColumns = $index->getInclude() ? sprintf('INCLUDE ("%s")', implode('","', $index->getInclude())) : '';
1263
1264
        return sprintf(
1265
            'CREATE %s INDEX %s ON %s (%s) %s;',
1266
            ($index->getType() === Index::UNIQUE ? 'UNIQUE' : ''),
1267
            $this->quoteColumnName($indexName),
1268
            $this->quoteTableName($tableName),
1269
            implode(',', $columnNames),
1270
            $includedColumns
1271
        );
1272
    }
1273
1274
    /**
1275
     * Gets the MySQL Foreign Key Definition for an ForeignKey object.
1276
     *
1277
     * @param \Phinx\Db\Table\ForeignKey $foreignKey Foreign key
1278
     * @param string $tableName Table name
1279
     *
1280
     * @return string
1281
     */
1282
    protected function getForeignKeySqlDefinition(ForeignKey $foreignKey, $tableName)
1283
    {
1284
        $parts = $this->getSchemaName($tableName);
1285
1286
        $constraintName = $foreignKey->getConstraint() ?: ($parts['table'] . '_' . implode('_', $foreignKey->getColumns()) . '_fkey');
1287
        $def = ' CONSTRAINT ' . $this->quoteColumnName($constraintName) .
1288
        ' FOREIGN KEY ("' . implode('", "', $foreignKey->getColumns()) . '")' .
1289
        " REFERENCES {$this->quoteTableName($foreignKey->getReferencedTable()->getName())} (\"" .
1290
        implode('", "', $foreignKey->getReferencedColumns()) . '")';
1291
        if ($foreignKey->getOnDelete()) {
1292
            $def .= " ON DELETE {$foreignKey->getOnDelete()}";
1293
        }
1294
        if ($foreignKey->getOnUpdate()) {
1295
            $def .= " ON UPDATE {$foreignKey->getOnUpdate()}";
1296
        }
1297
1298
        return $def;
1299
    }
1300
1301
    /**
1302
     * @inheritDoc
1303
     */
1304
    public function createSchemaTable()
1305
    {
1306
        // Create the public/custom schema if it doesn't already exist
1307
        if ($this->hasSchema($this->getGlobalSchemaName()) === false) {
1308
            $this->createSchema($this->getGlobalSchemaName());
1309
        }
1310
1311
        $this->setSearchPath();
1312
1313
        parent::createSchemaTable();
1314
    }
1315
1316
    /**
1317
     * @inheritDoc
1318
     */
1319
    public function getVersions()
1320
    {
1321
        $this->setSearchPath();
1322
1323
        return parent::getVersions();
1324
    }
1325
1326
    /**
1327
     * @inheritDoc
1328
     */
1329
    public function getVersionLog()
1330
    {
1331
        $this->setSearchPath();
1332
1333
        return parent::getVersionLog();
1334
    }
1335
1336
    /**
1337
     * Creates the specified schema.
1338
     *
1339
     * @param string $schemaName Schema Name
1340
     *
1341
     * @return void
1342
     */
1343
    public function createSchema($schemaName = 'public')
1344
    {
1345
        // from postgres 9.3 we can use "CREATE SCHEMA IF NOT EXISTS schema_name"
1346
        $sql = sprintf('CREATE SCHEMA IF NOT EXISTS %s', $this->quoteSchemaName($schemaName));
1347
        $this->execute($sql);
1348
    }
1349
1350
    /**
1351
     * Checks to see if a schema exists.
1352
     *
1353
     * @param string $schemaName Schema Name
1354
     *
1355
     * @return bool
1356
     */
1357
    public function hasSchema($schemaName)
1358
    {
1359
        $sql = sprintf(
1360
            'SELECT count(*)
1361
             FROM pg_namespace
1362
             WHERE nspname = %s',
1363
            $this->getConnection()->quote($schemaName)
1364
        );
1365
        $result = $this->fetchRow($sql);
1366
1367
        return $result['count'] > 0;
1368
    }
1369
1370
    /**
1371
     * Drops the specified schema table.
1372
     *
1373
     * @param string $schemaName Schema name
1374
     *
1375
     * @return void
1376
     */
1377
    public function dropSchema($schemaName)
1378
    {
1379
        $sql = sprintf('DROP SCHEMA IF EXISTS %s CASCADE', $this->quoteSchemaName($schemaName));
1380
        $this->execute($sql);
1381
1382
        foreach ($this->createdTables as $idx => $createdTable) {
1383
            if ($this->getSchemaName($createdTable)['schema'] === $this->quoteSchemaName($schemaName)) {
1384
                unset($this->createdTables[$idx]);
1385
            }
1386
        }
1387
    }
1388
1389
    /**
1390
     * Drops all schemas.
1391
     *
1392
     * @return void
1393
     */
1394
    public function dropAllSchemas()
1395
    {
1396
        foreach ($this->getAllSchemas() as $schema) {
1397
            $this->dropSchema($schema);
1398
        }
1399
    }
1400
1401
    /**
1402
     * Returns schemas.
1403
     *
1404
     * @return array
1405
     */
1406
    public function getAllSchemas()
1407
    {
1408
        $sql = "SELECT schema_name
1409
                FROM information_schema.schemata
1410
                WHERE schema_name <> 'information_schema' AND schema_name !~ '^pg_'";
1411
        $items = $this->fetchAll($sql);
1412
        $schemaNames = [];
1413
        foreach ($items as $item) {
1414
            $schemaNames[] = $item['schema_name'];
1415
        }
1416
1417
        return $schemaNames;
1418
    }
1419
1420
    /**
1421
     * @inheritDoc
1422
     */
1423
    public function getColumnTypes()
1424
    {
1425
        return array_merge(parent::getColumnTypes(), static::$specificColumnTypes);
1426
    }
1427
1428
    /**
1429
     * @inheritDoc
1430
     */
1431
    public function isValidColumnType(Column $column)
1432
    {
1433
        // If not a standard column type, maybe it is array type?
1434
        return (parent::isValidColumnType($column) || $this->isArrayType($column->getType()));
1435
    }
1436
1437
    /**
1438
     * Check if the given column is an array of a valid type.
1439
     *
1440
     * @param string $columnType Column type
1441
     *
1442
     * @return bool
1443
     */
1444
    protected function isArrayType($columnType)
1445
    {
1446
        if (!preg_match('/^([a-z]+)(?:\[\]){1,}$/', $columnType, $matches)) {
1447
            return false;
1448
        }
1449
1450
        $baseType = $matches[1];
1451
1452
        return in_array($baseType, $this->getColumnTypes(), true);
1453
    }
1454
1455
    /**
1456
     * @param string $tableName Table name
1457
     *
1458
     * @return array
1459
     */
1460
    protected function getSchemaName($tableName)
1461
    {
1462
        $schema = $this->getGlobalSchemaName();
1463
        $table = $tableName;
1464
        if (strpos($tableName, '.') !== false) {
1465
            [$schema, $table] = explode('.', $tableName);
1466
        }
1467
1468
        return [
1469
            'schema' => $schema,
1470
            'table' => $table,
1471
        ];
1472
    }
1473
1474
    /**
1475
     * Gets the schema name.
1476
     *
1477
     * @return string
1478
     */
1479
    protected function getGlobalSchemaName()
1480
    {
1481
        $options = $this->getOptions();
1482
1483
        return empty($options['schema']) ? 'public' : $options['schema'];
1484
    }
1485
1486
    /**
1487
     * @inheritDoc
1488
     */
1489
    public function castToBool($value)
1490
    {
1491
        return (bool)$value ? 'TRUE' : 'FALSE';
1492
    }
1493
1494
    /**
1495
     * @inheritDoc
1496
     */
1497
    public function getDecoratedConnection()
1498
    {
1499
        $options = $this->getOptions();
1500
        $options = [
1501
            'username' => $options['user'] ?? null,
1502
            'password' => $options['pass'] ?? null,
1503
            'database' => $options['name'],
1504
            'quoteIdentifiers' => true,
1505
        ] + $options;
1506
1507
        $driver = new PostgresDriver($options);
1508
1509
        $driver->setConnection($this->connection);
1510
1511
        return new Connection(['driver' => $driver] + $options);
1512
    }
1513
1514
    /**
1515
     * Sets search path of schemas to look through for a table
1516
     *
1517
     * @return void
1518
     */
1519
    public function setSearchPath()
1520
    {
1521
        $this->execute(
1522
            sprintf(
1523
                'SET search_path TO %s,"$user",public',
1524
                $this->quoteSchemaName($this->getGlobalSchemaName())
1525
            )
1526
        );
1527
    }
1528
}
1529