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

PostgresAdapter::getIndexSqlDefinition()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 23
Code Lines 16

Duplication

Lines 7
Ratio 30.43 %

Code Coverage

Tests 10
CRAP Score 4.3731

Importance

Changes 0
Metric Value
dl 7
loc 23
ccs 10
cts 14
cp 0.7143
rs 8.7972
c 0
b 0
f 0
cc 4
eloc 16
nc 3
nop 2
crap 4.3731
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
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
                $sql .= implode(',', array_map([$this, 'quoteColumnName'], $options['primary_key']));
222 1
            }
223 1
            $sql .= ')';
224 1
        } else {
225 1
            $sql = substr(rtrim($sql), 0, -1); // no primary keys
226 1
        }
227 1
228 1
        // set the foreign keys
229 68
        $foreignKeys = $table->getForeignKeys();
230 68
        if (!empty($foreignKeys)) {
231 2
            foreach ($foreignKeys as $foreignKey) {
232
                $sql .= ', ' . $this->getForeignKeySqlDefinition($foreignKey, $table->getName());
233
            }
234
        }
235 68
236 68
        $sql .= ');';
237 1
238 1
        // process column comments
239 1
        if (!empty($this->columnsWithComments)) {
240 1
            foreach ($this->columnsWithComments as $column) {
241
                $sql .= $this->getColumnCommentSqlDefinition($column, $table->getName());
242 68
            }
243
        }
244
245 68
        // set the indexes
246 6
        $indexes = $table->getIndexes();
247 6
        if (!empty($indexes)) {
248 6
            foreach ($indexes as $index) {
249 6
                $sql .= $this->getIndexSqlDefinition($index, $table->getName());
250
            }
251
        }
252
253 68
        // execute the sql
254 68
        $this->execute($sql);
255 5
256 5
        // process table comments
257 5
        if (isset($options['comment'])) {
258 5
            $sql = sprintf(
259
                'COMMENT ON TABLE %s IS %s',
260
                $this->quoteTableName($table->getName()),
261 68
                $this->getConnection()->quote($options['comment'])
262
            );
263
            $this->execute($sql);
264 68
        }
265 1
    }
266 1
267 1
    /**
268 1
     * {@inheritdoc}
269 1
     */
270 1
    public function renameTable($tableName, $newTableName)
271 1
    {
272 68
        $sql = sprintf(
273
            'ALTER TABLE %s RENAME TO %s',
274
            $this->quoteTableName($tableName),
275
            $this->quoteColumnName($newTableName)
276
        );
277 1
        $this->execute($sql);
278
    }
279 1
280 1
    /**
281 1
     * {@inheritdoc}
282 1
     */
283 1
    public function dropTable($tableName)
284 1
    {
285 1
        $this->execute(sprintf('DROP TABLE %s', $this->quoteTableName($tableName)));
286
    }
287
288
    /**
289
     * {@inheritdoc}
290 1
     */
291
    public function truncateTable($tableName)
292 1
    {
293 1
        $sql = sprintf(
294
            'TRUNCATE TABLE %s',
295
            $this->quoteTableName($tableName)
296
        );
297
298 1
        $this->execute($sql);
299
    }
300 1
301 1
    /**
302 1
     * {@inheritdoc}
303 1
     */
304
    public function getColumns($tableName)
305 1
    {
306 1
        $parts = $this->getSchemaName($tableName);
307
        $columns = [];
308
        $sql = sprintf(
309
            "SELECT column_name, data_type, is_identity, is_nullable,
310
             column_default, character_maximum_length, numeric_precision, numeric_scale
311 9
             FROM information_schema.columns
312
             WHERE table_schema = %s AND table_name = %s",
313 9
            $this->getConnection()->quote($parts['schema']),
314 9
            $this->getConnection()->quote($parts['table'])
315
        );
316
        $columnsInfo = $this->fetchAll($sql);
317
318 9
        foreach ($columnsInfo as $columnInfo) {
319
            $column = new Column();
320 9
            $column->setName($columnInfo['column_name'])
321 9
                   ->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"}>; 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...
322
                   ->setNull($columnInfo['is_nullable'] === 'YES')
323 9
                   ->setDefault($columnInfo['column_default'])
324 9
                   ->setIdentity($columnInfo['is_identity'] === 'YES')
325 9
                   ->setPrecision($columnInfo['numeric_precision'])
326 9
                   ->setScale($columnInfo['numeric_scale']);
327 9
328 9
            if (preg_match('/\bwith time zone$/', $columnInfo['data_type'])) {
329 9
                $column->setTimezone(true);
330 9
            }
331 9
332
            if (isset($columnInfo['character_maximum_length'])) {
333 9
                $column->setLimit($columnInfo['character_maximum_length']);
334 1
            }
335 1
            $columns[] = $column;
336
        }
337 9
338 5
        return $columns;
339 5
    }
340 9
341 9
    /**
342 9
     * {@inheritdoc}
343
     */
344
    public function hasColumn($tableName, $columnName)
345
    {
346
        $parts = $this->getSchemaName($tableName);
347
        $sql = sprintf(
348 24
            "SELECT count(*)
349
            FROM information_schema.columns
350 24
            WHERE table_schema = %s AND table_name = %s AND column_name = %s",
351
            $this->getConnection()->quote($parts['schema']),
352
            $this->getConnection()->quote($parts['table']),
353 24
            $this->getConnection()->quote($columnName)
354 24
        );
355 24
356
        $result = $this->fetchRow($sql);
357 24
358
        return $result['count'] > 0;
359 24
    }
360 24
361
    /**
362
     * {@inheritdoc}
363
     */
364 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...
365
    {
366 18
        $sql = sprintf(
367
            'ALTER TABLE %s ADD %s %s;',
368 18
            $this->quoteTableName($table->getName()),
369 18
            $this->quoteColumnName($column->getName()),
370 18
            $this->getColumnSqlDefinition($column)
371 18
        );
372 18
373 18
        if ($column->getComment()) {
374
            $sql .= $this->getColumnCommentSqlDefinition($column, $table->getName());
375 18
        }
376 18
377
        $this->execute($sql);
378
    }
379
380
    /**
381 3
     * {@inheritdoc}
382
     */
383 3
    public function renameColumn($tableName, $columnName, $newColumnName)
384
    {
385
        $parts = $this->getSchemaName($tableName);
386 3
        $sql = sprintf(
387 3
            "SELECT CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END AS column_exists
388
             FROM information_schema.columns
389 3
             WHERE table_schema = %s AND table_name = %s AND column_name = %s",
390 3
            $this->getConnection()->quote($parts['schema']),
391 3
            $this->getConnection()->quote($parts['table']),
392 1
            $this->getConnection()->quote($columnName)
393
        );
394 2
        $result = $this->fetchRow($sql);
395 2
        if (!(bool)$result['column_exists']) {
396 2
            throw new \InvalidArgumentException("The specified column does not exist: $columnName");
397 2
        }
398 2
        $this->execute(
399 2
            sprintf(
400 2
                'ALTER TABLE %s RENAME COLUMN %s TO %s',
401 2
                $this->quoteTableName($tableName),
402 2
                $this->quoteColumnName($columnName),
403
                $this->quoteColumnName($newColumnName)
404
            )
405
        );
406
    }
407 5
408
    /**
409
     * {@inheritdoc}
410
     */
411 5
    public function changeColumn($tableName, $columnName, Column $newColumn)
412 5
    {
413 5
        // TODO - is it possible to merge these 3 queries into less?
414 5
        // change data type
415 5
        $sql = sprintf(
416 5
            'ALTER TABLE %s ALTER COLUMN %s TYPE %s',
417
            $this->quoteTableName($tableName),
418 5
            $this->quoteColumnName($columnName),
419 5
            $this->getColumnSqlDefinition($newColumn)
420
        );
421 5
        //NULL and DEFAULT cannot be set while changing column type
422 5
        $sql = preg_replace('/ NOT NULL/', '', $sql);
423
        $sql = preg_replace('/ NULL/', '', $sql);
424 5
        //If it is set, DEFAULT is the last definition
425 5
        $sql = preg_replace('/DEFAULT .*/', '', $sql);
426 5
        $this->execute($sql);
427 5
        // process null
428 5
        $sql = sprintf(
429 5
            'ALTER TABLE %s ALTER COLUMN %s',
430 2
            $this->quoteTableName($tableName),
431 2
            $this->quoteColumnName($columnName)
432 4
        );
433
        if ($newColumn->isNull()) {
434 5
            $sql .= ' DROP NOT NULL';
435 5
        } else {
436
            $sql .= ' SET NOT NULL';
437 1
        }
438 1
        $this->execute($sql);
439 1
        if (!is_null($newColumn->getDefault())) {
440 1
            //change default
441 1
            $this->execute(
442 1
                sprintf(
443 1
                    'ALTER TABLE %s ALTER COLUMN %s SET %s',
444 1
                    $this->quoteTableName($tableName),
445 1
                    $this->quoteColumnName($columnName),
446
                    $this->getDefaultValueDefinition($newColumn->getDefault())
447 4
                )
448 4
            );
449 4
        } else {
450 4
            //drop default
451 4
            $this->execute(
452 4
                sprintf(
453 4
                    'ALTER TABLE %s ALTER COLUMN %s DROP DEFAULT',
454
                    $this->quoteTableName($tableName),
455
                    $this->quoteColumnName($columnName)
456 5
                )
457 1
            );
458 1
        }
459 1
        // rename column
460 1
        if ($columnName !== $newColumn->getName()) {
461 1
            $this->execute(
462 1
                sprintf(
463 1
                    'ALTER TABLE %s RENAME COLUMN %s TO %s',
464 1
                    $this->quoteTableName($tableName),
465 1
                    $this->quoteColumnName($columnName),
466
                    $this->quoteColumnName($newColumn->getName())
467
                )
468 5
            );
469 2
        }
470 2
471 2
        // change column comment if needed
472 5
        if ($newColumn->getComment()) {
473
            $sql = $this->getColumnCommentSqlDefinition($newColumn, $tableName);
474
            $this->execute($sql);
475
        }
476
    }
477 1
478
    /**
479 1
     * {@inheritdoc}
480 1
     */
481 1
    public function dropColumn($tableName, $columnName)
482 1
    {
483 1
        $this->execute(
484 1
            sprintf(
485 1
                'ALTER TABLE %s DROP COLUMN %s',
486 1
                $this->quoteTableName($tableName),
487
                $this->quoteColumnName($columnName)
488
            )
489
        );
490
    }
491
492
    /**
493
     * Get an array of indexes from a particular table.
494 9
     *
495
     * @param string $tableName Table Name
496 9
     * @return array
497
     */
498
    protected function getIndexes($tableName)
499
    {
500
        $parts = $this->getSchemaName($tableName);
501
502
        $indexes = [];
503
        $sql = sprintf(
504
            "SELECT
505
                i.relname AS index_name,
506
                a.attname AS column_name
507
            FROM
508
                pg_class t,
509
                pg_class i,
510
                pg_index ix,
511
                pg_attribute a,
512
                pg_namespace nsp
513
            WHERE
514 9
                t.oid = ix.indrelid
515 9
                AND i.oid = ix.indexrelid
516 9
                AND a.attrelid = t.oid
517 9
                AND a.attnum = ANY(ix.indkey)
518 9
                AND t.relnamespace = nsp.oid
519 9
                AND nsp.nspname = %s
520 9
                AND t.relkind = 'r'
521 9
                AND t.relname = %s
522 9
            ORDER BY
523
                t.relname,
524
                i.relname",
525
            $this->getConnection()->quote($parts['schema']),
526
            $this->getConnection()->quote($parts['table'])
527
        );
528 9
        $rows = $this->fetchAll($sql);
529 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...
530 9
            if (!isset($indexes[$row['index_name']])) {
531 4
                $indexes[$row['index_name']] = ['columns' => []];
532 4
            }
533 9
            $indexes[$row['index_name']]['columns'][] = $row['column_name'];
534 9
        }
535 9
536 9
        return $indexes;
537 9
    }
538
539 8
    /**
540 8
     * {@inheritdoc}
541
     */
542 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...
543
    {
544
        if (is_string($columns)) {
545
            $columns = [$columns];
546 1
        }
547
        $indexes = $this->getIndexes($tableName);
548 1
        foreach ($indexes as $index) {
549 1
            if (array_diff($index['columns'], $columns) === array_diff($columns, $index['columns'])) {
550 1
                return true;
551 1
            }
552
        }
553
554
        return false;
555
    }
556
557
    /**
558
     * {@inheritdoc}
559
     */
560 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...
561
    {
562 2
        $indexes = $this->getIndexes($tableName);
563 2
        foreach ($indexes as $name => $index) {
564 2
            if ($name === $indexName) {
565
                return true;
566
            }
567
        }
568
569 1
        return false;
570
    }
571 1
572 1
    /**
573 1
     * {@inheritdoc}
574
     */
575 1
    public function addIndex(Table $table, Index $index)
576 1
    {
577
        $sql = $this->getIndexSqlDefinition($index, $table->getName());
578 1
        $this->execute($sql);
579 1
    }
580 1
581 1
    /**
582 1
     * {@inheritdoc}
583 1
     */
584 1
    public function dropIndex($tableName, $columns)
585 1
    {
586 1
        $parts = $this->getSchemaName($tableName);
587
588 1
        if (is_string($columns)) {
589
            $columns = [$columns]; // str to array
590
        }
591
592
        $indexes = $this->getIndexes($tableName);
593
        foreach ($indexes as $indexName => $index) {
594
            $a = array_diff($columns, $index['columns']);
595
            if (empty($a)) {
596 1
                $this->execute(
597
                    sprintf(
598 1
                        'DROP INDEX IF EXISTS %s',
599 1
                        '"' . ($parts['schema'] . '".' . $this->quoteColumnName($indexName))
600
                    )
601 1
                );
602 1
603 1
                return;
604
            }
605
        }
606
    }
607
608 3
    /**
609
     * {@inheritdoc}
610 3
     */
611 1
    public function dropIndexByName($tableName, $indexName)
612 1
    {
613 3
        $parts = $this->getSchemaName($tableName);
614 3
615
        $sql = sprintf(
616
            'DROP INDEX IF EXISTS %s',
617
            '"' . ($parts['schema'] . '".' . $this->quoteColumnName($indexName))
618
        );
619
        $this->execute($sql);
620 3
    }
621 3
622 3
    /**
623 3
     * {@inheritdoc}
624
     */
625 1 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...
626 1
    {
627
        if (is_string($columns)) {
628
            $columns = [$columns]; // str to array
629
        }
630
        $foreignKeys = $this->getForeignKeys($tableName);
631
        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...
632
            if (isset($foreignKeys[$constraint])) {
633
                return !empty($foreignKeys[$constraint]);
634
            }
635
636 3
            return false;
637
        } else {
638 3
            foreach ($foreignKeys as $key) {
639 3
                $a = array_diff($columns, $key['columns']);
640
                if (empty($a)) {
641
                    return true;
642
                }
643
            }
644
645
            return false;
646
        }
647
    }
648
649
    /**
650 3
     * Get an array of foreign keys from a particular table.
651
     *
652 3
     * @param string $tableName Table Name
653 3
     * @return array
654 3
     */
655 3
    protected function getForeignKeys($tableName)
656 3
    {
657 3
        $parts = $this->getSchemaName($tableName);
658 3
        $foreignKeys = [];
659 3
        $rows = $this->fetchAll(sprintf(
660
            "SELECT
661
                    tc.constraint_name,
662
                    tc.table_name, kcu.column_name,
663
                    ccu.table_name AS referenced_table_name,
664
                    ccu.column_name AS referenced_column_name
665 2
                FROM
666
                    information_schema.table_constraints AS tc
667 2
                    JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name
668 2
                    JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name
669 2
                WHERE constraint_type = 'FOREIGN KEY' AND tc.table_schema = %s AND tc.table_name = %s
670 2
                ORDER BY kcu.position_in_unique_constraint",
671 2
            $this->getConnection()->quote($parts['schema']),
672 2
            $this->getConnection()->quote($parts['table'])
673 2
        ));
674
        foreach ($rows as $row) {
675
            $foreignKeys[$row['constraint_name']]['table'] = $row['table_name'];
676
            $foreignKeys[$row['constraint_name']]['columns'][] = $row['column_name'];
677
            $foreignKeys[$row['constraint_name']]['referenced_table'] = $row['referenced_table_name'];
678 1
            $foreignKeys[$row['constraint_name']]['referenced_columns'][] = $row['referenced_column_name'];
679
        }
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_TEXT:
745 68
            case static::PHINX_TYPE_TIME:
746 68
            case static::PHINX_TYPE_DATE:
747 1
            case static::PHINX_TYPE_BOOLEAN:
748 68
            case static::PHINX_TYPE_JSON:
749 68
            case static::PHINX_TYPE_JSONB:
750 68
            case static::PHINX_TYPE_UUID:
751 15
            case static::PHINX_TYPE_CIDR:
752 15
            case static::PHINX_TYPE_INET:
753 1
            case static::PHINX_TYPE_MACADDR:
754
            case static::PHINX_TYPE_TIMESTAMP:
755
                return ['name' => $type];
756
            case static::PHINX_TYPE_INTEGER:
757
                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...
758 14
                    return [
759
                        'name' => 'smallint',
760
                        'limit' => static::INT_SMALL
761 14
                    ];
762
                }
763
764 14
                return ['name' => $type];
765
            case static::PHINX_TYPE_DECIMAL:
766
                return ['name' => $type, 'precision' => 18, 'scale' => 0];
767 14
            case static::PHINX_TYPE_STRING:
768
                return ['name' => 'character varying', 'limit' => 255];
769
            case static::PHINX_TYPE_CHAR:
770 14
                return ['name' => 'character', 'limit' => 255];
771 14
            case static::PHINX_TYPE_BIG_INTEGER:
772 13
                return ['name' => 'bigint'];
773
            case static::PHINX_TYPE_FLOAT:
774
                return ['name' => 'real'];
775 1
            case static::PHINX_TYPE_DATETIME:
776 14
                return ['name' => 'timestamp'];
777
            case static::PHINX_TYPE_BLOB:
778
            case static::PHINX_TYPE_BINARY:
779
                return ['name' => 'bytea'];
780
            case static::PHINX_TYPE_INTERVAL:
781
                return ['name' => 'interval'];
782
            // Geospatial database types
783
            // Spatial storage in Postgres is done via the PostGIS extension,
784
            // which enables the use of the "geography" type in combination
785 10
            // with SRID 4326.
786
            case static::PHINX_TYPE_GEOMETRY:
787
                return ['name' => 'geography', 'type' => 'geometry', 'srid' => 4326];
788 10
            case static::PHINX_TYPE_POINT:
789 10
                return ['name' => 'geography', 'type' => 'point', 'srid' => 4326];
790 6
            case static::PHINX_TYPE_LINESTRING:
791 10
                return ['name' => 'geography', 'type' => 'linestring', 'srid' => 4326];
792 10
            case static::PHINX_TYPE_POLYGON:
793
                return ['name' => 'geography', 'type' => 'polygon', 'srid' => 4326];
794 10
            default:
795 2
                if ($this->isArrayType($type)) {
796 10
                    return ['name' => $type];
797
                }
798 10
                // Return array type
799
                throw new \RuntimeException('The type: "' . $type . '" is not supported');
800 10
        }
801
    }
802 1
803
    /**
804 1
     * Returns Phinx type by SQL type
805 10
     *
806 10
     * @param string $sqlType SQL type
807 10
     * @returns string Phinx type
808 9
     */
809 5
    public function getPhinxType($sqlType)
810 5
    {
811 3
        switch ($sqlType) {
812 4
            case 'character varying':
813 4
            case 'varchar':
814 2
                return static::PHINX_TYPE_STRING;
815 4
            case 'character':
816 4
            case 'char':
817 2
                return static::PHINX_TYPE_CHAR;
818 4
            case 'text':
819 1
                return static::PHINX_TYPE_TEXT;
820
            case 'json':
821 4
                return static::PHINX_TYPE_JSON;
822 4
            case 'jsonb':
823 4
                return static::PHINX_TYPE_JSONB;
824 4
            case 'smallint':
825 3
                return [
826 4
                    'name' => 'smallint',
827 2
                    'limit' => static::INT_SMALL
828 4
                ];
829 4
            case 'int':
830 4
            case 'int4':
831 4
            case 'integer':
832 3
                return static::PHINX_TYPE_INTEGER;
833 3
            case 'decimal':
834 3
            case 'numeric':
835 3
                return static::PHINX_TYPE_DECIMAL;
836 1
            case 'bigint':
837 1
            case 'int8':
838
                return static::PHINX_TYPE_BIG_INTEGER;
839
            case 'real':
840
            case 'float4':
841
                return static::PHINX_TYPE_FLOAT;
842
            case 'bytea':
843
                return static::PHINX_TYPE_BINARY;
844
            case 'interval':
845
                return static::PHINX_TYPE_INTERVAL;
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
891 68
        return $result['count'] > 0;
892
    }
893
894
    /**
895
     * {@inheritdoc}
896
     */
897
    public function dropDatabase($name)
898
    {
899
        $this->disconnect();
900 68
        $this->execute(sprintf('DROP DATABASE IF EXISTS %s', $name));
901
        $this->connect();
902 68
    }
903 68
904 50
    /**
905 50
     * Get the defintion for a `DEFAULT` statement.
906 68
     *
907 68
     * @param  mixed $default
908
     * @return string
909 68
     */
910 1 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...
911 1
    {
912 1
        if (is_string($default) && 'CURRENT_TIMESTAMP' !== $default) {
913 1
            $default = $this->getConnection()->quote($default);
914 1
        } elseif (is_bool($default)) {
915 68
            $default = $this->castToBool($default);
916
        }
917
918
        return isset($default) ? 'DEFAULT ' . $default : '';
919
    }
920
921
    /**
922 68
     * Gets the PostgreSQL Column Definition for a Column object.
923 68
     *
924 68
     * @param \Phinx\Db\Table\Column $column Column
925 68
     * @return string
926 68
     */
927
    protected function getColumnSqlDefinition(Column $column)
928
    {
929 68
        $buffer = [];
930 68
        if ($column->isIdentity()) {
931 68
            $buffer[] = $column->getType() == 'biginteger' ? 'BIGSERIAL' : 'SERIAL';
932 68
        } else {
933 1
            $sqlType = $this->getSqlType($column->getType(), $column->getLimit());
934 1
            $buffer[] = strtoupper($sqlType['name']);
935
            // integers cant have limits in postgres
936
            if (static::PHINX_TYPE_DECIMAL === $sqlType['name'] && ($column->getPrecision() || $column->getScale())) {
937 68
                $buffer[] = sprintf(
938
                    '(%s, %s)',
939 68
                    $column->getPrecision() ?: $sqlType['precision'],
940 68
                    $column->getScale() ?: $sqlType['scale']
941 68
                );
942
            } elseif (in_array($sqlType['name'], ['geography'])) {
943 68
                // geography type must be written with geometry type and srid, like this: geography(POLYGON,4326)
944
                $buffer[] = sprintf(
945
                    '(%s,%s)',
946
                    strtoupper($sqlType['type']),
947
                    $sqlType['srid']
948
                );
949
            } elseif (!in_array($sqlType['name'], ['integer', 'smallint', 'bigint'])) {
950
                if ($column->getLimit() || isset($sqlType['limit'])) {
951
                    $buffer[] = sprintf('(%s)', $column->getLimit() ?: $sqlType['limit']);
952
                }
953 6
            }
954
955
            $timeTypes = [
956 6
                'time',
957 6
                'timestamp',
958 6
            ];
959
            if (in_array($sqlType['name'], $timeTypes) && $column->isTimezone()) {
960 6
                $buffer[] = strtoupper('with time zone');
961 6
            }
962 6
        }
963 6
964
        $buffer[] = $column->isNull() ? 'NULL' : 'NOT NULL';
965 6
966
        if (!is_null($column->getDefault())) {
967
            $buffer[] = $this->getDefaultValueDefinition($column->getDefault());
968
        }
969
970
        return implode(' ', $buffer);
971
    }
972
973
    /**
974
     * Gets the PostgreSQL Column Comment Definition for a column object.
975 7
     *
976
     * @param \Phinx\Db\Table\Column $column Column
977 7
     * @param string $tableName Table name
978 3
     * @return string
979 3
     */
980 5
    protected function getColumnCommentSqlDefinition(Column $column, $tableName)
981 5
    {
982
        // passing 'null' is to remove column comment
983
        $comment = (strcasecmp($column->getComment(), 'NULL') !== 0)
984 5
                 ? $this->getConnection()->quote($column->getComment())
985
                 : 'NULL';
986 7
987 7
        return sprintf(
988 7
            'COMMENT ON COLUMN %s.%s IS %s;',
989 7
            $this->quoteTableName($tableName),
990 7
            $this->quoteColumnName($column->getName()),
991 7
            $comment
992 7
        );
993 7
    }
994
995
    /**
996
     * Gets the PostgreSQL Index Definition for an Index object.
997
     *
998
     * @param \Phinx\Db\Table\Index  $index Index
999
     * @param string $tableName Table name
1000
     * @return string
1001
     */
1002
    protected function getIndexSqlDefinition(Index $index, $tableName)
1003 3
    {
1004
        $parts = $this->getSchemaName($tableName);
1005 3
1006 3
        if (is_string($index->getName())) {
1007 3
            $indexName = $index->getName();
1008 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...
1009
            $columnNames = $index->getColumns();
1010
            if (is_string($columnNames)) {
1011 3
                $columnNames = [$columnNames];
1012
            }
1013
            $indexName = sprintf('%s_%s', $parts['table'], implode('_', $columnNames));
1014 3
        }
1015
        $def = sprintf(
1016
            "CREATE %s INDEX %s ON %s (%s);",
1017
            ($index->getType() === Index::UNIQUE ? 'UNIQUE' : ''),
1018
            $this->quoteColumnName($indexName),
1019
            $this->quoteTableName($tableName),
1020 68
            implode(',', array_map([$this, 'quoteColumnName'], $index->getColumns()))
1021
        );
1022
1023 68
        return $def;
1024 67
    }
1025 67
1026
    /**
1027 68
     * Gets the MySQL Foreign Key Definition for an ForeignKey object.
1028
     *
1029 68
     * @param \Phinx\Db\Table\ForeignKey $foreignKey
1030 68
     * @param string     $tableName  Table name
1031
     * @return string
1032
     */
1033
    protected function getForeignKeySqlDefinition(ForeignKey $foreignKey, $tableName)
1034
    {
1035
        $parts = $this->getSchemaName($tableName);
1036
1037
        $constraintName = $foreignKey->getConstraint() ?: ($parts['table'] . '_' . implode('_', $foreignKey->getColumns()) . '_fkey');
1038 68
        $def = ' CONSTRAINT ' . $this->quoteColumnName($constraintName)
0 ignored issues
show
Bug introduced by
It seems like $constraintName defined by $foreignKey->getConstrai...getColumns()) . '_fkey' on line 1037 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...
1039
            . ' FOREIGN KEY ("'
1040 68
            . implode('", "', $foreignKey->getColumns())
1041 68
            . '")'
1042 68
            . " REFERENCES {$this->quoteTableName($foreignKey->getReferencedTable()->getName())} (\""
1043
            . implode('", "', $foreignKey->getReferencedColumns())
1044
            . '")';
1045
        if ($foreignKey->getOnDelete()) {
1046
            $def .= " ON DELETE {$foreignKey->getOnDelete()}";
1047
        }
1048
        if ($foreignKey->getOnUpdate()) {
1049
            $def .= " ON UPDATE {$foreignKey->getOnUpdate()}";
1050 68
        }
1051
1052 68
        return $def;
1053
    }
1054
1055 68
    /**
1056
     * {@inheritdoc}
1057 68
     */
1058 68
    public function createSchemaTable()
1059 68
    {
1060
        // Create the public/custom schema if it doesn't already exist
1061
        if ($this->hasSchema($this->getGlobalSchemaName()) === false) {
1062
            $this->createSchema($this->getGlobalSchemaName());
1063
        }
1064
1065
        $this->fetchAll(sprintf('SET search_path TO %s', $this->getGlobalSchemaName()));
1066
1067
        parent::createSchemaTable();
1068 68
    }
1069
1070 68
    /**
1071 68
     * Creates the specified schema.
1072 68
     *
1073
     * @param  string $schemaName Schema Name
1074
     * @return void
1075
     */
1076
    public function createSchema($schemaName = 'public')
1077
    {
1078
        $sql = sprintf('CREATE SCHEMA %s;', $this->quoteSchemaName($schemaName)); // from postgres 9.3 we can use "CREATE SCHEMA IF NOT EXISTS schema_name"
1079 68
        $this->execute($sql);
1080
    }
1081 68
1082 68
    /**
1083 68
     * Checks to see if a schema exists.
1084 68
     *
1085
     * @param string $schemaName Schema Name
1086
     * @return bool
1087
     */
1088
    public function hasSchema($schemaName)
1089
    {
1090
        $sql = sprintf(
1091 68
            "SELECT count(*)
1092
             FROM pg_namespace
1093
             WHERE nspname = %s",
1094
            $this->getConnection()->quote($schemaName)
1095 68
        );
1096 68
        $result = $this->fetchRow($sql);
1097 68
1098 68
        return $result['count'] > 0;
1099 68
    }
1100 68
1101 68
    /**
1102
     * Drops the specified schema table.
1103
     *
1104
     * @param string $schemaName Schema name
1105
     * @return void
1106
     */
1107 73
    public function dropSchema($schemaName)
1108
    {
1109 73
        $sql = sprintf("DROP SCHEMA IF EXISTS %s CASCADE;", $this->quoteSchemaName($schemaName));
1110
        $this->execute($sql);
1111
    }
1112
1113
    /**
1114
     * Drops all schemas.
1115 73
     *
1116
     * @return void
1117
     */
1118 73
    public function dropAllSchemas()
1119
    {
1120
        foreach ($this->getAllSchemas() as $schema) {
1121
            $this->dropSchema($schema);
1122
        }
1123
    }
1124
1125
    /**
1126
     * Returns schemas.
1127 14
     *
1128
     * @return array
1129 14
     */
1130 1
    public function getAllSchemas()
1131
    {
1132
        $sql = "SELECT schema_name
1133 13
                FROM information_schema.schemata
1134 13
                WHERE schema_name <> 'information_schema' AND schema_name !~ '^pg_'";
1135
        $items = $this->fetchAll($sql);
1136
        $schemaNames = [];
1137
        foreach ($items as $item) {
1138
            $schemaNames[] = $item['schema_name'];
1139
        }
1140
1141
        return $schemaNames;
1142 68
    }
1143
1144 68
    /**
1145 68
     * {@inheritdoc}
1146
     */
1147
    public function getColumnTypes()
1148
    {
1149
        return array_merge(parent::getColumnTypes(), ['json', 'jsonb', 'cidr', 'inet', 'macaddr', 'interval']);
1150
    }
1151 68
1152
    /**
1153 68
     * {@inheritdoc}
1154
     */
1155
    public function isValidColumnType(Column $column)
1156
    {
1157
        // If not a standard column type, maybe it is array type?
1158
        return (parent::isValidColumnType($column) || $this->isArrayType($column->getType()));
1159
    }
1160
1161
    /**
1162
     * Check if the given column is an array of a valid type.
1163
     *
1164
     * @param  string $columnType
1165
     * @return bool
1166
     */
1167
    protected function isArrayType($columnType)
1168
    {
1169
        if (!preg_match('/^([a-z]+)(?:\[\]){1,}$/', $columnType, $matches)) {
1170
            return false;
1171
        }
1172
1173
        $baseType = $matches[1];
1174
1175
        return in_array($baseType, $this->getColumnTypes());
1176
    }
1177
1178
    /**
1179
     * @param string $tableName
1180
     * @return array
1181
     */
1182
    private function getSchemaName($tableName)
1183
    {
1184
        $schema = $this->getGlobalSchemaName();
1185
        $table = $tableName;
1186
        if (false !== strpos($tableName, '.')) {
1187
            list($schema, $table) = explode('.', $tableName);
1188
        }
1189
1190
        return [
1191
            'schema' => $schema,
1192
            'table' => $table,
1193
        ];
1194
    }
1195
1196
    /**
1197
     * Gets the schema name.
1198
     *
1199
     * @return string
1200
     */
1201
    private function getGlobalSchemaName()
1202
    {
1203
        $options = $this->getOptions();
1204
1205
        return empty($options['schema']) ? 'public' : $options['schema'];
1206
    }
1207
1208
    /**
1209
     * {@inheritdoc}
1210
     */
1211
    public function castToBool($value)
1212
    {
1213
        return (bool)$value ? 'TRUE' : 'FALSE';
1214
    }
1215
}
1216