Completed
Pull Request — master (#1175)
by David Joseph
04:55
created

PostgresAdapter::getColumns()   C

Complexity

Conditions 9
Paths 33

Size

Total Lines 53
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 32
CRAP Score 9

Importance

Changes 0
Metric Value
dl 0
loc 53
ccs 32
cts 32
cp 1
rs 6.8963
c 0
b 0
f 0
cc 9
eloc 35
nc 33
nop 1
crap 9

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

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

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

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

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

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

Loading history...
213 68
            $sql = rtrim($sql);
214 68
            $sql .= sprintf(' CONSTRAINT %s_pkey PRIMARY KEY (', $table->getName());
215 68
            if (is_string($options['primary_key'])) { // handle primary_key => 'id'
216 68
                $sql .= $this->quoteColumnName($options['primary_key']);
217
            } 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...
218
                $sql .= implode(',', array_map([$this, 'quoteColumnName'], $options['primary_key']));
219 1
            }
220 1
            $sql .= ')';
221 1
        } else {
222 1
            $sql = rtrim($sql, ', '); // no primary keys
223 1
        }
224 1
225 1
        // set the foreign keys
226 1
        $foreignKeys = $table->getForeignKeys();
227 1
        if (!empty($foreignKeys)) {
228 1
            foreach ($foreignKeys as $foreignKey) {
229 68
                $sql .= ', ' . $this->getForeignKeySqlDefinition($foreignKey, $table->getName());
230 68
            }
231 2
        }
232
233
        $sql .= ');';
234
235 68
        // process column comments
236 68
        if (!empty($this->columnsWithComments)) {
237 1
            foreach ($this->columnsWithComments as $column) {
238 1
                $sql .= $this->getColumnCommentSqlDefinition($column, $table->getName());
239 1
            }
240 1
        }
241
242 68
        // set the indexes
243
        $indexes = $table->getIndexes();
244
        if (!empty($indexes)) {
245 68
            foreach ($indexes as $index) {
246 6
                $sql .= $this->getIndexSqlDefinition($index, $table->getName());
247 6
            }
248 6
        }
249 6
250
        // execute the sql
251
        $this->execute($sql);
252
253 68
        // process table comments
254 68
        if (isset($options['comment'])) {
255 5
            $sql = sprintf(
256 5
                'COMMENT ON TABLE %s IS %s',
257 5
                $this->quoteTableName($table->getName()),
258 5
                $this->getConnection()->quote($options['comment'])
259
            );
260
            $this->execute($sql);
261 68
        }
262
    }
263
264 68
    /**
265 1
     * {@inheritdoc}
266 1
     */
267 1
    public function renameTable($tableName, $newTableName)
268 1
    {
269 1
        $sql = sprintf(
270 1
            'ALTER TABLE %s RENAME TO %s',
271 1
            $this->quoteTableName($tableName),
272 68
            $this->quoteColumnName($newTableName)
273
        );
274
        $this->execute($sql);
275
    }
276
277 1
    /**
278
     * {@inheritdoc}
279 1
     */
280 1
    public function dropTable($tableName)
281 1
    {
282 1
        $this->execute(sprintf('DROP TABLE %s', $this->quoteTableName($tableName)));
283 1
    }
284 1
285 1
    /**
286
     * {@inheritdoc}
287
     */
288
    public function truncateTable($tableName)
289
    {
290 1
        $sql = sprintf(
291
            'TRUNCATE TABLE %s',
292 1
            $this->quoteTableName($tableName)
293 1
        );
294
295
        $this->execute($sql);
296
    }
297
298 1
    /**
299
     * {@inheritdoc}
300 1
     */
301 1
    public function getColumns($tableName)
302 1
    {
303 1
        $columns = [];
304
        $sql = sprintf(
305 1
            "SELECT column_name, data_type, udt_name, is_identity, is_nullable,
306 1
             column_default, character_maximum_length, numeric_precision, numeric_scale
307
             FROM information_schema.columns
308
             WHERE table_name ='%s'",
309
            $tableName
310
        );
311 9
        $columnsInfo = $this->fetchAll($sql);
312
313 9
        foreach ($columnsInfo as $columnInfo) {
314 9
            $isUserDefined = $columnInfo['data_type'] === 'USER-DEFINED';
315
            if ($isUserDefined) {
316
                $columnType = Literal::from($columnInfo['udt_name']);
317
            } else {
318 9
                $columnType = $this->getPhinxType($columnInfo['data_type']);
319
            }
320 9
            // If the default value begins with a ' or looks like a function mark it as literal
321 9
            if (isset($columnInfo['column_default'][0]) && $columnInfo['column_default'][0] === "'") {
322
                if (preg_match('/^\'(.*)\'::[^:]+$/', $columnInfo['column_default'], $match)) {
323 9
                    $columnDefault = $match[1];
324 9
                } else {
325 9
                    $columnDefault = Literal::from($columnInfo['column_default']);
326 9
                }
327 9
            } elseif (preg_match('/^\D[a-z_\d]*\(.*\)$/', $columnInfo['column_default'])) {
328 9
                $columnDefault = Literal::from($columnInfo['column_default']);
329 9
            } else {
330 9
                $columnDefault = $columnInfo['column_default'];
331 9
            }
332
333 9
            $column = new Column();
334 1
            $column->setName($columnInfo['column_name'])
335 1
                   ->setType($columnType)
336
                   ->setNull($columnInfo['is_nullable'] === 'YES')
337 9
                   ->setDefault($columnDefault)
338 5
                   ->setIdentity($columnInfo['is_identity'] === 'YES')
339 5
                   ->setPrecision($columnInfo['numeric_precision'])
340 9
                   ->setScale($columnInfo['numeric_scale']);
341 9
342 9
            if (preg_match('/\bwith time zone$/', $columnInfo['data_type'])) {
343
                $column->setTimezone(true);
344
            }
345
346
            if (isset($columnInfo['character_maximum_length'])) {
347
                $column->setLimit($columnInfo['character_maximum_length']);
348 24
            }
349
            $columns[] = $column;
350 24
        }
351
352
        return $columns;
353 24
    }
354 24
355 24
    /**
356
     * {@inheritdoc}
357 24
     */
358 View Code Duplication
    public function hasColumn($tableName, $columnName)
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...
359 24
    {
360 24
        $sql = sprintf(
361
            "SELECT count(*)
362
            FROM information_schema.columns
363
            WHERE table_schema = '%s' AND table_name = '%s' AND column_name = '%s'",
364
            $this->getSchemaName(),
365
            $tableName,
366 18
            $columnName
367
        );
368 18
369 18
        $result = $this->fetchRow($sql);
370 18
371 18
        return $result['count'] > 0;
372 18
    }
373 18
374
    /**
375 18
     * {@inheritdoc}
376 18
     */
377
    public function addColumn(Table $table, Column $column)
378
    {
379
        $sql = sprintf(
380
            'ALTER TABLE %s ADD %s %s;',
381 3
            $this->quoteTableName($table->getName()),
382
            $this->quoteColumnName($column->getName()),
383 3
            $this->getColumnSqlDefinition($column)
384
        );
385
386 3
        if ($column->getComment()) {
387 3
            $sql .= $this->getColumnCommentSqlDefinition($column, $table->getName());
388
        }
389 3
390 3
        $this->execute($sql);
391 3
    }
392 1
393
    /**
394 2
     * {@inheritdoc}
395 2
     */
396 2
    public function renameColumn($tableName, $columnName, $newColumnName)
397 2
    {
398 2
        $sql = sprintf(
399 2
            "SELECT CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END AS column_exists
400 2
             FROM information_schema.columns
401 2
             WHERE table_name ='%s' AND column_name = '%s'",
402 2
            $tableName,
403
            $columnName
404
        );
405
        $result = $this->fetchRow($sql);
406
        if (!(bool)$result['column_exists']) {
407 5
            throw new \InvalidArgumentException("The specified column does not exist: $columnName");
408
        }
409
        $this->execute(
410
            sprintf(
411 5
                'ALTER TABLE %s RENAME COLUMN %s TO %s',
412 5
                $this->quoteTableName($tableName),
413 5
                $this->quoteColumnName($columnName),
414 5
                $this->quoteColumnName($newColumnName)
415 5
            )
416 5
        );
417
    }
418 5
419 5
    /**
420
     * {@inheritdoc}
421 5
     */
422 5
    public function changeColumn($tableName, $columnName, Column $newColumn)
423
    {
424 5
        // TODO - is it possible to merge these 3 queries into less?
425 5
        // change data type
426 5
        $sql = sprintf(
427 5
            'ALTER TABLE %s ALTER COLUMN %s TYPE %s',
428 5
            $this->quoteTableName($tableName),
429 5
            $this->quoteColumnName($columnName),
430 2
            $this->getColumnSqlDefinition($newColumn)
431 2
        );
432 4
        //NULL and DEFAULT cannot be set while changing column type
433
        $sql = preg_replace('/ NOT NULL/', '', $sql);
434 5
        $sql = preg_replace('/ NULL/', '', $sql);
435 5
        //If it is set, DEFAULT is the last definition
436
        $sql = preg_replace('/DEFAULT .*/', '', $sql);
437 1
        $this->execute($sql);
438 1
        // process null
439 1
        $sql = sprintf(
440 1
            'ALTER TABLE %s ALTER COLUMN %s',
441 1
            $this->quoteTableName($tableName),
442 1
            $this->quoteColumnName($columnName)
443 1
        );
444 1
        if ($newColumn->isNull()) {
445 1
            $sql .= ' DROP NOT NULL';
446
        } else {
447 4
            $sql .= ' SET NOT NULL';
448 4
        }
449 4
        $this->execute($sql);
450 4
        if (!is_null($newColumn->getDefault())) {
451 4
            //change default
452 4
            $this->execute(
453 4
                sprintf(
454
                    'ALTER TABLE %s ALTER COLUMN %s SET %s',
455
                    $this->quoteTableName($tableName),
456 5
                    $this->quoteColumnName($columnName),
457 1
                    $this->getDefaultValueDefinition($newColumn->getDefault())
458 1
                )
459 1
            );
460 1
        } else {
461 1
            //drop default
462 1
            $this->execute(
463 1
                sprintf(
464 1
                    'ALTER TABLE %s ALTER COLUMN %s DROP DEFAULT',
465 1
                    $this->quoteTableName($tableName),
466
                    $this->quoteColumnName($columnName)
467
                )
468 5
            );
469 2
        }
470 2
        // rename column
471 2
        if ($columnName !== $newColumn->getName()) {
472 5
            $this->execute(
473
                sprintf(
474
                    'ALTER TABLE %s RENAME COLUMN %s TO %s',
475
                    $this->quoteTableName($tableName),
476
                    $this->quoteColumnName($columnName),
477 1
                    $this->quoteColumnName($newColumn->getName())
478
                )
479 1
            );
480 1
        }
481 1
482 1
        // change column comment if needed
483 1
        if ($newColumn->getComment()) {
484 1
            $sql = $this->getColumnCommentSqlDefinition($newColumn, $tableName);
485 1
            $this->execute($sql);
486 1
        }
487
    }
488
489
    /**
490
     * {@inheritdoc}
491
     */
492
    public function dropColumn($tableName, $columnName)
493
    {
494 9
        $this->execute(
495
            sprintf(
496 9
                'ALTER TABLE %s DROP COLUMN %s',
497
                $this->quoteTableName($tableName),
498
                $this->quoteColumnName($columnName)
499
            )
500
        );
501
    }
502
503
    /**
504
     * Get an array of indexes from a particular table.
505
     *
506
     * @param string $tableName Table Name
507
     * @return array
508
     */
509 View Code Duplication
    protected function getIndexes($tableName)
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...
510
    {
511
        $indexes = [];
512
        $sql = "SELECT
513
            i.relname AS index_name,
514 9
            a.attname AS column_name
515 9
        FROM
516 9
            pg_class t,
517 9
            pg_class i,
518 9
            pg_index ix,
519 9
            pg_attribute a
520 9
        WHERE
521 9
            t.oid = ix.indrelid
522 9
            AND i.oid = ix.indexrelid
523
            AND a.attrelid = t.oid
524
            AND a.attnum = ANY(ix.indkey)
525
            AND t.relkind = 'r'
526
            AND t.relname = '$tableName'
527
        ORDER BY
528 9
            t.relname,
529
            i.relname;";
530 9
        $rows = $this->fetchAll($sql);
531 4
        foreach ($rows as $row) {
532 4
            if (!isset($indexes[$row['index_name']])) {
533 9
                $indexes[$row['index_name']] = ['columns' => []];
534 9
            }
535 9
            $indexes[$row['index_name']]['columns'][] = strtolower($row['column_name']);
536 9
        }
537 9
538
        return $indexes;
539 8
    }
540 8
541
    /**
542
     * {@inheritdoc}
543
     */
544 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...
545
    {
546 1
        if (is_string($columns)) {
547
            $columns = [$columns];
548 1
        }
549 1
        $columns = array_map('strtolower', $columns);
550 1
        $indexes = $this->getIndexes($tableName);
551 1
        foreach ($indexes as $index) {
552
            if (array_diff($index['columns'], $columns) === array_diff($columns, $index['columns'])) {
553
                return true;
554
            }
555
        }
556
557
        return false;
558
    }
559
560 2
    /**
561
     * {@inheritdoc}
562 2
     */
563 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...
564 2
    {
565
        $indexes = $this->getIndexes($tableName);
566
        foreach ($indexes as $name => $index) {
567
            if ($name === $indexName) {
568
                return true;
569 1
            }
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
        if (is_string($columns)) {
590
            $columns = [$columns]; // str to array
591
        }
592
593
        $indexes = $this->getIndexes($tableName);
594
        $columns = array_map('strtolower', $columns);
595
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
                        $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
        $sql = sprintf(
617
            'DROP INDEX IF EXISTS %s',
618
            $indexName
619
        );
620 3
        $this->execute($sql);
621 3
    }
622 3
623 3
    /**
624
     * {@inheritdoc}
625 1
     */
626 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...
627
    {
628
        if (is_string($columns)) {
629
            $columns = [$columns]; // str to array
630
        }
631
        $foreignKeys = $this->getForeignKeys($tableName);
632
        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...
633
            if (isset($foreignKeys[$constraint])) {
634
                return !empty($foreignKeys[$constraint]);
635
            }
636 3
637
            return false;
638 3
        } else {
639 3
            foreach ($foreignKeys as $key) {
640
                $a = array_diff($columns, $key['columns']);
641
                if (empty($a)) {
642
                    return true;
643
                }
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 View Code Duplication
    protected function getForeignKeys($tableName)
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...
657 3
    {
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_name = '%s'
670 2
                ORDER BY kcu.position_in_unique_constraint",
671 2
            $tableName
672 2
        ));
673 2
        foreach ($rows as $row) {
674
            $foreignKeys[$row['constraint_name']]['table'] = $row['table_name'];
675
            $foreignKeys[$row['constraint_name']]['columns'][] = $row['column_name'];
676
            $foreignKeys[$row['constraint_name']]['referenced_table'] = $row['referenced_table_name'];
677
            $foreignKeys[$row['constraint_name']]['referenced_columns'][] = $row['referenced_column_name'];
678 1
        }
679
680 1
        return $foreignKeys;
681
    }
682
683
    /**
684 1
     * {@inheritdoc}
685 1
     */
686 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...
687 1
    {
688 1
        $sql = sprintf(
689
            'ALTER TABLE %s ADD %s',
690 1
            $this->quoteTableName($table->getName()),
691 1
            $this->getForeignKeySqlDefinition($foreignKey, $table->getName())
692 1
        );
693 1
        $this->execute($sql);
694 1
    }
695
696
    /**
697
     * {@inheritdoc}
698
     */
699 View Code Duplication
    public function dropForeignKey($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...
700
    {
701 1
        if (is_string($columns)) {
702 1
            $columns = [$columns]; // str to array
703
        }
704 1
705
        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...
706 1
            $this->execute(
707 1
                sprintf(
708 1
                    'ALTER TABLE %s DROP CONSTRAINT %s',
709 1
                    $this->quoteTableName($tableName),
710
                    $constraint
711 1
                )
712
            );
713
        } else {
714
            foreach ($columns as $column) {
715
                $rows = $this->fetchAll(sprintf(
716 68
                    "SELECT CONSTRAINT_NAME
717
                      FROM information_schema.KEY_COLUMN_USAGE
718
                      WHERE TABLE_SCHEMA = CURRENT_SCHEMA()
719 68
                        AND TABLE_NAME IS NOT NULL
720 14
                        AND TABLE_NAME = '%s'
721
                        AND COLUMN_NAME = '%s'
722 1
                      ORDER BY POSITION_IN_UNIQUE_CONSTRAINT",
723
                    $tableName,
724 1
                    $column
725
                ));
726 14
727 68
                foreach ($rows as $row) {
728 68
                    $this->dropForeignKey($tableName, $columns, $row['constraint_name']);
729 68
                }
730 68
            }
731 68
        }
732 68
    }
733 68
734 68
    /**
735 68
     * {@inheritdoc}
736 68
     */
737 68
    public function getSqlType($type, $limit = null)
738 68
    {
739 2
        switch ($type) {
740 68
            case static::PHINX_TYPE_INTEGER:
741 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...
742 68
                    return [
743
                        'name' => 'smallint',
744 68
                        'limit' => static::INT_SMALL
745 68
                    ];
746 68
                }
747 1
748 68
                return ['name' => $type];
749 68
            case static::PHINX_TYPE_TEXT:
750 68
            case static::PHINX_TYPE_TIME:
751 15
            case static::PHINX_TYPE_DATE:
752 15
            case static::PHINX_TYPE_BOOLEAN:
753 1
            case static::PHINX_TYPE_JSON:
754
            case static::PHINX_TYPE_JSONB:
755
            case static::PHINX_TYPE_UUID:
756
            case static::PHINX_TYPE_CIDR:
757
            case static::PHINX_TYPE_INET:
758 14
            case static::PHINX_TYPE_MACADDR:
759
                return ['name' => $type];
760
            case static::PHINX_TYPE_DECIMAL:
761 14
                return ['name' => $type, 'precision' => 18, 'scale' => 0];
762
            case static::PHINX_TYPE_STRING:
763
                return ['name' => 'character varying', 'limit' => 255];
764 14
            case static::PHINX_TYPE_CHAR:
765
                return ['name' => 'character', 'limit' => 255];
766
            case static::PHINX_TYPE_BIG_INTEGER:
767 14
                return ['name' => 'bigint'];
768
            case static::PHINX_TYPE_FLOAT:
769
                return ['name' => 'real'];
770 14
            case static::PHINX_TYPE_DATETIME:
771 14
            case static::PHINX_TYPE_TIMESTAMP:
772 13
                return ['name' => 'timestamp'];
773
            case static::PHINX_TYPE_BLOB:
774
            case static::PHINX_TYPE_BINARY:
775 1
                return ['name' => 'bytea'];
776 14
            case static::PHINX_TYPE_INTERVAL:
777
                return ['name' => 'interval'];
778
            // Geospatial database types
779
            // Spatial storage in Postgres is done via the PostGIS extension,
780
            // which enables the use of the "geography" type in combination
781
            // with SRID 4326.
782
            case static::PHINX_TYPE_GEOMETRY:
783
                return ['name' => 'geography', 'type' => 'geometry', 'srid' => 4326];
784
            case static::PHINX_TYPE_POINT:
785 10
                return ['name' => 'geography', 'type' => 'point', 'srid' => 4326];
786
            case static::PHINX_TYPE_LINESTRING:
787
                return ['name' => 'geography', 'type' => 'linestring', 'srid' => 4326];
788 10
            case static::PHINX_TYPE_POLYGON:
789 10
                return ['name' => 'geography', 'type' => 'polygon', 'srid' => 4326];
790 6
            default:
791 10
                if ($this->isArrayType($type)) {
792 10
                    return ['name' => $type];
793
                }
794 10
                // Return array type
795 2
                throw new \RuntimeException('The type: "' . $type . '" is not supported');
796 10
        }
797
    }
798 10
799
    /**
800 10
     * Returns Phinx type by SQL type
801
     *
802 1
     * @param string $sqlType SQL type
803
     * @returns string Phinx type
804 1
     */
805 10
    public function getPhinxType($sqlType)
806 10
    {
807 10
        switch ($sqlType) {
808 9
            case 'character varying':
809 5
            case 'varchar':
810 5
                return static::PHINX_TYPE_STRING;
811 3
            case 'character':
812 4
            case 'char':
813 4
                return static::PHINX_TYPE_CHAR;
814 2
            case 'text':
815 4
                return static::PHINX_TYPE_TEXT;
816 4
            case 'json':
817 2
                return static::PHINX_TYPE_JSON;
818 4
            case 'jsonb':
819 1
                return static::PHINX_TYPE_JSONB;
820
            case 'smallint':
821 4
                return [
822 4
                    'name' => 'smallint',
823 4
                    'limit' => static::INT_SMALL
824 4
                ];
825 3
            case 'int':
826 4
            case 'int4':
827 2
            case 'integer':
828 4
                return static::PHINX_TYPE_INTEGER;
829 4
            case 'decimal':
830 4
            case 'numeric':
831 4
                return static::PHINX_TYPE_DECIMAL;
832 3
            case 'bigint':
833 3
            case 'int8':
834 3
                return static::PHINX_TYPE_BIG_INTEGER;
835 3
            case 'real':
836 1
            case 'float4':
837 1
                return static::PHINX_TYPE_FLOAT;
838
            case 'bytea':
839
                return static::PHINX_TYPE_BINARY;
840
            case 'interval':
841
                return static::PHINX_TYPE_INTERVAL;
842
            case 'time':
843
            case 'timetz':
844
            case 'time with time zone':
845
            case 'time without time zone':
846
                return static::PHINX_TYPE_TIME;
847
            case 'date':
848
                return static::PHINX_TYPE_DATE;
849
            case 'timestamp':
850
            case 'timestamptz':
851
            case 'timestamp with time zone':
852 1
            case 'timestamp without time zone':
853
                return static::PHINX_TYPE_DATETIME;
854 1
            case 'bool':
855 1
            case 'boolean':
856 1
                return static::PHINX_TYPE_BOOLEAN;
857
            case 'uuid':
858
                return static::PHINX_TYPE_UUID;
859
            case 'cidr':
860
                return static::PHINX_TYPE_CIDR;
861 2
            case 'inet':
862
                return static::PHINX_TYPE_INET;
863 2
            case 'macaddr':
864 2
                return static::PHINX_TYPE_MACADDR;
865 2
            default:
866
                throw new \RuntimeException('The PostgreSQL type: "' . $sqlType . '" is not supported');
867
        }
868
    }
869
870
    /**
871 1
     * {@inheritdoc}
872
     */
873 1
    public function createDatabase($name, $options = [])
874 1
    {
875 1
        $charset = isset($options['charset']) ? $options['charset'] : 'utf8';
876 1
        $this->execute(sprintf("CREATE DATABASE %s WITH ENCODING = '%s'", $name, $charset));
877
    }
878
879
    /**
880
     * {@inheritdoc}
881
     */
882
    public function hasDatabase($databaseName)
883
    {
884 68
        $sql = sprintf("SELECT count(*) FROM pg_database WHERE datname = '%s'", $databaseName);
885
        $result = $this->fetchRow($sql);
886 68
887 4
        return $result['count'] > 0;
888 68
    }
889 68
890 68
    /**
891 68
     * {@inheritdoc}
892
     */
893
    public function dropDatabase($name)
894
    {
895
        $this->disconnect();
896
        $this->execute(sprintf('DROP DATABASE IF EXISTS %s', $name));
897
        $this->connect();
898
    }
899
900 68
    /**
901
     * Gets the PostgreSQL Column Definition for a Column object.
902 68
     *
903 68
     * @param \Phinx\Db\Table\Column $column Column
904 50
     * @return string
905 50
     */
906 68
    protected function getColumnSqlDefinition(Column $column)
907 68
    {
908
        $buffer = [];
909 68
        if ($column->isIdentity()) {
910 1
            $buffer[] = $column->getType() == 'biginteger' ? 'BIGSERIAL' : 'SERIAL';
911 1
        } elseif ($column->getType() instanceof Literal) {
912 1
            $buffer[] = (string)$column->getType();
913 1
        } else {
914 1
            $sqlType = $this->getSqlType($column->getType(), $column->getLimit());
915 68
            $buffer[] = strtoupper($sqlType['name']);
916
917
            // integers cant have limits in postgres
918
            if (static::PHINX_TYPE_DECIMAL === $sqlType['name'] && ($column->getPrecision() || $column->getScale())) {
919
                $buffer[] = sprintf(
920
                    '(%s, %s)',
921
                    $column->getPrecision() ?: $sqlType['precision'],
922 68
                    $column->getScale() ?: $sqlType['scale']
923 68
                );
924 68
            } elseif (in_array($sqlType['name'], ['geography'])) {
925 68
                // geography type must be written with geometry type and srid, like this: geography(POLYGON,4326)
926 68
                $buffer[] = sprintf(
927
                    '(%s,%s)',
928
                    strtoupper($sqlType['type']),
929 68
                    $sqlType['srid']
930 68
                );
931 68
            } elseif (!in_array($sqlType['name'], ['integer', 'smallint', 'bigint'])) {
932 68
                if ($column->getLimit() || isset($sqlType['limit'])) {
933 1
                    $buffer[] = sprintf('(%s)', $column->getLimit() ?: $sqlType['limit']);
934 1
                }
935
            }
936
937 68
            $timeTypes = [
938
                'time',
939 68
                'timestamp',
940 68
            ];
941 68
            if (in_array($sqlType['name'], $timeTypes) && $column->isTimezone()) {
942
                $buffer[] = strtoupper('with time zone');
943 68
            }
944
        }
945
946
        $buffer[] = $column->isNull() ? 'NULL' : 'NOT NULL';
947
        $buffer = implode(' ', $buffer);
948
949
        if (!is_null($column->getDefault())) {
950
            $buffer .= $this->getDefaultValueDefinition($column->getDefault());
951
        }
952
953 6
        return $buffer;
954
    }
955
956 6
    /**
957 6
     * Gets the PostgreSQL Column Comment Defininition for a column object.
958 6
     *
959
     * @param \Phinx\Db\Table\Column $column Column
960 6
     * @param string $tableName Table name
961 6
     * @return string
962 6
     */
963 6
    protected function getColumnCommentSqlDefinition(Column $column, $tableName)
964
    {
965 6
        // passing 'null' is to remove column comment
966
        $comment = (strcasecmp($column->getComment(), 'NULL') !== 0)
967
                 ? $this->getConnection()->quote($column->getComment())
968
                 : 'NULL';
969
970
        return sprintf(
971
            'COMMENT ON COLUMN %s.%s IS %s;',
972
            $this->quoteSchemaName($tableName),
973
            $this->quoteColumnName($column->getName()),
974
            $comment
975 7
        );
976
    }
977 7
978 3
    /**
979 3
     * Gets the PostgreSQL Index Definition for an Index object.
980 5
     *
981 5
     * @param \Phinx\Db\Table\Index  $index Index
982
     * @param string $tableName Table name
983
     * @return string
984 5
     */
985
    protected function getIndexSqlDefinition(Index $index, $tableName)
986 7
    {
987 7 View Code Duplication
        if (is_string($index->getName())) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
988 7
            $indexName = $index->getName();
989 7
        } else {
990 7
            $columnNames = $index->getColumns();
991 7
            if (is_string($columnNames)) {
992 7
                $columnNames = [$columnNames];
993 7
            }
994
            $indexName = sprintf('%s_%s', $tableName, implode('_', $columnNames));
995
        }
996
        $def = sprintf(
997
            "CREATE %s INDEX %s ON %s (%s);",
998
            ($index->getType() === Index::UNIQUE ? 'UNIQUE' : ''),
999
            $indexName,
1000
            $this->quoteTableName($tableName),
1001
            implode(',', array_map([$this, 'quoteColumnName'], $index->getColumns()))
1002
        );
1003 3
1004
        return $def;
1005 3
    }
1006 3
1007 3
    /**
1008 3
     * Gets the MySQL Foreign Key Definition for an ForeignKey object.
1009
     *
1010
     * @param \Phinx\Db\Table\ForeignKey $foreignKey
1011 3
     * @param string     $tableName  Table name
1012
     * @return string
1013
     */
1014 3 View Code Duplication
    protected function getForeignKeySqlDefinition(ForeignKey $foreignKey, $tableName)
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...
1015
    {
1016
        $constraintName = $foreignKey->getConstraint() ?: $tableName . '_' . implode('_', $foreignKey->getColumns());
1017
1018
        $def = ' CONSTRAINT "' . $constraintName . '" FOREIGN KEY ("' . implode('", "', $foreignKey->getColumns()) . '")';
1019
        $def .= " REFERENCES {$this->quoteTableName($foreignKey->getReferencedTable()->getName())} (\"" . implode('", "', $foreignKey->getReferencedColumns()) . '")';
1020 68
        if ($foreignKey->getOnDelete()) {
1021
            $def .= " ON DELETE {$foreignKey->getOnDelete()}";
1022
        }
1023 68
        if ($foreignKey->getOnUpdate()) {
1024 67
            $def .= " ON UPDATE {$foreignKey->getOnUpdate()}";
1025 67
        }
1026
1027 68
        return $def;
1028
    }
1029 68
1030 68
    /**
1031
     * {@inheritdoc}
1032
     */
1033
    public function createSchemaTable()
1034
    {
1035
        // Create the public/custom schema if it doesn't already exist
1036
        if ($this->hasSchema($this->getSchemaName()) === false) {
1037
            $this->createSchema($this->getSchemaName());
1038 68
        }
1039
1040 68
        $this->fetchAll(sprintf('SET search_path TO %s', $this->getSchemaName()));
1041 68
1042 68
        parent::createSchemaTable();
1043
    }
1044
1045
    /**
1046
     * Creates the specified schema.
1047
     *
1048
     * @param  string $schemaName Schema Name
1049
     * @return void
1050 68
     */
1051
    public function createSchema($schemaName = 'public')
1052 68
    {
1053
        $sql = sprintf('CREATE SCHEMA %s;', $this->quoteSchemaName($schemaName)); // from postgres 9.3 we can use "CREATE SCHEMA IF NOT EXISTS schema_name"
1054
        $this->execute($sql);
1055 68
    }
1056
1057 68
    /**
1058 68
     * Checks to see if a schema exists.
1059 68
     *
1060
     * @param string $schemaName Schema Name
1061
     * @return bool
1062
     */
1063
    public function hasSchema($schemaName)
1064
    {
1065
        $sql = sprintf(
1066
            "SELECT count(*)
1067
             FROM pg_namespace
1068 68
             WHERE nspname = '%s'",
1069
            $schemaName
1070 68
        );
1071 68
        $result = $this->fetchRow($sql);
1072 68
1073
        return $result['count'] > 0;
1074
    }
1075
1076
    /**
1077
     * Drops the specified schema table.
1078
     *
1079 68
     * @param string $schemaName Schema name
1080
     * @return void
1081 68
     */
1082 68
    public function dropSchema($schemaName)
1083 68
    {
1084 68
        $sql = sprintf("DROP SCHEMA IF EXISTS %s CASCADE;", $this->quoteSchemaName($schemaName));
1085
        $this->execute($sql);
1086
    }
1087
1088
    /**
1089
     * Drops all schemas.
1090
     *
1091 68
     * @return void
1092
     */
1093
    public function dropAllSchemas()
1094
    {
1095 68
        foreach ($this->getAllSchemas() as $schema) {
1096 68
            $this->dropSchema($schema);
1097 68
        }
1098 68
    }
1099 68
1100 68
    /**
1101 68
     * Returns schemas.
1102
     *
1103
     * @return array
1104
     */
1105
    public function getAllSchemas()
1106
    {
1107 73
        $sql = "SELECT schema_name
1108
                FROM information_schema.schemata
1109 73
                WHERE schema_name <> 'information_schema' AND schema_name !~ '^pg_'";
1110
        $items = $this->fetchAll($sql);
1111
        $schemaNames = [];
1112
        foreach ($items as $item) {
1113
            $schemaNames[] = $item['schema_name'];
1114
        }
1115 73
1116
        return $schemaNames;
1117
    }
1118 73
1119
    /**
1120
     * {@inheritdoc}
1121
     */
1122
    public function getColumnTypes()
1123
    {
1124
        return array_merge(parent::getColumnTypes(), ['json', 'jsonb', 'cidr', 'inet', 'macaddr', 'interval']);
1125
    }
1126
1127 14
    /**
1128
     * {@inheritdoc}
1129 14
     */
1130 1
    public function isValidColumnType(Column $column)
1131
    {
1132
        // If not a standard column type, maybe it is array type?
1133 13
        return (parent::isValidColumnType($column) || $this->isArrayType($column->getType()));
0 ignored issues
show
Bug introduced by
It seems like $column->getType() targeting Phinx\Db\Table\Column::getType() can also be of type object<Phinx\Util\Literal>; however, Phinx\Db\Adapter\PostgresAdapter::isArrayType() does only seem to accept string, maybe add an additional type check?

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

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

An additional type check may prevent trouble.

Loading history...
1134 13
    }
1135
1136
    /**
1137
     * Check if the given column is an array of a valid type.
1138
     *
1139
     * @param  string $columnType
1140
     * @return bool
1141
     */
1142 68
    protected function isArrayType($columnType)
1143
    {
1144 68
        if (!preg_match('/^([a-z]+)(?:\[\]){1,}$/', $columnType, $matches)) {
1145 68
            return false;
1146
        }
1147
1148
        $baseType = $matches[1];
1149
1150
        return in_array($baseType, $this->getColumnTypes());
1151 68
    }
1152
1153 68
    /**
1154
     * Gets the schema name.
1155
     *
1156
     * @return string
1157
     */
1158
    private function getSchemaName()
1159
    {
1160
        $options = $this->getOptions();
1161
1162
        return empty($options['schema']) ? 'public' : $options['schema'];
1163
    }
1164
1165
    /**
1166
     * {@inheritdoc}
1167
     */
1168
    public function castToBool($value)
1169
    {
1170
        return (bool)$value ? 'TRUE' : 'FALSE';
1171
    }
1172
}
1173