Completed
Pull Request — master (#1193)
by Dmitriy
05:13
created

PostgresAdapter::renameColumn()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 21
cts 21
cp 1
rs 8.9713
c 0
b 0
f 0
cc 2
eloc 16
nc 2
nop 3
crap 2
1
<?php
2
/**
3
 * Phinx
4
 *
5
 * (The MIT license)
6
 * Copyright (c) 2015 Rob Morgan
7
 *
8
 * Permission is hereby granted, free of charge, to any person obtaining a copy
9
 * of this software and associated * documentation files (the "Software"), to
10
 * deal in the Software without restriction, including without limitation the
11
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
12
 * sell copies of the Software, and to permit persons to whom the Software is
13
 * furnished to do so, subject to the following conditions:
14
 *
15
 * The above copyright notice and this permission notice shall be included in
16
 * all copies or substantial portions of the Software.
17
 *
18
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24
 * IN THE SOFTWARE.
25
 *
26
 * @package    Phinx
27
 * @subpackage Phinx\Db\Adapter
28
 */
29
namespace Phinx\Db\Adapter;
30
31
use Phinx\Db\Table;
32
use Phinx\Db\Table\Column;
33
use Phinx\Db\Table\ForeignKey;
34
use Phinx\Db\Table\Index;
35
use Phinx\Util\Literal;
36
37
class PostgresAdapter extends PdoAdapter implements AdapterInterface
38
{
39
    const INT_SMALL = 65535;
40
41
    /**
42
     * Columns with comments
43
     *
44
     * @var array
45
     */
46
    protected $columnsWithComments = [];
47
48
    /**
49
     * {@inheritdoc}
50 68
     */
51
    public function connect()
52 68
    {
53 68
        if ($this->connection === null) {
54
            if (!class_exists('PDO') || !in_array('pgsql', \PDO::getAvailableDrivers(), true)) {
55
                // @codeCoverageIgnoreStart
56
                throw new \RuntimeException('You need to enable the PDO_Pgsql extension for Phinx to run properly.');
57
                // @codeCoverageIgnoreEnd
58
            }
59 68
60 68
            $db = null;
61
            $options = $this->getOptions();
62
63 68
            // if port is specified use it, otherwise use the PostgreSQL default
64 68 View Code Duplication
            if (isset($options['port'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
65 68
                $dsn = 'pgsql:host=' . $options['host'] . ';port=' . $options['port'] . ';dbname=' . $options['name'];
66 1
            } else {
67
                $dsn = 'pgsql:host=' . $options['host'] . ';dbname=' . $options['name'];
68
            }
69
70 68
            try {
71 68
                $db = new \PDO($dsn, $options['user'], $options['pass'], [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]);
72 1
            } catch (\PDOException $exception) {
73 1
                throw new \InvalidArgumentException(sprintf(
74 1
                    'There was a problem connecting to the database: %s',
75 1
                    $exception->getMessage()
76
                ), $exception->getCode(), $exception);
77
            }
78 68
79 68
            try {
80 68
                if (isset($options['schema'])) {
81
                    $db->exec('SET search_path TO ' . $options['schema']);
82
                }
83
            } catch (\PDOException $exception) {
84
                throw new \InvalidArgumentException(
85 68
                    sprintf('Schema does not exists: %s', $options['schema']),
86
                    $exception->getCode(),
87 68
                    $exception
88 68
                );
89
            }
90
91
            $this->setConnection($db);
92
        }
93
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98
    public function disconnect()
99
    {
100
        $this->connection = null;
101
    }
102
103
    /**
104
     * {@inheritdoc}
105
     */
106
    public function hasTransactions()
107
    {
108
        return true;
109
    }
110
111
    /**
112
     * {@inheritdoc}
113
     */
114
    public function beginTransaction()
115
    {
116
        $this->execute('BEGIN');
117
    }
118
119
    /**
120
     * {@inheritdoc}
121
     */
122
    public function commitTransaction()
123
    {
124
        $this->execute('COMMIT');
125
    }
126
127
    /**
128 68
     * {@inheritdoc}
129
     */
130 68
    public function rollbackTransaction()
131
    {
132
        $this->execute('ROLLBACK');
133
    }
134
135
    /**
136 68
     * Quotes a schema name for use in a query.
137
     *
138 68
     * @param string $schemaName Schema Name
139
     * @return string
140
     */
141
    public function quoteSchemaName($schemaName)
142
    {
143
        return $this->quoteColumnName($schemaName);
144 68
    }
145
146 68
    /**
147
     * {@inheritdoc}
148
     */
149
    public function quoteTableName($tableName)
150
    {
151
        $parts = $this->getSchemaName($tableName);
152 68
153
        return $this->quoteSchemaName($parts['schema']) . '.' . $this->quoteColumnName($parts['table']);
154 68
    }
155 68
156
    /**
157
     * {@inheritdoc}
158
     */
159 68
    public function quoteColumnName($columnName)
160 68
    {
161 68
        return '"' . $columnName . '"';
162 68
    }
163 68
164
    /**
165 68
     * {@inheritdoc}
166
     */
167
    public function hasTable($tableName)
168
    {
169
        $parts = $this->getSchemaName($tableName);
170
        $result = $this->getConnection()->query(
171 68
            sprintf(
172
                'SELECT *
173 68
                FROM information_schema.tables
174
                WHERE table_schema = %s
175
                AND table_name = %s',
176 68
                $this->getConnection()->quote($parts['schema']),
177 68
                $this->getConnection()->quote($parts['table'])
178 48
            )
179 48
        );
180 48
181 48
        return $result->rowCount() === 1;
182
    }
183 48
184 48
    /**
185 68
     * {@inheritdoc}
186
     */
187 2
    public function createTable(Table $table)
188 2
    {
189 2
        $options = $table->getOptions();
190 2
        $parts = $this->getSchemaName($table->getName());
191
192 2
         // Add the default primary key
193 2
        $columns = $table->getPendingColumns();
194 2 View Code Duplication
        if (!isset($options['id']) || (isset($options['id']) && $options['id'] === true)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
195
            $column = new Column();
196
            $column->setName('id')
197 68
                   ->setType('integer')
198 68
                   ->setIdentity(true);
199
200 68
            array_unshift($columns, $column);
201 68
            $options['primary_key'] = 'id';
202 68
        } elseif (isset($options['id']) && is_string($options['id'])) {
203
            // Handle id => "field_name" to support AUTO_INCREMENT
204
            $column = new Column();
205 68
            $column->setName($options['id'])
206 6
                   ->setType('integer')
207 6
                   ->setIdentity(true);
208 68
209
            array_unshift($columns, $column);
210
            $options['primary_key'] = $options['id'];
211 68
        }
212 68
213 68
        // TODO - process table options like collation etc
214 68
        $sql = 'CREATE TABLE ';
215 68
        $sql .= $this->quoteTableName($table->getName()) . ' (';
216 68
217
        $this->columnsWithComments = [];
218 View Code Duplication
        foreach ($columns as $column) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
219 1
            $sql .= $this->quoteColumnName($column->getName()) . ' ' . $this->getColumnSqlDefinition($column) . ', ';
220 1
221 1
            // set column comments, if needed
222 1
            if ($column->getComment()) {
223 1
                $this->columnsWithComments[] = $column;
224 1
            }
225 1
        }
226 1
227 1
         // set the primary key(s)
228 1 View Code Duplication
        if (isset($options['primary_key'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
229 68
            $sql = rtrim($sql);
230 68
            $sql .= sprintf(' CONSTRAINT %s PRIMARY KEY (', $this->quoteColumnName($parts['table'] . '_pkey'));
231 2
            if (is_string($options['primary_key'])) { // handle primary_key => 'id'
232
                $sql .= $this->quoteColumnName($options['primary_key']);
233
            } elseif (is_array($options['primary_key'])) { // handle primary_key => array('tag_id', 'resource_id')
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
234
                $sql .= implode(',', array_map([$this, 'quoteColumnName'], $options['primary_key']));
235 68
            }
236 68
            $sql .= ')';
237 1
        } else {
238 1
            $sql = rtrim($sql, ', '); // no primary keys
239 1
        }
240 1
241
        // set the foreign keys
242 68
        $foreignKeys = $table->getForeignKeys();
243
        if (!empty($foreignKeys)) {
244
            foreach ($foreignKeys as $foreignKey) {
245 68
                $sql .= ', ' . $this->getForeignKeySqlDefinition($foreignKey, $table->getName());
246 6
            }
247 6
        }
248 6
249 6
        $sql .= ');';
250
251
        // process column comments
252
        if (!empty($this->columnsWithComments)) {
253 68
            foreach ($this->columnsWithComments as $column) {
254 68
                $sql .= $this->getColumnCommentSqlDefinition($column, $table->getName());
255 5
            }
256 5
        }
257 5
258 5
        // set the indexes
259
        $indexes = $table->getIndexes();
260
        if (!empty($indexes)) {
261 68
            foreach ($indexes as $index) {
262
                $sql .= $this->getIndexSqlDefinition($index, $table->getName());
263
            }
264 68
        }
265 1
266 1
        // execute the sql
267 1
        $this->execute($sql);
268 1
269 1
        // process table comments
270 1
        if (isset($options['comment'])) {
271 1
            $sql = sprintf(
272 68
                'COMMENT ON TABLE %s IS %s',
273
                $this->quoteTableName($table->getName()),
274
                $this->getConnection()->quote($options['comment'])
275
            );
276
            $this->execute($sql);
277 1
        }
278
    }
279 1
280 1
    /**
281 1
     * {@inheritdoc}
282 1
     */
283 1
    public function renameTable($tableName, $newTableName)
284 1
    {
285 1
        $sql = sprintf(
286
            'ALTER TABLE %s RENAME TO %s',
287
            $this->quoteTableName($tableName),
288
            $this->quoteColumnName($newTableName)
289
        );
290 1
        $this->execute($sql);
291
    }
292 1
293 1
    /**
294
     * {@inheritdoc}
295
     */
296
    public function dropTable($tableName)
297
    {
298 1
        $this->execute(sprintf('DROP TABLE %s', $this->quoteTableName($tableName)));
299
    }
300 1
301 1
    /**
302 1
     * {@inheritdoc}
303 1
     */
304
    public function truncateTable($tableName)
305 1
    {
306 1
        $sql = sprintf(
307
            'TRUNCATE TABLE %s',
308
            $this->quoteTableName($tableName)
309
        );
310
311 9
        $this->execute($sql);
312
    }
313 9
314 9
    /**
315
     * {@inheritdoc}
316
     */
317
    public function getColumns($tableName)
318 9
    {
319
        $parts = $this->getSchemaName($tableName);
320 9
        $columns = [];
321 9
        $sql = sprintf(
322
            "SELECT column_name, data_type, udt_name, is_identity, is_nullable,
323 9
             column_default, character_maximum_length, numeric_precision, numeric_scale,
324 9
             datetime_precision
325 9
             FROM information_schema.columns
326 9
             WHERE table_schema = %s AND table_name = %s",
327 9
            $this->getConnection()->quote($parts['schema']),
328 9
            $this->getConnection()->quote($parts['table'])
329 9
        );
330 9
        $columnsInfo = $this->fetchAll($sql);
331 9
332
        foreach ($columnsInfo as $columnInfo) {
333 9
            $isUserDefined = strtoupper(trim($columnInfo['data_type'])) === 'USER-DEFINED';
334 1
335 1
            if ($isUserDefined) {
336
                $columnType = Literal::from($columnInfo['udt_name']);
337 9
            } else {
338 5
                $columnType = $this->getPhinxType($columnInfo['data_type']);
339 5
            }
340 9
341 9
            // If the default value begins with a ' or looks like a function mark it as literal
342 9
            if (isset($columnInfo['column_default'][0]) && $columnInfo['column_default'][0] === "'") {
343
                if (preg_match('/^\'(.*)\'::[^:]+$/', $columnInfo['column_default'], $match)) {
344
                    // '' and \' are replaced with a single '
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
345
                    $columnDefault = preg_replace('/[\'\\\\]\'/', "'", $match[1]);
346
                } else {
347
                    $columnDefault = Literal::from($columnInfo['column_default']);
348 24
                }
349
            } elseif (preg_match('/^\D[a-z_\d]*\(.*\)$/', $columnInfo['column_default'])) {
350 24
                $columnDefault = Literal::from($columnInfo['column_default']);
351
            } else {
352
                $columnDefault = $columnInfo['column_default'];
353 24
            }
354 24
355 24
            $column = new Column();
356
            $column->setName($columnInfo['column_name'])
357 24
                   ->setType($columnType)
358
                   ->setNull($columnInfo['is_nullable'] === 'YES')
359 24
                   ->setDefault($columnDefault)
360 24
                   ->setIdentity($columnInfo['is_identity'] === 'YES')
361
                   ->setScale($columnInfo['numeric_scale']);
362
363
            if (preg_match('/\bwith time zone$/', $columnInfo['data_type'])) {
364
                $column->setTimezone(true);
365
            }
366 18
367
            if (isset($columnInfo['character_maximum_length'])) {
368 18
                $column->setLimit($columnInfo['character_maximum_length']);
369 18
            }
370 18
371 18
            if (in_array($columnType, [static::PHINX_TYPE_TIME, static::PHINX_TYPE_DATETIME])) {
372 18
                $column->setPrecision($columnInfo['datetime_precision']);
373 18
            } else {
374
                $column->setPrecision($columnInfo['numeric_precision']);
375 18
            }
376 18
377
            $columns[] = $column;
378
        }
379
380
        return $columns;
381 3
    }
382
383 3
    /**
384
     * {@inheritdoc}
385
     */
386 3
    public function hasColumn($tableName, $columnName)
387 3
    {
388
        $parts = $this->getSchemaName($tableName);
389 3
        $sql = sprintf(
390 3
            "SELECT count(*)
391 3
            FROM information_schema.columns
392 1
            WHERE table_schema = %s AND table_name = %s AND column_name = %s",
393
            $this->getConnection()->quote($parts['schema']),
394 2
            $this->getConnection()->quote($parts['table']),
395 2
            $this->getConnection()->quote($columnName)
396 2
        );
397 2
398 2
        $result = $this->fetchRow($sql);
399 2
400 2
        return $result['count'] > 0;
401 2
    }
402 2
403
    /**
404
     * {@inheritdoc}
405
     */
406 View Code Duplication
    public function addColumn(Table $table, Column $column)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
407 5
    {
408
        $sql = sprintf(
409
            'ALTER TABLE %s ADD %s %s;',
410
            $this->quoteTableName($table->getName()),
411 5
            $this->quoteColumnName($column->getName()),
412 5
            $this->getColumnSqlDefinition($column)
413 5
        );
414 5
415 5
        if ($column->getComment()) {
416 5
            $sql .= $this->getColumnCommentSqlDefinition($column, $table->getName());
417
        }
418 5
419 5
        $this->execute($sql);
420
    }
421 5
422 5
    /**
423
     * {@inheritdoc}
424 5
     */
425 5
    public function renameColumn($tableName, $columnName, $newColumnName)
426 5
    {
427 5
        $parts = $this->getSchemaName($tableName);
428 5
        $sql = sprintf(
429 5
            "SELECT CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END AS column_exists
430 2
             FROM information_schema.columns
431 2
             WHERE table_schema = %s AND table_name = %s AND column_name = %s",
432 4
            $this->getConnection()->quote($parts['schema']),
433
            $this->getConnection()->quote($parts['table']),
434 5
            $this->getConnection()->quote($columnName)
435 5
        );
436
        $result = $this->fetchRow($sql);
437 1
        if (!(bool)$result['column_exists']) {
438 1
            throw new \InvalidArgumentException("The specified column does not exist: $columnName");
439 1
        }
440 1
        $this->execute(
441 1
            sprintf(
442 1
                'ALTER TABLE %s RENAME COLUMN %s TO %s',
443 1
                $this->quoteTableName($tableName),
444 1
                $this->quoteColumnName($columnName),
445 1
                $this->quoteColumnName($newColumnName)
446
            )
447 4
        );
448 4
    }
449 4
450 4
    /**
451 4
     * {@inheritdoc}
452 4
     */
453 4
    public function changeColumn($tableName, $columnName, Column $newColumn)
454
    {
455
        // TODO - is it possible to merge these 3 queries into less?
456 5
        // change data type
457 1
        $sql = sprintf(
458 1
            'ALTER TABLE %s ALTER COLUMN %s TYPE %s',
459 1
            $this->quoteTableName($tableName),
460 1
            $this->quoteColumnName($columnName),
461 1
            $this->getColumnSqlDefinition($newColumn)
462 1
        );
463 1
        //NULL and DEFAULT cannot be set while changing column type
464 1
        $sql = preg_replace('/ NOT NULL/', '', $sql);
465 1
        $sql = preg_replace('/ NULL/', '', $sql);
466
        //If it is set, DEFAULT is the last definition
467
        $sql = preg_replace('/DEFAULT .*/', '', $sql);
468 5
        $this->execute($sql);
469 2
        // process null
470 2
        $sql = sprintf(
471 2
            'ALTER TABLE %s ALTER COLUMN %s',
472 5
            $this->quoteTableName($tableName),
473
            $this->quoteColumnName($columnName)
474
        );
475
        if ($newColumn->isNull()) {
476
            $sql .= ' DROP NOT NULL';
477 1
        } else {
478
            $sql .= ' SET NOT NULL';
479 1
        }
480 1
        $this->execute($sql);
481 1
        if (!is_null($newColumn->getDefault())) {
482 1
            //change default
483 1
            $this->execute(
484 1
                sprintf(
485 1
                    'ALTER TABLE %s ALTER COLUMN %s SET %s',
486 1
                    $this->quoteTableName($tableName),
487
                    $this->quoteColumnName($columnName),
488
                    $this->getDefaultValueDefinition($newColumn->getDefault(), $newColumn->getType())
0 ignored issues
show
Bug introduced by
It seems like $newColumn->getType() targeting Phinx\Db\Table\Column::getType() can also be of type object<Phinx\Util\Literal>; however, Phinx\Db\Adapter\Postgre...efaultValueDefinition() does only seem to accept string|null, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
489
                )
490
            );
491
        } else {
492
            //drop default
493
            $this->execute(
494 9
                sprintf(
495
                    'ALTER TABLE %s ALTER COLUMN %s DROP DEFAULT',
496 9
                    $this->quoteTableName($tableName),
497
                    $this->quoteColumnName($columnName)
498
                )
499
            );
500
        }
501
        // rename column
502
        if ($columnName !== $newColumn->getName()) {
503
            $this->execute(
504
                sprintf(
505
                    'ALTER TABLE %s RENAME COLUMN %s TO %s',
506
                    $this->quoteTableName($tableName),
507
                    $this->quoteColumnName($columnName),
508
                    $this->quoteColumnName($newColumn->getName())
509
                )
510
            );
511
        }
512
513
        // change column comment if needed
514 9
        if ($newColumn->getComment()) {
515 9
            $sql = $this->getColumnCommentSqlDefinition($newColumn, $tableName);
516 9
            $this->execute($sql);
517 9
        }
518 9
    }
519 9
520 9
    /**
521 9
     * {@inheritdoc}
522 9
     */
523
    public function dropColumn($tableName, $columnName)
524
    {
525
        $this->execute(
526
            sprintf(
527
                'ALTER TABLE %s DROP COLUMN %s',
528 9
                $this->quoteTableName($tableName),
529
                $this->quoteColumnName($columnName)
530 9
            )
531 4
        );
532 4
    }
533 9
534 9
    /**
535 9
     * Get an array of indexes from a particular table.
536 9
     *
537 9
     * @param string $tableName Table Name
538
     * @return array
539 8
     */
540 8
    protected function getIndexes($tableName)
541
    {
542
        $parts = $this->getSchemaName($tableName);
543
544
        $indexes = [];
545
        $sql = sprintf(
546 1
            "SELECT
547
                i.relname AS index_name,
548 1
                a.attname AS column_name
549 1
            FROM
550 1
                pg_class t,
551 1
                pg_class i,
552
                pg_index ix,
553
                pg_attribute a,
554
                pg_namespace nsp
555
            WHERE
556
                t.oid = ix.indrelid
557
                AND i.oid = ix.indexrelid
558
                AND a.attrelid = t.oid
559
                AND a.attnum = ANY(ix.indkey)
560 2
                AND t.relnamespace = nsp.oid
561
                AND nsp.nspname = %s
562 2
                AND t.relkind = 'r'
563 2
                AND t.relname = %s
564 2
            ORDER BY
565
                t.relname,
566
                i.relname",
567
            $this->getConnection()->quote($parts['schema']),
568
            $this->getConnection()->quote($parts['table'])
569 1
        );
570
        $rows = $this->fetchAll($sql);
571 1 View Code Duplication
        foreach ($rows as $row) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
572 1
            if (!isset($indexes[$row['index_name']])) {
573 1
                $indexes[$row['index_name']] = ['columns' => []];
574
            }
575 1
            $indexes[$row['index_name']]['columns'][] = $row['column_name'];
576 1
        }
577
578 1
        return $indexes;
579 1
    }
580 1
581 1
    /**
582 1
     * {@inheritdoc}
583 1
     */
584 1 View Code Duplication
    public function hasIndex($tableName, $columns)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
585 1
    {
586 1
        if (is_string($columns)) {
587
            $columns = [$columns];
588 1
        }
589
        $indexes = $this->getIndexes($tableName);
590
        foreach ($indexes as $index) {
591
            if (array_diff($index['columns'], $columns) === array_diff($columns, $index['columns'])) {
592
                return true;
593
            }
594
        }
595
596 1
        return false;
597
    }
598 1
599 1
    /**
600
     * {@inheritdoc}
601 1
     */
602 1 View Code Duplication
    public function hasIndexByName($tableName, $indexName)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
603 1
    {
604
        $indexes = $this->getIndexes($tableName);
605
        foreach ($indexes as $name => $index) {
606
            if ($name === $indexName) {
607
                return true;
608 3
            }
609
        }
610 3
611 1
        return false;
612 1
    }
613 3
614 3
    /**
615
     * {@inheritdoc}
616
     */
617
    public function addIndex(Table $table, Index $index)
618
    {
619
        $sql = $this->getIndexSqlDefinition($index, $table->getName());
620 3
        $this->execute($sql);
621 3
    }
622 3
623 3
    /**
624
     * {@inheritdoc}
625 1
     */
626 1
    public function dropIndex($tableName, $columns)
627
    {
628
        $parts = $this->getSchemaName($tableName);
629
630
        if (is_string($columns)) {
631
            $columns = [$columns]; // str to array
632
        }
633
634
        $indexes = $this->getIndexes($tableName);
635
        foreach ($indexes as $indexName => $index) {
636 3
            $a = array_diff($columns, $index['columns']);
637
            if (empty($a)) {
638 3
                $this->execute(
639 3
                    sprintf(
640
                        'DROP INDEX IF EXISTS %s',
641
                        '"' . ($parts['schema'] . '".' . $this->quoteColumnName($indexName))
642
                    )
643
                );
644
645
                return;
646
            }
647
        }
648
    }
649
650 3
    /**
651
     * {@inheritdoc}
652 3
     */
653 3
    public function dropIndexByName($tableName, $indexName)
654 3
    {
655 3
        $parts = $this->getSchemaName($tableName);
656 3
657 3
        $sql = sprintf(
658 3
            'DROP INDEX IF EXISTS %s',
659 3
            '"' . ($parts['schema'] . '".' . $this->quoteColumnName($indexName))
660
        );
661
        $this->execute($sql);
662
    }
663
664
    /**
665 2
     * {@inheritdoc}
666
     */
667 2 View Code Duplication
    public function hasForeignKey($tableName, $columns, $constraint = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
668 2
    {
669 2
        if (is_string($columns)) {
670 2
            $columns = [$columns]; // str to array
671 2
        }
672 2
        $foreignKeys = $this->getForeignKeys($tableName);
673 2
        if ($constraint) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $constraint of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
674
            if (isset($foreignKeys[$constraint])) {
675
                return !empty($foreignKeys[$constraint]);
676
            }
677
678 1
            return false;
679
        } else {
680 1
            foreach ($foreignKeys as $key) {
681
                $a = array_diff($columns, $key['columns']);
682
                if (empty($a)) {
683
                    return true;
684 1
                }
685 1
            }
686 1
687 1
            return false;
688 1
        }
689
    }
690 1
691 1
    /**
692 1
     * Get an array of foreign keys from a particular table.
693 1
     *
694 1
     * @param string $tableName Table Name
695
     * @return array
696
     */
697
    protected function getForeignKeys($tableName)
698
    {
699
        $parts = $this->getSchemaName($tableName);
700
        $foreignKeys = [];
701 1
        $rows = $this->fetchAll(sprintf(
702 1
            "SELECT
703
                    tc.constraint_name,
704 1
                    tc.table_name, kcu.column_name,
705
                    ccu.table_name AS referenced_table_name,
706 1
                    ccu.column_name AS referenced_column_name
707 1
                FROM
708 1
                    information_schema.table_constraints AS tc
709 1
                    JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name
710
                    JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name
711 1
                WHERE constraint_type = 'FOREIGN KEY' AND tc.table_schema = %s AND tc.table_name = %s
712
                ORDER BY kcu.position_in_unique_constraint",
713
            $this->getConnection()->quote($parts['schema']),
714
            $this->getConnection()->quote($parts['table'])
715
        ));
716 68
        foreach ($rows as $row) {
717
            $foreignKeys[$row['constraint_name']]['table'] = $row['table_name'];
718
            $foreignKeys[$row['constraint_name']]['columns'][] = $row['column_name'];
719 68
            $foreignKeys[$row['constraint_name']]['referenced_table'] = $row['referenced_table_name'];
720 14
            $foreignKeys[$row['constraint_name']]['referenced_columns'][] = $row['referenced_column_name'];
721
        }
722 1
723
        return $foreignKeys;
724 1
    }
725
726 14
    /**
727 68
     * {@inheritdoc}
728 68
     */
729 68 View Code Duplication
    public function addForeignKey(Table $table, ForeignKey $foreignKey)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
730 68
    {
731 68
        $sql = sprintf(
732 68
            'ALTER TABLE %s ADD %s',
733 68
            $this->quoteTableName($table->getName()),
734 68
            $this->getForeignKeySqlDefinition($foreignKey, $table->getName())
735 68
        );
736 68
        $this->execute($sql);
737 68
    }
738 68
739 2
    /**
740 68
     * {@inheritdoc}
741 68
     */
742 68
    public function dropForeignKey($tableName, $columns, $constraint = null)
743
    {
744 68
        if (is_string($columns)) {
745 68
            $columns = [$columns]; // str to array
746 68
        }
747 1
748 68
        $parts = $this->getSchemaName($tableName);
749 68
750 68
        if ($constraint) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $constraint of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
751 15
            $this->execute(
752 15
                sprintf(
753 1
                    'ALTER TABLE %s DROP CONSTRAINT %s',
754
                    $this->quoteTableName($tableName),
755
                    $this->quoteColumnName($constraint)
756
                )
757
            );
758 14
        } else {
759
            foreach ($columns as $column) {
760
                $rows = $this->fetchAll(sprintf(
761 14
                    "SELECT CONSTRAINT_NAME
762
                      FROM information_schema.KEY_COLUMN_USAGE
763
                      WHERE TABLE_SCHEMA = %s
764 14
                        AND TABLE_NAME IS NOT NULL
765
                        AND TABLE_NAME = %s
766
                        AND COLUMN_NAME = %s
767 14
                      ORDER BY POSITION_IN_UNIQUE_CONSTRAINT",
768
                    $this->getConnection()->quote($parts['schema']),
769
                    $this->getConnection()->quote($parts['table']),
770 14
                    $this->getConnection()->quote($column)
771 14
                ));
772 13
773
                foreach ($rows as $row) {
774
                    $this->dropForeignKey($tableName, $columns, $row['constraint_name']);
775 1
                }
776 14
            }
777
        }
778
    }
779
780
    /**
781
     * {@inheritdoc}
782
     */
783
    public function getSqlType($type, $limit = null)
784
    {
785 10
        switch ($type) {
786
            case static::PHINX_TYPE_TEXT:
787
            case static::PHINX_TYPE_TIME:
788 10
            case static::PHINX_TYPE_DATE:
789 10
            case static::PHINX_TYPE_BOOLEAN:
790 6
            case static::PHINX_TYPE_JSON:
791 10
            case static::PHINX_TYPE_JSONB:
792 10
            case static::PHINX_TYPE_UUID:
793
            case static::PHINX_TYPE_CIDR:
794 10
            case static::PHINX_TYPE_INET:
795 2
            case static::PHINX_TYPE_MACADDR:
796 10
            case static::PHINX_TYPE_TIMESTAMP:
797
                return ['name' => $type];
798 10
            case static::PHINX_TYPE_INTEGER:
799
                if ($limit && $limit == static::INT_SMALL) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $limit of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
800 10
                    return [
801
                        'name' => 'smallint',
802 1
                        'limit' => static::INT_SMALL
803
                    ];
804 1
                }
805 10
806 10
                return ['name' => $type];
807 10
            case static::PHINX_TYPE_DECIMAL:
808 9
                return ['name' => $type, 'precision' => 18, 'scale' => 0];
809 5
            case static::PHINX_TYPE_STRING:
810 5
                return ['name' => 'character varying', 'limit' => 255];
811 3
            case static::PHINX_TYPE_CHAR:
812 4
                return ['name' => 'character', 'limit' => 255];
813 4
            case static::PHINX_TYPE_BIG_INTEGER:
814 2
                return ['name' => 'bigint'];
815 4
            case static::PHINX_TYPE_FLOAT:
816 4
                return ['name' => 'real'];
817 2
            case static::PHINX_TYPE_DATETIME:
818 4
                return ['name' => 'timestamp'];
819 1
            case static::PHINX_TYPE_BLOB:
820
            case static::PHINX_TYPE_BINARY:
821 4
                return ['name' => 'bytea'];
822 4
            case static::PHINX_TYPE_INTERVAL:
823 4
                return ['name' => 'interval'];
824 4
            // Geospatial database types
825 3
            // Spatial storage in Postgres is done via the PostGIS extension,
826 4
            // which enables the use of the "geography" type in combination
827 2
            // with SRID 4326.
828 4
            case static::PHINX_TYPE_GEOMETRY:
829 4
                return ['name' => 'geography', 'type' => 'geometry', 'srid' => 4326];
830 4
            case static::PHINX_TYPE_POINT:
831 4
                return ['name' => 'geography', 'type' => 'point', 'srid' => 4326];
832 3
            case static::PHINX_TYPE_LINESTRING:
833 3
                return ['name' => 'geography', 'type' => 'linestring', 'srid' => 4326];
834 3
            case static::PHINX_TYPE_POLYGON:
835 3
                return ['name' => 'geography', 'type' => 'polygon', 'srid' => 4326];
836 1
            default:
837 1
                if ($this->isArrayType($type)) {
838
                    return ['name' => $type];
839
                }
840
                // Return array type
841
                throw new \RuntimeException('The type: "' . $type . '" is not supported');
842
        }
843
    }
844
845
    /**
846
     * Returns Phinx type by SQL type
847
     *
848
     * @param string $sqlType SQL type
849
     * @returns string Phinx type
850
     */
851
    public function getPhinxType($sqlType)
852 1
    {
853
        switch ($sqlType) {
854 1
            case 'character varying':
855 1
            case 'varchar':
856 1
                return static::PHINX_TYPE_STRING;
857
            case 'character':
858
            case 'char':
859
                return static::PHINX_TYPE_CHAR;
860
            case 'text':
861 2
                return static::PHINX_TYPE_TEXT;
862
            case 'json':
863 2
                return static::PHINX_TYPE_JSON;
864 2
            case 'jsonb':
865 2
                return static::PHINX_TYPE_JSONB;
866
            case 'smallint':
867
                return [
868
                    'name' => 'smallint',
869
                    'limit' => static::INT_SMALL
870
                ];
871 1
            case 'int':
872
            case 'int4':
873 1
            case 'integer':
874 1
                return static::PHINX_TYPE_INTEGER;
875 1
            case 'decimal':
876 1
            case 'numeric':
877
                return static::PHINX_TYPE_DECIMAL;
878
            case 'bigint':
879
            case 'int8':
880
                return static::PHINX_TYPE_BIG_INTEGER;
881
            case 'real':
882
            case 'float4':
883
                return static::PHINX_TYPE_FLOAT;
884 68
            case 'bytea':
885
                return static::PHINX_TYPE_BINARY;
886 68
            case 'interval':
887 4
                return static::PHINX_TYPE_INTERVAL;
888 68
            case 'time':
889 68
            case 'timetz':
890 68
            case 'time with time zone':
891 68
            case 'time without time zone':
892
                return static::PHINX_TYPE_TIME;
893
            case 'date':
894
                return static::PHINX_TYPE_DATE;
895
            case 'timestamp':
896
            case 'timestamptz':
897
            case 'timestamp with time zone':
898
            case 'timestamp without time zone':
899
                return static::PHINX_TYPE_DATETIME;
900 68
            case 'bool':
901
            case 'boolean':
902 68
                return static::PHINX_TYPE_BOOLEAN;
903 68
            case 'uuid':
904 50
                return static::PHINX_TYPE_UUID;
905 50
            case 'cidr':
906 68
                return static::PHINX_TYPE_CIDR;
907 68
            case 'inet':
908
                return static::PHINX_TYPE_INET;
909 68
            case 'macaddr':
910 1
                return static::PHINX_TYPE_MACADDR;
911 1
            default:
912 1
                throw new \RuntimeException('The PostgreSQL type: "' . $sqlType . '" is not supported');
913 1
        }
914 1
    }
915 68
916
    /**
917
     * {@inheritdoc}
918
     */
919
    public function createDatabase($name, $options = [])
920
    {
921
        $charset = isset($options['charset']) ? $options['charset'] : 'utf8';
922 68
        $this->execute(sprintf("CREATE DATABASE %s WITH ENCODING = '%s'", $name, $charset));
923 68
    }
924 68
925 68
    /**
926 68
     * {@inheritdoc}
927
     */
928
    public function hasDatabase($name)
929 68
    {
930 68
        $sql = sprintf("SELECT count(*) FROM pg_database WHERE datname = '%s'", $name);
931 68
        $result = $this->fetchRow($sql);
932 68
933 1
        return $result['count'] > 0;
934 1
    }
935
936
    /**
937 68
     * {@inheritdoc}
938
     */
939 68
    public function dropDatabase($name)
940 68
    {
941 68
        $this->disconnect();
942
        $this->execute(sprintf('DROP DATABASE IF EXISTS %s', $name));
943 68
        $this->connect();
944
    }
945
946
    /**
947
     * Get the defintion for a `DEFAULT` statement.
948
     *
949
     * @param mixed $default default value
950
     * @param string $columnType column type added
951
     * @return string
952
     */
953 6 View Code Duplication
    protected function getDefaultValueDefinition($default, $columnType = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
954
    {
955
        if (is_string($default) && 'CURRENT_TIMESTAMP' !== $default) {
956 6
            $default = $this->getConnection()->quote($default);
957 6
        } elseif (is_bool($default)) {
958 6
            $default = $this->castToBool($default);
959
        } elseif ($columnType === static::PHINX_TYPE_BOOLEAN) {
960 6
            $default = $this->castToBool((bool)$default);
961 6
        }
962 6
963 6
        return isset($default) ? 'DEFAULT ' . $default : '';
964
    }
965 6
966
    /**
967
     * Gets the PostgreSQL Column Definition for a Column object.
968
     *
969
     * @param \Phinx\Db\Table\Column $column Column
970
     * @return string
971
     */
972
    protected function getColumnSqlDefinition(Column $column)
973
    {
974
        $buffer = [];
975 7
        if ($column->isIdentity()) {
976
            $buffer[] = $column->getType() == 'biginteger' ? 'BIGSERIAL' : 'SERIAL';
977 7
        } elseif ($column->getType() instanceof Literal) {
978 3
            $buffer[] = (string)$column->getType();
979 3
        } else {
980 5
            $sqlType = $this->getSqlType($column->getType(), $column->getLimit());
981 5
            $buffer[] = strtoupper($sqlType['name']);
982
983
            // integers cant have limits in postgres
984 5
            if (static::PHINX_TYPE_DECIMAL === $sqlType['name'] && ($column->getPrecision() || $column->getScale())) {
985
                $buffer[] = sprintf(
986 7
                    '(%s, %s)',
987 7
                    $column->getPrecision() ?: $sqlType['precision'],
988 7
                    $column->getScale() ?: $sqlType['scale']
989 7
                );
990 7
            } elseif (in_array($sqlType['name'], ['geography'])) {
991 7
                // geography type must be written with geometry type and srid, like this: geography(POLYGON,4326)
992 7
                $buffer[] = sprintf(
993 7
                    '(%s,%s)',
994
                    strtoupper($sqlType['type']),
995
                    $sqlType['srid']
996
                );
997
            } elseif (!in_array($sqlType['name'], ['integer', 'smallint', 'bigint', 'boolean'])) {
998
                if ($column->getLimit() || isset($sqlType['limit'])) {
999
                    $buffer[] = sprintf('(%s)', $column->getLimit() ?: $sqlType['limit']);
1000
                }
1001
            }
1002
1003 3
            $timeTypes = [
1004
                'time',
1005 3
                'timestamp',
1006 3
            ];
1007 3
1008 3
            if (in_array($sqlType['name'], $timeTypes) && is_numeric($column->getPrecision())) {
1009
                $buffer[] = sprintf('(%s)', $column->getPrecision());
1010
            }
1011 3
1012
            if (in_array($sqlType['name'], $timeTypes) && $column->isTimezone()) {
1013
                $buffer[] = strtoupper('with time zone');
1014 3
            }
1015
        }
1016
1017
        $buffer[] = $column->isNull() ? 'NULL' : 'NOT NULL';
1018
1019
        if (!is_null($column->getDefault())) {
1020 68
            $buffer[] = $this->getDefaultValueDefinition($column->getDefault(), $column->getType());
0 ignored issues
show
Bug introduced by
It seems like $column->getType() targeting Phinx\Db\Table\Column::getType() can also be of type object<Phinx\Util\Literal>; however, Phinx\Db\Adapter\Postgre...efaultValueDefinition() does only seem to accept string|null, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
1021
        }
1022
1023 68
        return implode(' ', $buffer);
1024 67
    }
1025 67
1026
    /**
1027 68
     * Gets the PostgreSQL Column Comment Definition for a column object.
1028
     *
1029 68
     * @param \Phinx\Db\Table\Column $column Column
1030 68
     * @param string $tableName Table name
1031
     * @return string
1032
     */
1033
    protected function getColumnCommentSqlDefinition(Column $column, $tableName)
1034
    {
1035
        // passing 'null' is to remove column comment
1036
        $comment = (strcasecmp($column->getComment(), 'NULL') !== 0)
1037
                 ? $this->getConnection()->quote($column->getComment())
1038 68
                 : 'NULL';
1039
1040 68
        return sprintf(
1041 68
            'COMMENT ON COLUMN %s.%s IS %s;',
1042 68
            $this->quoteTableName($tableName),
1043
            $this->quoteColumnName($column->getName()),
1044
            $comment
1045
        );
1046
    }
1047
1048
    /**
1049
     * Gets the PostgreSQL Index Definition for an Index object.
1050 68
     *
1051
     * @param \Phinx\Db\Table\Index  $index Index
1052 68
     * @param string $tableName Table name
1053
     * @return string
1054
     */
1055 68
    protected function getIndexSqlDefinition(Index $index, $tableName)
1056
    {
1057 68
        $parts = $this->getSchemaName($tableName);
1058 68
1059 68 View Code Duplication
        if (is_string($index->getName())) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1060
            $indexName = $index->getName();
1061
        } else {
1062
            $columnNames = $index->getColumns();
1063
            $indexName = sprintf('%s_%s', $parts['table'], implode('_', $columnNames));
1064
        }
1065
        $def = sprintf(
1066
            "CREATE %s INDEX %s ON %s (%s);",
1067
            ($index->getType() === Index::UNIQUE ? 'UNIQUE' : ''),
1068 68
            $this->quoteColumnName($indexName),
1069
            $this->quoteTableName($tableName),
1070 68
            implode(',', array_map([$this, 'quoteColumnName'], $index->getColumns()))
1071 68
        );
1072 68
1073
        return $def;
1074
    }
1075
1076
    /**
1077
     * Gets the MySQL Foreign Key Definition for an ForeignKey object.
1078
     *
1079 68
     * @param \Phinx\Db\Table\ForeignKey $foreignKey
1080
     * @param string     $tableName  Table name
1081 68
     * @return string
1082 68
     */
1083 68
    protected function getForeignKeySqlDefinition(ForeignKey $foreignKey, $tableName)
1084 68
    {
1085
        $parts = $this->getSchemaName($tableName);
1086
1087
        $constraintName = $foreignKey->getConstraint() ?: ($parts['table'] . '_' . implode('_', $foreignKey->getColumns()) . '_fkey');
1088
        $def = ' CONSTRAINT ' . $this->quoteColumnName($constraintName)
0 ignored issues
show
Bug introduced by
It seems like $constraintName defined by $foreignKey->getConstrai...getColumns()) . '_fkey' on line 1087 can also be of type boolean; however, Phinx\Db\Adapter\Postgre...pter::quoteColumnName() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
1089
            . ' FOREIGN KEY ("'
1090
            . implode('", "', $foreignKey->getColumns())
1091 68
            . '")'
1092
            . " REFERENCES {$this->quoteTableName($foreignKey->getReferencedTable()->getName())} (\""
1093
            . implode('", "', $foreignKey->getReferencedColumns())
1094
            . '")';
1095 68
        if ($foreignKey->getOnDelete()) {
1096 68
            $def .= " ON DELETE {$foreignKey->getOnDelete()}";
1097 68
        }
1098 68
        if ($foreignKey->getOnUpdate()) {
1099 68
            $def .= " ON UPDATE {$foreignKey->getOnUpdate()}";
1100 68
        }
1101 68
1102
        return $def;
1103
    }
1104
1105
    /**
1106
     * {@inheritdoc}
1107 73
     */
1108
    public function createSchemaTable()
1109 73
    {
1110
        // Create the public/custom schema if it doesn't already exist
1111
        if ($this->hasSchema($this->getGlobalSchemaName()) === false) {
1112
            $this->createSchema($this->getGlobalSchemaName());
1113
        }
1114
1115 73
        $this->fetchAll(sprintf('SET search_path TO %s', $this->getGlobalSchemaName()));
1116
1117
        parent::createSchemaTable();
1118 73
    }
1119
1120
    /**
1121
     * Creates the specified schema.
1122
     *
1123
     * @param  string $schemaName Schema Name
1124
     * @return void
1125
     */
1126
    public function createSchema($schemaName = 'public')
1127 14
    {
1128
        $sql = sprintf('CREATE SCHEMA %s;', $this->quoteSchemaName($schemaName)); // from postgres 9.3 we can use "CREATE SCHEMA IF NOT EXISTS schema_name"
1129 14
        $this->execute($sql);
1130 1
    }
1131
1132
    /**
1133 13
     * Checks to see if a schema exists.
1134 13
     *
1135
     * @param string $schemaName Schema Name
1136
     * @return bool
1137
     */
1138
    public function hasSchema($schemaName)
1139
    {
1140
        $sql = sprintf(
1141
            "SELECT count(*)
1142 68
             FROM pg_namespace
1143
             WHERE nspname = %s",
1144 68
            $this->getConnection()->quote($schemaName)
1145 68
        );
1146
        $result = $this->fetchRow($sql);
1147
1148
        return $result['count'] > 0;
1149
    }
1150
1151 68
    /**
1152
     * Drops the specified schema table.
1153 68
     *
1154
     * @param string $schemaName Schema name
1155
     * @return void
1156
     */
1157
    public function dropSchema($schemaName)
1158
    {
1159
        $sql = sprintf("DROP SCHEMA IF EXISTS %s CASCADE;", $this->quoteSchemaName($schemaName));
1160
        $this->execute($sql);
1161
    }
1162
1163
    /**
1164
     * Drops all schemas.
1165
     *
1166
     * @return void
1167
     */
1168
    public function dropAllSchemas()
1169
    {
1170
        foreach ($this->getAllSchemas() as $schema) {
1171
            $this->dropSchema($schema);
1172
        }
1173
    }
1174
1175
    /**
1176
     * Returns schemas.
1177
     *
1178
     * @return array
1179
     */
1180
    public function getAllSchemas()
1181
    {
1182
        $sql = "SELECT schema_name
1183
                FROM information_schema.schemata
1184
                WHERE schema_name <> 'information_schema' AND schema_name !~ '^pg_'";
1185
        $items = $this->fetchAll($sql);
1186
        $schemaNames = [];
1187
        foreach ($items as $item) {
1188
            $schemaNames[] = $item['schema_name'];
1189
        }
1190
1191
        return $schemaNames;
1192
    }
1193
1194
    /**
1195
     * {@inheritdoc}
1196
     */
1197
    public function getColumnTypes()
1198
    {
1199
        return array_merge(parent::getColumnTypes(), ['json', 'jsonb', 'cidr', 'inet', 'macaddr', 'interval']);
1200
    }
1201
1202
    /**
1203
     * {@inheritdoc}
1204
     */
1205
    public function isValidColumnType(Column $column)
1206
    {
1207
        // If not a standard column type, maybe it is array type?
1208
        return (parent::isValidColumnType($column) || $this->isArrayType($column->getType()));
0 ignored issues
show
Bug introduced by
It seems like $column->getType() targeting Phinx\Db\Table\Column::getType() can also be of type object<Phinx\Util\Literal>; however, Phinx\Db\Adapter\PostgresAdapter::isArrayType() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
1209
    }
1210
1211
    /**
1212
     * Check if the given column is an array of a valid type.
1213
     *
1214
     * @param  string $columnType
1215
     * @return bool
1216
     */
1217
    protected function isArrayType($columnType)
1218
    {
1219
        if (!preg_match('/^([a-z]+)(?:\[\]){1,}$/', $columnType, $matches)) {
1220
            return false;
1221
        }
1222
1223
        $baseType = $matches[1];
1224
1225
        return in_array($baseType, $this->getColumnTypes());
1226
    }
1227
1228
    /**
1229
     * @param string $tableName
1230
     * @return array
1231
     */
1232
    private function getSchemaName($tableName)
1233
    {
1234
        $schema = $this->getGlobalSchemaName();
1235
        $table = $tableName;
1236
        if (false !== strpos($tableName, '.')) {
1237
            list($schema, $table) = explode('.', $tableName);
1238
        }
1239
1240
        return [
1241
            'schema' => $schema,
1242
            'table' => $table,
1243
        ];
1244
    }
1245
1246
    /**
1247
     * Gets the schema name.
1248
     *
1249
     * @return string
1250
     */
1251
    private function getGlobalSchemaName()
1252
    {
1253
        $options = $this->getOptions();
1254
1255
        return empty($options['schema']) ? 'public' : $options['schema'];
1256
    }
1257
1258
    /**
1259
     * {@inheritdoc}
1260
     */
1261
    public function castToBool($value)
1262
    {
1263
        return (bool)$value ? 'TRUE' : 'FALSE';
1264
    }
1265
}
1266