Completed
Pull Request — master (#1193)
by Dmitriy
01:46
created

PostgresAdapter::getForeignKeySqlDefinition()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 22
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 6
cts 6
cp 1
rs 8.9197
c 0
b 0
f 0
cc 4
eloc 17
nc 8
nop 2
crap 4
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\Index;
34
use Phinx\Db\Table\ForeignKey;
35
36
class PostgresAdapter extends PdoAdapter implements AdapterInterface
37
{
38
    const INT_SMALL = 65535;
39
40
    /**
41
     * Columns with comments
42
     *
43
     * @var array
44
     */
45
    protected $columnsWithComments = [];
46
47
    /**
48
     * {@inheritdoc}
49
     */
50 68
    public function connect()
51
    {
52 68
        if ($this->connection === null) {
53 68
            if (!class_exists('PDO') || !in_array('pgsql', \PDO::getAvailableDrivers(), true)) {
54
                // @codeCoverageIgnoreStart
55
                throw new \RuntimeException('You need to enable the PDO_Pgsql extension for Phinx to run properly.');
56
                // @codeCoverageIgnoreEnd
57
            }
58
59 68
            $db = null;
60 68
            $options = $this->getOptions();
61
62
            // if port is specified use it, otherwise use the PostgreSQL default
63 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...
64 68
                $dsn = 'pgsql:host=' . $options['host'] . ';port=' . $options['port'] . ';dbname=' . $options['name'];
65 68
            } else {
66 1
                $dsn = 'pgsql:host=' . $options['host'] . ';dbname=' . $options['name'];
67
            }
68
69
            try {
70 68
                $db = new \PDO($dsn, $options['user'], $options['pass'], [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]);
71 68
            } catch (\PDOException $exception) {
72 1
                throw new \InvalidArgumentException(sprintf(
73 1
                    'There was a problem connecting to the database: %s',
74 1
                    $exception->getMessage()
75 1
                ));
76
            }
77
78 68
            $this->setConnection($db);
79 68
        }
80 68
    }
81
82
    /**
83
     * {@inheritdoc}
84
     */
85 68
    public function disconnect()
86
    {
87 68
        $this->connection = null;
88 68
    }
89
90
    /**
91
     * {@inheritdoc}
92
     */
93
    public function hasTransactions()
94
    {
95
        return true;
96
    }
97
98
    /**
99
     * {@inheritdoc}
100
     */
101
    public function beginTransaction()
102
    {
103
        $this->execute('BEGIN');
104
    }
105
106
    /**
107
     * {@inheritdoc}
108
     */
109
    public function commitTransaction()
110
    {
111
        $this->execute('COMMIT');
112
    }
113
114
    /**
115
     * {@inheritdoc}
116
     */
117
    public function rollbackTransaction()
118
    {
119
        $this->execute('ROLLBACK');
120
    }
121
122
    /**
123
     * Quotes a schema name for use in a query.
124
     *
125
     * @param string $schemaName Schema Name
126
     * @return string
127
     */
128 68
    public function quoteSchemaName($schemaName)
129
    {
130 68
        return $this->quoteColumnName($schemaName);
131
    }
132
133
    /**
134
     * {@inheritdoc}
135
     */
136 68
    public function quoteTableName($tableName)
137
    {
138 68
        $parts = $this->getSchemaName($tableName);
139
140
        return $this->quoteSchemaName($parts['schema']) . '.' . $this->quoteColumnName($parts['table']);
141
    }
142
143
    /**
144 68
     * {@inheritdoc}
145
     */
146 68
    public function quoteColumnName($columnName)
147
    {
148
        return '"'. $columnName . '"';
149
    }
150
151
    /**
152 68
     * {@inheritdoc}
153
     */
154 68
    public function hasTable($tableName)
155 68
    {
156
        $parts  = $this->getSchemaName($tableName);
157
        $result = $this->getConnection()->query(
158
            sprintf(
159 68
                'SELECT *
160 68
                FROM information_schema.tables
161 68
                WHERE table_schema = %s
162 68
                AND table_name = %s',
163 68
                $this->getConnection()->quote($parts['schema']),
164
                $this->getConnection()->quote($parts['table'])
165 68
            )
166
        );
167
168
        return $result->rowCount() === 1;
169
    }
170
171 68
    /**
172
     * {@inheritdoc}
173 68
     */
174
    public function createTable(Table $table)
175
    {
176 68
        $options = $table->getOptions();
177 68
        $parts   = $this->getSchemaName($table->getName());
178 48
179 48
         // Add the default primary key
180 48
        $columns = $table->getPendingColumns();
181 48 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...
182
            $column = new Column();
183 48
            $column->setName('id')
184 48
                   ->setType('integer')
185 68
                   ->setIdentity(true);
186
187 2
            array_unshift($columns, $column);
188 2
            $options['primary_key'] = 'id';
189 2
        } elseif (isset($options['id']) && is_string($options['id'])) {
190 2
            // Handle id => "field_name" to support AUTO_INCREMENT
191
            $column = new Column();
192 2
            $column->setName($options['id'])
193 2
                   ->setType('integer')
194 2
                   ->setIdentity(true);
195
196
            array_unshift($columns, $column);
197 68
            $options['primary_key'] = $options['id'];
198 68
        }
199
200 68
        // TODO - process table options like collation etc
201 68
        $sql = 'CREATE TABLE ';
202 68
        $sql .= $this->quoteTableName($table->getName()) . ' (';
203
204
        $this->columnsWithComments = [];
205 68 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...
206 6
            $sql .= $this->quoteColumnName($column->getName()) . ' ' . $this->getColumnSqlDefinition($column) . ', ';
207 6
208 68
            // set column comments, if needed
209
            if ($column->getComment()) {
210
                $this->columnsWithComments[] = $column;
211 68
            }
212 68
        }
213 68
214 68
         // set the primary key(s)
215 68
        if (isset($options['primary_key'])) {
216 68
            $sql = rtrim($sql);
217
            $sql .= sprintf(' CONSTRAINT %s PRIMARY KEY (', $this->quoteColumnName($parts['table'] . '_pkey'));
218
            if (is_string($options['primary_key'])) {       // handle primary_key => 'id'
219 1
                $sql .= $this->quoteColumnName($options['primary_key']);
220 1
            } 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...
221 1
                // PHP 5.4 will allow access of $this, so we can call quoteColumnName() directly in the anonymous function,
222 1
                // but for now just hard-code the adapter quotes
223 1
                $sql .= implode(
224 1
                    ',',
225 1
                    array_map(
226 1
                        function ($v) {
227 1
                            return '"' . $v . '"';
228 1
                        },
229 68
                        $options['primary_key']
230 68
                    )
231 2
                );
232
            }
233
            $sql .= ')';
234
        } else {
235 68
            $sql = substr(rtrim($sql), 0, -1);              // no primary keys
236 68
        }
237 1
238 1
        // set the foreign keys
239 1
        $foreignKeys = $table->getForeignKeys();
240 1
        if (!empty($foreignKeys)) {
241
            foreach ($foreignKeys as $foreignKey) {
242 68
                $sql .= ', ' . $this->getForeignKeySqlDefinition($foreignKey, $table->getName());
243
            }
244
        }
245 68
246 6
        $sql .= ');';
247 6
248 6
        // process column comments
249 6
        if (!empty($this->columnsWithComments)) {
250
            foreach ($this->columnsWithComments as $column) {
251
                $sql .= $this->getColumnCommentSqlDefinition($column, $table->getName());
252
            }
253 68
        }
254 68
255 5
256 5
        // set the indexes
257 5
        $indexes = $table->getIndexes();
258 5
        if (!empty($indexes)) {
259
            foreach ($indexes as $index) {
260
                $sql .= $this->getIndexSqlDefinition($index, $table->getName());
261 68
            }
262
        }
263
264 68
        // execute the sql
265 1
        $this->execute($sql);
266 1
267 1
        // process table comments
268 1
        if (isset($options['comment'])) {
269 1
            $sql = sprintf(
270 1
                'COMMENT ON TABLE %s IS %s',
271 1
                $this->quoteTableName($table->getName()),
272 68
                $this->getConnection()->quote($options['comment'])
273
            );
274
            $this->execute($sql);
275
        }
276
    }
277 1
278
    /**
279 1
     * {@inheritdoc}
280 1
     */
281 1
    public function renameTable($tableName, $newTableName)
282 1
    {
283 1
        $sql = sprintf(
284 1
            'ALTER TABLE %s RENAME TO %s',
285 1
            $this->quoteTableName($tableName),
286
            $this->quoteColumnName($newTableName)
287
        );
288
        $this->execute($sql);
289
    }
290 1
291
    /**
292 1
     * {@inheritdoc}
293 1
     */
294
    public function dropTable($tableName)
295
    {
296
        $this->execute(sprintf('DROP TABLE %s', $this->quoteTableName($tableName)));
297
    }
298 1
299
    /**
300 1
     * {@inheritdoc}
301 1
     */
302 1
    public function truncateTable($tableName)
303 1
    {
304
        $sql = sprintf(
305 1
            'TRUNCATE TABLE %s',
306 1
            $this->quoteTableName($tableName)
307
        );
308
309
        $this->execute($sql);
310
    }
311 9
312
    /**
313 9
     * {@inheritdoc}
314 9
     */
315
    public function getColumns($tableName)
316
    {
317
        $parts   = $this->getSchemaName($tableName);
318 9
        $columns = [];
319
        $sql     = sprintf(
320 9
            "SELECT column_name, data_type, is_identity, is_nullable,
321 9
             column_default, character_maximum_length, numeric_precision, numeric_scale
322
             FROM information_schema.columns
323 9
             WHERE table_schema = %s AND table_name = %s",
324 9
            $this->getConnection()->quote($parts['schema']),
325 9
            $this->getConnection()->quote($parts['table'])
326 9
        );
327 9
        $columnsInfo = $this->fetchAll($sql);
328 9
329 9
        foreach ($columnsInfo as $columnInfo) {
330 9
            $column = new Column();
331 9
            $column->setName($columnInfo['column_name'])
332
                   ->setType($this->getPhinxType($columnInfo['data_type']))
0 ignored issues
show
Bug introduced by
It seems like $this->getPhinxType($columnInfo['data_type']) targeting Phinx\Db\Adapter\PostgresAdapter::getPhinxType() can also be of type array<string,string|inte...ng","limit":"integer"}> or null; however, Phinx\Db\Table\Column::setType() 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...
333 9
                   ->setNull($columnInfo['is_nullable'] === 'YES')
334 1
                   ->setDefault($columnInfo['column_default'])
335 1
                   ->setIdentity($columnInfo['is_identity'] === 'YES')
336
                   ->setPrecision($columnInfo['numeric_precision'])
337 9
                   ->setScale($columnInfo['numeric_scale']);
338 5
339 5
            if (preg_match('/\bwith time zone$/', $columnInfo['data_type'])) {
340 9
                $column->setTimezone(true);
341 9
            }
342 9
343
            if (isset($columnInfo['character_maximum_length'])) {
344
                $column->setLimit($columnInfo['character_maximum_length']);
345
            }
346
            $columns[] = $column;
347
        }
348 24
        return $columns;
349
    }
350 24
351
    /**
352
     * {@inheritdoc}
353 24
     */
354 24
    public function hasColumn($tableName, $columnName)
355 24
    {
356
        $parts = $this->getSchemaName($tableName);
357 24
        $sql   = sprintf(
358
            "SELECT count(*)
359 24
            FROM information_schema.columns
360 24
            WHERE table_schema = %s AND table_name = %s AND column_name = %s",
361
            $this->getConnection()->quote($parts['schema']),
362
            $this->getConnection()->quote($parts['table']),
363
            $this->getConnection()->quote($columnName)
364
        );
365
366 18
        $result = $this->fetchRow($sql);
367
368 18
        return $result['count'] > 0;
369 18
    }
370 18
371 18
    /**
372 18
     * {@inheritdoc}
373 18
     */
374 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...
375 18
    {
376 18
        $sql = sprintf(
377
            'ALTER TABLE %s ADD %s %s',
378
            $this->quoteTableName($table->getName()),
379
            $this->quoteColumnName($column->getName()),
380
            $this->getColumnSqlDefinition($column)
381 3
        );
382
383 3
        $this->execute($sql);
384
    }
385
386 3
    /**
387 3
     * {@inheritdoc}
388
     */
389 3
    public function renameColumn($tableName, $columnName, $newColumnName)
390 3
    {
391 3
        $parts = $this->getSchemaName($tableName);
392 1
        $sql   = sprintf(
393
            "SELECT CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END AS column_exists
394 2
             FROM information_schema.columns
395 2
             WHERE table_schema = %s AND table_name = %s AND column_name = %s",
396 2
            $this->getConnection()->quote($parts['schema']),
397 2
            $this->getConnection()->quote($parts['table']),
398 2
            $this->getConnection()->quote($columnName)
399 2
        );
400 2
        $result = $this->fetchRow($sql);
401 2
        if (!(bool) $result['column_exists']) {
402 2
            throw new \InvalidArgumentException("The specified column does not exist: $columnName");
403
        }
404
        $this->execute(
405
            sprintf(
406
                'ALTER TABLE %s RENAME COLUMN %s TO %s',
407 5
                $this->quoteTableName($tableName),
408
                $this->quoteColumnName($columnName),
409
                $this->quoteColumnName($newColumnName)
410
            )
411 5
        );
412 5
    }
413 5
414 5
    /**
415 5
     * {@inheritdoc}
416 5
     */
417
    public function changeColumn($tableName, $columnName, Column $newColumn)
418 5
    {
419 5
        // TODO - is it possible to merge these 3 queries into less?
420
        // change data type
421 5
        $sql = sprintf(
422 5
            'ALTER TABLE %s ALTER COLUMN %s TYPE %s',
423
            $this->quoteTableName($tableName),
424 5
            $this->quoteColumnName($columnName),
425 5
            $this->getColumnSqlDefinition($newColumn)
426 5
        );
427 5
        //NULL and DEFAULT cannot be set while changing column type
428 5
        $sql = preg_replace('/ NOT NULL/', '', $sql);
429 5
        $sql = preg_replace('/ NULL/', '', $sql);
430 2
        //If it is set, DEFAULT is the last definition
431 2
        $sql = preg_replace('/DEFAULT .*/', '', $sql);
432 4
        $this->execute($sql);
433
        // process null
434 5
        $sql = sprintf(
435 5
            'ALTER TABLE %s ALTER COLUMN %s',
436
            $this->quoteTableName($tableName),
437 1
            $this->quoteColumnName($columnName)
438 1
        );
439 1
        if ($newColumn->isNull()) {
440 1
            $sql .= ' DROP NOT NULL';
441 1
        } else {
442 1
            $sql .= ' SET NOT NULL';
443 1
        }
444 1
        $this->execute($sql);
445 1
        if (!is_null($newColumn->getDefault())) {
446
            //change default
447 4
            $this->execute(
448 4
                sprintf(
449 4
                    'ALTER TABLE %s ALTER COLUMN %s SET %s',
450 4
                    $this->quoteTableName($tableName),
451 4
                    $this->quoteColumnName($columnName),
452 4
                    $this->getDefaultValueDefinition($newColumn->getDefault())
453 4
                )
454
            );
455
        } else {
456 5
            //drop default
457 1
            $this->execute(
458 1
                sprintf(
459 1
                    'ALTER TABLE %s ALTER COLUMN %s DROP DEFAULT',
460 1
                    $this->quoteTableName($tableName),
461 1
                    $this->quoteColumnName($columnName)
462 1
                )
463 1
            );
464 1
        }
465 1
        // rename column
466
        if ($columnName !== $newColumn->getName()) {
467
            $this->execute(
468 5
                sprintf(
469 2
                    'ALTER TABLE %s RENAME COLUMN %s TO %s',
470 2
                    $this->quoteTableName($tableName),
471 2
                    $this->quoteColumnName($columnName),
472 5
                    $this->quoteColumnName($newColumn->getName())
473
                )
474
            );
475
        }
476
477 1
        // change column comment if needed
478
        if ($newColumn->getComment()) {
479 1
            $sql = $this->getColumnCommentSqlDefinition($newColumn, $tableName);
480 1
            $this->execute($sql);
481 1
        }
482 1
    }
483 1
484 1
    /**
485 1
     * {@inheritdoc}
486 1
     */
487
    public function dropColumn($tableName, $columnName)
488
    {
489
        $this->execute(
490
            sprintf(
491
                'ALTER TABLE %s DROP COLUMN %s',
492
                $this->quoteTableName($tableName),
493
                $this->quoteColumnName($columnName)
494 9
            )
495
        );
496 9
    }
497
498
    /**
499
     * Get an array of indexes from a particular table.
500
     *
501
     * @param string $tableName Table Name
502
     * @return array
503
     */
504
    protected function getIndexes($tableName)
505
    {
506
        $parts = $this->getSchemaName($tableName);
507
508
        $indexes = [];
509
        $sql     = sprintf(
510
            "SELECT
511
                i.relname AS index_name,
512
                a.attname AS column_name
513
            FROM
514 9
                pg_class t,
515 9
                pg_class i,
516 9
                pg_index ix,
517 9
                pg_attribute a,
518 9
                pg_namespace nsp
519 9
            WHERE
520 9
                t.oid = ix.indrelid
521 9
                AND i.oid = ix.indexrelid
522 9
                AND a.attrelid = t.oid
523
                AND a.attnum = ANY(ix.indkey)
524
                AND t.relnamespace = nsp.oid
525
                AND nsp.nspname = %s
526
                AND t.relkind = 'r'
527
                AND t.relname = %s
528 9
            ORDER BY
529
                t.relname,
530 9
                i.relname",
531 4
            $this->getConnection()->quote($parts['schema']),
532 4
            $this->getConnection()->quote($parts['table'])
533 9
        );
534 9
        $rows = $this->fetchAll($sql);
535 9 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...
536 9
            if (!isset($indexes[$row['index_name']])) {
537 9
                $indexes[$row['index_name']] = ['columns' => []];
538
            }
539 8
            $indexes[$row['index_name']]['columns'][] = $row['column_name'];
540 8
        }
541
        return $indexes;
542
    }
543
544
    /**
545
     * {@inheritdoc}
546 1
     */
547 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...
548 1
    {
549 1
        if (is_string($columns)) {
550 1
            $columns = [$columns];
551 1
        }
552
        $indexes = $this->getIndexes($tableName);
553
        foreach ($indexes as $index) {
554
            if (array_diff($index['columns'], $columns) === array_diff($columns, $index['columns'])) {
555
                return true;
556
            }
557
        }
558
        return false;
559
    }
560 2
561
     /**
562 2
      * {@inheritdoc}
563 2
      */
564 2 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...
565
    {
566
        $indexes = $this->getIndexes($tableName);
567
        foreach ($indexes as $name => $index) {
568
            if ($name === $indexName) {
569 1
                return true;
570
            }
571 1
        }
572 1
        return false;
573 1
    }
574
575 1
    /**
576 1
     * {@inheritdoc}
577
     */
578 1
    public function addIndex(Table $table, Index $index)
579 1
    {
580 1
        $sql = $this->getIndexSqlDefinition($index, $table->getName());
581 1
        $this->execute($sql);
582 1
    }
583 1
584 1
    /**
585 1
     * {@inheritdoc}
586 1
     */
587
    public function dropIndex($tableName, $columns)
588 1
    {
589
        $parts = $this->getSchemaName($tableName);
590
591
        if (is_string($columns)) {
592
            $columns = [$columns]; // str to array
593
        }
594
595
        $indexes = $this->getIndexes($tableName);
596 1
        foreach ($indexes as $indexName => $index) {
597
            $a = array_diff($columns, $index['columns']);
598 1
            if (empty($a)) {
599 1
                $this->execute(
600
                    sprintf(
601 1
                        'DROP INDEX IF EXISTS %s',
602 1
                        '"' . ($parts['schema'] . '".' . $this->quoteColumnName($indexName))
603 1
                    )
604
                );
605
606
                return;
607
            }
608 3
        }
609
    }
610 3
611 1
    /**
612 1
     * {@inheritdoc}
613 3
     */
614 3
    public function dropIndexByName($tableName, $indexName)
615
    {
616
        $parts = $this->getSchemaName($tableName);
617
618
        $sql = sprintf(
619
            'DROP INDEX IF EXISTS %s',
620 3
            '"' . ($parts['schema'] . '".' . $this->quoteColumnName($indexName))
621 3
        );
622 3
        $this->execute($sql);
623 3
    }
624
625 1
    /**
626 1
     * {@inheritdoc}
627
     */
628 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...
629
    {
630
        if (is_string($columns)) {
631
            $columns = [$columns]; // str to array
632
        }
633
        $foreignKeys = $this->getForeignKeys($tableName);
634
        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...
635
            if (isset($foreignKeys[$constraint])) {
636 3
                return !empty($foreignKeys[$constraint]);
637
            }
638 3
            return false;
639 3
        } else {
640
            foreach ($foreignKeys as $key) {
641
                $a = array_diff($columns, $key['columns']);
642
                if (empty($a)) {
643
                    return true;
644
                }
645
            }
646
            return false;
647
        }
648
    }
649
650 3
    /**
651
     * Get an array of foreign keys from a particular table.
652 3
     *
653 3
     * @param string $tableName Table Name
654 3
     * @return array
655 3
     */
656 3
    protected function getForeignKeys($tableName)
657 3
    {
658 3
        $parts       = $this->getSchemaName($tableName);
659 3
        $foreignKeys = [];
660
        $rows        = $this->fetchAll(sprintf(
661
            "SELECT
662
                    tc.constraint_name,
663
                    tc.table_name, kcu.column_name,
664
                    ccu.table_name AS referenced_table_name,
665 2
                    ccu.column_name AS referenced_column_name
666
                FROM
667 2
                    information_schema.table_constraints AS tc
668 2
                    JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name
669 2
                    JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name
670 2
                WHERE constraint_type = 'FOREIGN KEY' AND tc.table_schema = %s AND tc.table_name = %s
671 2
                ORDER BY kcu.position_in_unique_constraint",
672 2
            $this->getConnection()->quote($parts['schema']),
673 2
            $this->getConnection()->quote($parts['table'])
674
        ));
675
        foreach ($rows as $row) {
676
            $foreignKeys[$row['constraint_name']]['table'] = $row['table_name'];
677
            $foreignKeys[$row['constraint_name']]['columns'][] = $row['column_name'];
678 1
            $foreignKeys[$row['constraint_name']]['referenced_table'] = $row['referenced_table_name'];
679
            $foreignKeys[$row['constraint_name']]['referenced_columns'][] = $row['referenced_column_name'];
680 1
        }
681
        return $foreignKeys;
682
    }
683
684 1
    /**
685 1
     * {@inheritdoc}
686 1
     */
687 1 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...
688 1
    {
689
        $sql = sprintf(
690 1
            'ALTER TABLE %s ADD %s',
691 1
            $this->quoteTableName($table->getName()),
692 1
            $this->getForeignKeySqlDefinition($foreignKey, $table->getName())
693 1
        );
694 1
        $this->execute($sql);
695
    }
696
697
    /**
698
     * {@inheritdoc}
699
     */
700
    public function dropForeignKey($tableName, $columns, $constraint = null)
701 1
    {
702 1
        if (is_string($columns)) {
703
            $columns = [$columns]; // str to array
704 1
        }
705
706 1
        $parts = $this->getSchemaName($tableName);
707 1
708 1
        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...
709 1
            $this->execute(
710
                sprintf(
711 1
                    'ALTER TABLE %s DROP CONSTRAINT %s',
712
                    $this->quoteTableName($tableName),
713
                    $this->quoteColumnName($constraint)
714
                )
715
            );
716 68
        } else {
717
            foreach ($columns as $column) {
718
                $rows = $this->fetchAll(sprintf(
719 68
                    "SELECT CONSTRAINT_NAME
720 14
                      FROM information_schema.KEY_COLUMN_USAGE
721
                      WHERE TABLE_SCHEMA = %s
722 1
                        AND TABLE_NAME IS NOT NULL
723
                        AND TABLE_NAME = %s
724 1
                        AND COLUMN_NAME = %s
725
                      ORDER BY POSITION_IN_UNIQUE_CONSTRAINT",
726 14
                    $this->getConnection()->quote($parts['schema']),
727 68
                    $this->getConnection()->quote($parts['table']),
728 68
                    $this->getConnection()->quote($column)
729 68
                ));
730 68
731 68
                foreach ($rows as $row) {
732 68
                    $this->dropForeignKey($tableName, $columns, $row['constraint_name']);
733 68
                }
734 68
            }
735 68
        }
736 68
    }
737 68
738 68
    /**
739 2
     * {@inheritdoc}
740 68
     */
741 68
    public function getSqlType($type, $limit = null)
742 68
    {
743
        switch ($type) {
744 68
            case static::PHINX_TYPE_INTEGER:
745 68
                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...
746 68
                    return [
747 1
                        'name' => 'smallint',
748 68
                        'limit' => static::INT_SMALL
749 68
                    ];
750 68
                }
751 15
                return ['name' => $type];
752 15
            case static::PHINX_TYPE_TEXT:
753 1
            case static::PHINX_TYPE_TIME:
754
            case static::PHINX_TYPE_DATE:
755
            case static::PHINX_TYPE_BOOLEAN:
756
            case static::PHINX_TYPE_JSON:
757
            case static::PHINX_TYPE_JSONB:
758 14
            case static::PHINX_TYPE_UUID:
759
            case static::PHINX_TYPE_CIDR:
760
            case static::PHINX_TYPE_INET:
761 14
            case static::PHINX_TYPE_MACADDR:
762
                return ['name' => $type];
763
            case static::PHINX_TYPE_DECIMAL:
764 14
                return ['name' => $type, 'precision' => 18, 'scale' => 0];
765
            case static::PHINX_TYPE_STRING:
766
                return ['name' => 'character varying', 'limit' => 255];
767 14
            case static::PHINX_TYPE_CHAR:
768
                return ['name' => 'character', 'limit' => 255];
769
            case static::PHINX_TYPE_BIG_INTEGER:
770 14
                return ['name' => 'bigint'];
771 14
            case static::PHINX_TYPE_FLOAT:
772 13
                return ['name' => 'real'];
773
            case static::PHINX_TYPE_DATETIME:
774
            case static::PHINX_TYPE_TIMESTAMP:
775 1
                return ['name' => 'timestamp'];
776 14
            case static::PHINX_TYPE_BLOB:
777
            case static::PHINX_TYPE_BINARY:
778
                return ['name' => 'bytea'];
779
            // Geospatial database types
780
            // Spatial storage in Postgres is done via the PostGIS extension,
781
            // which enables the use of the "geography" type in combination
782
            // with SRID 4326.
783
            case static::PHINX_TYPE_GEOMETRY:
784
                return ['name' => 'geography', 'type' => 'geometry', 'srid' => 4326];
785 10
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
786
            case static::PHINX_TYPE_POINT:
787
                return ['name' => 'geography', 'type' => 'point', 'srid' => 4326];
788 10
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
789 10
            case static::PHINX_TYPE_LINESTRING:
790 6
                return ['name' => 'geography', 'type' => 'linestring', 'srid' => 4326];
791 10
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
792 10
            case static::PHINX_TYPE_POLYGON:
793
                return ['name' => 'geography', 'type' => 'polygon', 'srid' => 4326];
794 10
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
795 2
            default:
796 10
                if ($this->isArrayType($type)) {
797
                    return ['name' => $type];
798 10
                }
799
                // Return array type
800 10
                throw new \RuntimeException('The type: "' . $type . '" is not supported');
801
        }
802 1
    }
803
804 1
    /**
805 10
     * Returns Phinx type by SQL type
806 10
     *
807 10
     * @param string $sqlType SQL type
808 9
     * @returns string Phinx type
809 5
     */
810 5
    public function getPhinxType($sqlType)
811 3
    {
812 4
        switch ($sqlType) {
813 4
            case 'character varying':
814 2
            case 'varchar':
815 4
                return static::PHINX_TYPE_STRING;
816 4
            case 'character':
817 2
            case 'char':
818 4
                return static::PHINX_TYPE_CHAR;
819 1
            case 'text':
820
                return static::PHINX_TYPE_TEXT;
821 4
            case 'json':
822 4
                return static::PHINX_TYPE_JSON;
823 4
            case 'jsonb':
824 4
                return static::PHINX_TYPE_JSONB;
825 3
            case 'smallint':
826 4
                return [
827 2
                    'name' => 'smallint',
828 4
                    'limit' => static::INT_SMALL
829 4
                ];
830 4
            case 'int':
831 4
            case 'int4':
832 3
            case 'integer':
833 3
                return static::PHINX_TYPE_INTEGER;
834 3
            case 'decimal':
835 3
            case 'numeric':
836 1
                return static::PHINX_TYPE_DECIMAL;
837 1
            case 'bigint':
838
            case 'int8':
839
                return static::PHINX_TYPE_BIG_INTEGER;
840
            case 'real':
841
            case 'float4':
842
                return static::PHINX_TYPE_FLOAT;
843
            case 'bytea':
844
                return static::PHINX_TYPE_BINARY;
845
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
846
            case 'time':
847
            case 'timetz':
848
            case 'time with time zone':
849
            case 'time without time zone':
850
                return static::PHINX_TYPE_TIME;
851
            case 'date':
852 1
                return static::PHINX_TYPE_DATE;
853
            case 'timestamp':
854 1
            case 'timestamptz':
855 1
            case 'timestamp with time zone':
856 1
            case 'timestamp without time zone':
857
                return static::PHINX_TYPE_DATETIME;
858
            case 'bool':
859
            case 'boolean':
860
                return static::PHINX_TYPE_BOOLEAN;
861 2
            case 'uuid':
862
                return static::PHINX_TYPE_UUID;
863 2
            case 'cidr':
864 2
                return static::PHINX_TYPE_CIDR;
865 2
            case 'inet':
866
                return static::PHINX_TYPE_INET;
867
            case 'macaddr':
868
                return static::PHINX_TYPE_MACADDR;
869
            default:
870
                throw new \RuntimeException('The PostgreSQL type: "' . $sqlType . '" is not supported');
871 1
        }
872
    }
873 1
874 1
    /**
875 1
     * {@inheritdoc}
876 1
     */
877
    public function createDatabase($name, $options = [])
878
    {
879
        $charset = isset($options['charset']) ? $options['charset'] : 'utf8';
880
        $this->execute(sprintf("CREATE DATABASE %s WITH ENCODING = '%s'", $name, $charset));
881
    }
882
883
    /**
884 68
     * {@inheritdoc}
885
     */
886 68
    public function hasDatabase($name)
887 4
    {
888 68
        $sql = sprintf("SELECT count(*) FROM pg_database WHERE datname = '%s'", $name);
889 68
        $result = $this->fetchRow($sql);
890 68
        return  $result['count'] > 0;
891 68
    }
892
893
    /**
894
     * {@inheritdoc}
895
     */
896
    public function dropDatabase($name)
897
    {
898
        $this->disconnect();
899
        $this->execute(sprintf('DROP DATABASE IF EXISTS %s', $name));
900 68
        $this->connect();
901
    }
902 68
903 68
    /**
904 50
     * Get the defintion for a `DEFAULT` statement.
905 50
     *
906 68
     * @param  mixed $default
907 68
     * @return string
908
     */
909 68 View Code Duplication
    protected function getDefaultValueDefinition($default)
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...
910 1
    {
911 1
        if (is_string($default) && 'CURRENT_TIMESTAMP' !== $default) {
912 1
            $default = $this->getConnection()->quote($default);
913 1
        } elseif (is_bool($default)) {
914 1
            $default = $this->castToBool($default);
915 68
        }
916
        return isset($default) ? 'DEFAULT ' . $default : '';
917
    }
918
919
    /**
920
     * Gets the PostgreSQL Column Definition for a Column object.
921
     *
922 68
     * @param Column $column Column
923 68
     * @return string
924 68
     */
925 68
    protected function getColumnSqlDefinition(Column $column)
926 68
    {
927
        $buffer = [];
928
        if ($column->isIdentity()) {
929 68
            $buffer[] = $column->getType() == 'biginteger' ? 'BIGSERIAL' : 'SERIAL';
930 68
        } else {
931 68
            $sqlType = $this->getSqlType($column->getType(), $column->getLimit());
932 68
            $buffer[] = strtoupper($sqlType['name']);
933 1
            // integers cant have limits in postgres
934 1
            if (static::PHINX_TYPE_DECIMAL === $sqlType['name'] && ($column->getPrecision() || $column->getScale())) {
935
                $buffer[] = sprintf(
936
                    '(%s, %s)',
937 68
                    $column->getPrecision() ? $column->getPrecision() : $sqlType['precision'],
938
                    $column->getScale() ? $column->getScale() : $sqlType['scale']
939 68
                );
940 68
            } elseif (in_array($sqlType['name'], ['geography'])) {
941 68
                // geography type must be written with geometry type and srid, like this: geography(POLYGON,4326)
942
                $buffer[] = sprintf(
943 68
                    '(%s,%s)',
944
                    strtoupper($sqlType['type']),
945
                    $sqlType['srid']
946
                );
947
            } elseif (!in_array($sqlType['name'], ['integer', 'smallint', 'bigint'])) {
948
                if ($column->getLimit() || isset($sqlType['limit'])) {
949
                    $buffer[] = sprintf('(%s)', $column->getLimit() ? $column->getLimit() : $sqlType['limit']);
950
                }
951
            }
952
953 6
            $timeTypes = [
954
                'time',
955
                'timestamp',
956 6
            ];
957 6
            if (in_array($sqlType['name'], $timeTypes) && $column->isTimezone()) {
958 6
                $buffer[] = strtoupper('with time zone');
959
            }
960 6
        }
961 6
962 6
        $buffer[] = $column->isNull() ? 'NULL' : 'NOT NULL';
963 6
964
        if (!is_null($column->getDefault())) {
965 6
            $buffer[] = $this->getDefaultValueDefinition($column->getDefault());
966
        }
967
968
        return implode(' ', $buffer);
969
    }
970
971
    /**
972
     * Gets the PostgreSQL Column Comment Definition for a column object.
973
     *
974
     * @param Column $column Column
975 7
     * @param string $tableName Table name
976
     * @return string
977 7
     */
978 3
    protected function getColumnCommentSqlDefinition(Column $column, $tableName)
979 3
    {
980 5
        // passing 'null' is to remove column comment
981 5
        $comment = (strcasecmp($column->getComment(), 'NULL') !== 0)
982
                 ? $this->getConnection()->quote($column->getComment())
983
                 : 'NULL';
984 5
985
        return sprintf(
986 7
            'COMMENT ON COLUMN %s.%s IS %s;',
987 7
            $this->quoteTableName($tableName),
988 7
            $this->quoteColumnName($column->getName()),
989 7
            $comment
990 7
        );
991 7
    }
992 7
993 7
    /**
994
     * Gets the PostgreSQL Index Definition for an Index object.
995
     *
996
     * @param Index  $index Index
997
     * @param string $tableName Table name
998
     * @return string
999
     */
1000
    protected function getIndexSqlDefinition(Index $index, $tableName)
1001
    {
1002
        $parts = $this->getSchemaName($tableName);
1003 3
1004
        if (is_string($index->getName())) {
1005 3
            $indexName = $index->getName();
1006 3 View Code Duplication
        } else {
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...
1007 3
            $columnNames = $index->getColumns();
1008 3
            if (is_string($columnNames)) {
1009
                $columnNames = [$columnNames];
1010
            }
1011 3
            $indexName = sprintf('%s_%s', $parts['table'], implode('_', $columnNames));
1012
        }
1013
        $def = sprintf(
1014 3
            "CREATE %s INDEX %s ON %s (%s);",
1015
            ($index->getType() === Index::UNIQUE ? 'UNIQUE' : ''),
1016
            $this->quoteColumnName($indexName),
1017
            $this->quoteTableName($tableName),
1018
            implode(',', array_map([$this, 'quoteColumnName'], $index->getColumns()))
1019
        );
1020 68
        return $def;
1021
    }
1022
1023 68
    /**
1024 67
     * Gets the MySQL Foreign Key Definition for an ForeignKey object.
1025 67
     *
1026
     * @param ForeignKey $foreignKey
1027 68
     * @param string     $tableName  Table name
1028
     * @return string
1029 68
     */
1030 68
    protected function getForeignKeySqlDefinition(ForeignKey $foreignKey, $tableName)
1031
    {
1032
        $parts = $this->getSchemaName($tableName);
1033
1034
        $constraintName = $foreignKey->getConstraint()
1035
            ? $foreignKey->getConstraint()
1036
            : ($parts['table'] . '_' . implode('_', $foreignKey->getColumns()) . '_fkey');
1037
        $def = ' CONSTRAINT ' . $this->quoteColumnName($constraintName)
0 ignored issues
show
Bug introduced by
It seems like $constraintName defined by $foreignKey->getConstrai...getColumns()) . '_fkey' on line 1034 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...
1038 68
            . ' FOREIGN KEY ("'
1039
            . implode('", "', $foreignKey->getColumns())
1040 68
            . '")'
1041 68
            . " REFERENCES {$this->quoteTableName($foreignKey->getReferencedTable()->getName())} (\""
1042 68
            . implode('", "', $foreignKey->getReferencedColumns())
1043
            . '")';
1044
        if ($foreignKey->getOnDelete()) {
1045
            $def .= " ON DELETE {$foreignKey->getOnDelete()}";
1046
        }
1047
        if ($foreignKey->getOnUpdate()) {
1048
            $def .= " ON UPDATE {$foreignKey->getOnUpdate()}";
1049
        }
1050 68
        return $def;
1051
    }
1052 68
1053
    /**
1054
     * {@inheritdoc}
1055 68
     */
1056
    public function createSchemaTable()
1057 68
    {
1058 68
        // Create the public/custom schema if it doesn't already exist
1059 68
        if ($this->hasSchema($this->getGlobalSchemaName()) === false) {
1060
            $this->createSchema($this->getGlobalSchemaName());
1061
        }
1062
1063
        $this->fetchAll(sprintf('SET search_path TO %s', $this->getGlobalSchemaName()));
1064
1065
        parent::createSchemaTable();
1066
    }
1067
1068 68
    /**
1069
     * Creates the specified schema.
1070 68
     *
1071 68
     * @param  string $schemaName Schema Name
1072 68
     * @return void
1073
     */
1074
    public function createSchema($schemaName = 'public')
1075
    {
1076
        $sql = sprintf('CREATE SCHEMA %s;', $this->quoteSchemaName($schemaName)); // from postgres 9.3 we can use "CREATE SCHEMA IF NOT EXISTS schema_name"
1077
        $this->execute($sql);
1078
    }
1079 68
1080
    /**
1081 68
     * Checks to see if a schema exists.
1082 68
     *
1083 68
     * @param string $schemaName Schema Name
1084 68
     * @return boolean
1085
     */
1086
    public function hasSchema($schemaName)
1087
    {
1088
        $sql = sprintf(
1089
            "SELECT count(*)
1090
             FROM pg_namespace
1091 68
             WHERE nspname = %s",
1092
            $this->getConnection()->quote($schemaName)
1093
        );
1094
        $result = $this->fetchRow($sql);
1095 68
        return $result['count'] > 0;
1096 68
    }
1097 68
1098 68
    /**
1099 68
     * Drops the specified schema table.
1100 68
     *
1101 68
     * @param string $schemaName Schema name
1102
     * @return void
1103
     */
1104
    public function dropSchema($schemaName)
1105
    {
1106
        $sql = sprintf("DROP SCHEMA IF EXISTS %s CASCADE;", $this->quoteSchemaName($schemaName));
1107 73
        $this->execute($sql);
1108
    }
1109 73
1110
    /**
1111
     * Drops all schemas.
1112
     *
1113
     * @return void
1114
     */
1115 73
    public function dropAllSchemas()
1116
    {
1117
        foreach ($this->getAllSchemas() as $schema) {
1118 73
            $this->dropSchema($schema);
1119
        }
1120
    }
1121
1122
    /**
1123
     * Returns schemas.
1124
     *
1125
     * @return array
1126
     */
1127 14
    public function getAllSchemas()
1128
    {
1129 14
        $sql = "SELECT schema_name
1130 1
                FROM information_schema.schemata
1131
                WHERE schema_name <> 'information_schema' AND schema_name !~ '^pg_'";
1132
        $items = $this->fetchAll($sql);
1133 13
        $schemaNames = [];
1134 13
        foreach ($items as $item) {
1135
            $schemaNames[] = $item['schema_name'];
1136
        }
1137
        return $schemaNames;
1138
    }
1139
1140
    /**
1141
     * {@inheritdoc}
1142 68
     */
1143
    public function getColumnTypes()
1144 68
    {
1145 68
        return array_merge(parent::getColumnTypes(), ['json', 'jsonb', 'cidr', 'inet', 'macaddr']);
1146
    }
1147
1148
    /**
1149
     * {@inheritdoc}
1150
     */
1151 68
    public function isValidColumnType(Column $column)
1152
    {
1153 68
        // If not a standard column type, maybe it is array type?
1154
        return (parent::isValidColumnType($column) || $this->isArrayType($column->getType()));
1155
    }
1156
1157
    /**
1158
     * Check if the given column is an array of a valid type.
1159
     *
1160
     * @param  string $columnType
1161
     * @return bool
1162
     */
1163
    protected function isArrayType($columnType)
1164
    {
1165
        if (!preg_match('/^([a-z]+)(?:\[\]){1,}$/', $columnType, $matches)) {
1166
            return false;
1167
        }
1168
1169
        $baseType = $matches[1];
1170
        return in_array($baseType, $this->getColumnTypes());
1171
    }
1172
1173
    /**
1174
     * @param  string $tableName
1175
     * @return array
1176
     */
1177
    private function getSchemaName($tableName)
1178
    {
1179
        $schema = $this->getGlobalSchemaName();
1180
        $table  = $tableName;
1181
        if (false !== strpos($tableName, '.')) {
1182
            list($schema, $table) = explode('.', $tableName);
1183
        }
1184
1185
        return [
1186
            'schema' => $schema,
1187
            'table'  => $table,
1188
        ];
1189
    }
1190
1191
    /**
1192
     * Gets the schema name.
1193
     *
1194
     * @return string
1195
     */
1196
    private function getGlobalSchemaName()
1197
    {
1198
        $options = $this->getOptions();
1199
1200
        return empty($options['schema']) ? 'public' : $options['schema'];
1201
    }
1202
1203
    /**
1204
     * {@inheritdoc}
1205
     */
1206
    public function castToBool($value)
1207
    {
1208
        return (bool) $value ? 'TRUE' : 'FALSE';
1209
    }
1210
}
1211