Passed
Pull Request — master (#1928)
by Corey
03:06
created

PostgresAdapter::hasForeignKey()   A

Complexity

Conditions 6
Paths 10

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 6

Importance

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