Completed
Push — master ( ad056c...acdd85 )
by mark
18s queued 14s
created

PostgresAdapter::getIndexSqlDefinition()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 37
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

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