PostgreSqlPlatform.php 32.9 KB
Newer Older
1
<?php
2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
Benjamin Eberlei's avatar
Benjamin Eberlei committed
16
 * and is licensed under the MIT license. For more information, see
17 18
 * <http://www.doctrine-project.org>.
 */
19

20
namespace Doctrine\DBAL\Platforms;
21

Steve Müller's avatar
Steve Müller committed
22 23
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\ColumnDiff;
24
use Doctrine\DBAL\Schema\Identifier;
25
use Doctrine\DBAL\Schema\Index;
jeroendedauw's avatar
jeroendedauw committed
26
use Doctrine\DBAL\Schema\Sequence;
Benjamin Morel's avatar
Benjamin Morel committed
27
use Doctrine\DBAL\Schema\TableDiff;
Steve Müller's avatar
Steve Müller committed
28 29
use Doctrine\DBAL\Types\BinaryType;
use Doctrine\DBAL\Types\BlobType;
30

31 32 33
/**
 * PostgreSqlPlatform.
 *
Benjamin Morel's avatar
Benjamin Morel committed
34
 * @since  2.0
35 36
 * @author Roman Borschel <roman@code-factory.org>
 * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
37
 * @author Benjamin Eberlei <kontakt@beberlei.de>
Benjamin Morel's avatar
Benjamin Morel committed
38
 * @todo   Rename: PostgreSQLPlatform
39
 */
40
class PostgreSqlPlatform extends AbstractPlatform
41
{
42 43 44 45 46
    /**
     * @var bool
     */
    private $useBooleanTrueFalseStrings = true;

47 48 49 50
    /**
     * @var array PostgreSQL booleans literals
     */
    private $booleanLiterals = array(
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
        'true' => array(
            't',
            'true',
            'y',
            'yes',
            'on',
            '1'
        ),
        'false' => array(
            'f',
            'false',
            'n',
            'no',
            'off',
            '0'
        )
    );
68

69 70 71 72 73 74 75 76 77 78
    /**
     * PostgreSQL has different behavior with some drivers
     * with regard to how booleans have to be handled.
     *
     * Enables use of 'true'/'false' or otherwise 1 and 0 instead.
     *
     * @param bool $flag
     */
    public function setUseBooleanTrueFalseStrings($flag)
    {
79
        $this->useBooleanTrueFalseStrings = (bool) $flag;
80 81
    }

82
    /**
83
     * {@inheritDoc}
84
     */
85
    public function getSubstringExpression($value, $from, $length = null)
86
    {
87
        if ($length === null) {
88
            return 'SUBSTRING(' . $value . ' FROM ' . $from . ')';
89
        }
90

91
        return 'SUBSTRING(' . $value . ' FROM ' . $from . ' FOR ' . $length . ')';
92 93 94
    }

    /**
95
     * {@inheritDoc}
96 97 98 99 100 101 102
     */
    public function getNowExpression()
    {
        return 'LOCALTIMESTAMP(0)';
    }

    /**
103
     * {@inheritDoc}
104 105 106 107 108
     */
    public function getRegexpExpression()
    {
        return 'SIMILAR TO';
    }
109 110

    /**
111
     * {@inheritDoc}
112 113 114 115 116
     */
    public function getLocateExpression($str, $substr, $startPos = false)
    {
        if ($startPos !== false) {
            $str = $this->getSubstringExpression($str, $startPos);
117

118 119
            return 'CASE WHEN (POSITION('.$substr.' IN '.$str.') = 0) THEN 0 ELSE (POSITION('.$substr.' IN '.$str.') + '.($startPos-1).') END';
        }
120 121

        return 'POSITION('.$substr.' IN '.$str.')';
122
    }
123

124
    /**
125
     * {@inheritdoc}
126
     */
127
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
128
    {
129 130 131 132
        if (self::DATE_INTERVAL_UNIT_QUARTER === $unit) {
            $interval *= 3;
            $unit = self::DATE_INTERVAL_UNIT_MONTH;
        }
133

134
        return "(" . $date ." " . $operator . " (" . $interval . " || ' " . $unit . "')::interval)";
135 136
    }

137 138 139
    /**
     * {@inheritDoc}
     */
140
    public function getDateDiffExpression($date1, $date2)
141
    {
142
        return '(DATE(' . $date1 . ')-DATE(' . $date2 . '))';
143
    }
144

145
    /**
146
     * {@inheritDoc}
romanb's avatar
romanb committed
147 148 149 150 151
     */
    public function supportsSequences()
    {
        return true;
    }
152

153
    /**
154
     * {@inheritDoc}
155 156 157 158 159
     */
    public function supportsSchemas()
    {
        return true;
    }
160

161 162 163 164 165 166 167 168
    /**
     * {@inheritdoc}
     */
    public function getDefaultSchemaName()
    {
        return 'public';
    }

romanb's avatar
romanb committed
169
    /**
170
     * {@inheritDoc}
romanb's avatar
romanb committed
171 172 173 174 175
     */
    public function supportsIdentityColumns()
    {
        return true;
    }
176

177
    /**
178
     * {@inheritdoc}
179 180 181 182 183 184
     */
    public function supportsPartialIndexes()
    {
        return true;
    }

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    /**
     * {@inheritdoc}
     */
    public function usesSequenceEmulatedIdentityColumns()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function getIdentitySequenceName($tableName, $columnName)
    {
        return $tableName . '_' . $columnName . '_seq';
    }

201 202 203
    /**
     * {@inheritDoc}
     */
204 205 206 207
    public function supportsCommentOnStatement()
    {
        return true;
    }
208

romanb's avatar
romanb committed
209
    /**
210
     * {@inheritDoc}
romanb's avatar
romanb committed
211 212 213 214 215
     */
    public function prefersSequences()
    {
        return true;
    }
216

217 218 219 220 221 222 223 224
    /**
     * {@inheritDoc}
     */
    public function hasNativeGuidType()
    {
        return true;
    }

Benjamin Morel's avatar
Benjamin Morel committed
225 226 227
    /**
     * {@inheritDoc}
     */
228
    public function getListDatabasesSQL()
229 230 231
    {
        return 'SELECT datname FROM pg_database';
    }
232

233 234 235 236 237
    /**
     * {@inheritDoc}
     */
    public function getListNamespacesSQL()
    {
238 239 240 241
        return "SELECT schema_name AS nspname
                FROM   information_schema.schemata
                WHERE  schema_name NOT LIKE 'pg_%'
                AND    schema_name != 'information_schema'";
242 243
    }

Benjamin Morel's avatar
Benjamin Morel committed
244 245 246
    /**
     * {@inheritDoc}
     */
247
    public function getListSequencesSQL($database)
248
    {
249
        return "SELECT sequence_name AS relname,
x42p's avatar
x42p committed
250
                       sequence_schema AS schemaname
x42p's avatar
x42p committed
251
                FROM   information_schema.sequences
252
                WHERE  sequence_schema NOT LIKE 'pg_%'
x42p's avatar
x42p committed
253
                AND    sequence_schema != 'information_schema'";
254
    }
255

Benjamin Morel's avatar
Benjamin Morel committed
256 257 258
    /**
     * {@inheritDoc}
     */
259
    public function getListTablesSQL()
260
    {
261
        return "SELECT quote_ident(table_name) AS table_name,
x42p's avatar
x42p committed
262
                       table_schema AS schema_name
x42p's avatar
x42p committed
263
                FROM   information_schema.tables
264 265 266
                WHERE  table_schema NOT LIKE 'pg_%'
                AND    table_schema != 'information_schema'
                AND    table_name != 'geometry_columns'
267 268
                AND    table_name != 'spatial_ref_sys'
                AND    table_type != 'VIEW'";
269
    }
270

271 272 273
    /**
     * {@inheritDoc}
     */
274
    public function getListViewsSQL($database)
275
    {
276 277 278 279 280
        return 'SELECT quote_ident(table_name) AS viewname,
                       table_schema AS schemaname,
                       view_definition AS definition
                FROM   information_schema.views
                WHERE  view_definition IS NOT NULL';
281
    }
282

Benjamin Morel's avatar
Benjamin Morel committed
283 284 285
    /**
     * {@inheritDoc}
     */
286
    public function getListTableForeignKeysSQL($table, $database = null)
287
    {
288
        return "SELECT quote_ident(r.conname) as conname, pg_catalog.pg_get_constraintdef(r.oid, true) as condef
289 290 291 292
                  FROM pg_catalog.pg_constraint r
                  WHERE r.conrelid =
                  (
                      SELECT c.oid
293
                      FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n
294
                      WHERE " .$this->getTableWhereClause($table) ." AND n.oid = c.relnamespace
295 296 297 298
                  )
                  AND r.contype = 'f'";
    }

Benjamin Morel's avatar
Benjamin Morel committed
299 300 301
    /**
     * {@inheritDoc}
     */
302
    public function getCreateViewSQL($name, $sql)
303 304 305 306
    {
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
    }

Benjamin Morel's avatar
Benjamin Morel committed
307 308 309
    /**
     * {@inheritDoc}
     */
310
    public function getDropViewSQL($name)
311 312 313 314
    {
        return 'DROP VIEW '. $name;
    }

Benjamin Morel's avatar
Benjamin Morel committed
315 316 317
    /**
     * {@inheritDoc}
     */
318
    public function getListTableConstraintsSQL($table)
319
    {
320 321 322
        $table = new Identifier($table);
        $table = $table->getName();

323
        return "SELECT
324
                    quote_ident(relname) as relname
325 326 327 328 329
                FROM
                    pg_class
                WHERE oid IN (
                    SELECT indexrelid
                    FROM pg_index, pg_class
330
                    WHERE pg_class.relname = '$table'
331 332 333 334
                        AND pg_class.oid = pg_index.indrelid
                        AND (indisunique = 't' OR indisprimary = 't')
                        )";
    }
335

336
    /**
337 338
     * {@inheritDoc}
     *
339 340 341
     * @license New BSD License
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
     */
342
    public function getListTableIndexesSQL($table, $currentDatabase = null)
343
    {
344
        return "SELECT quote_ident(relname) as relname, pg_index.indisunique, pg_index.indisprimary,
345
                       pg_index.indkey, pg_index.indrelid,
346
                       pg_get_expr(indpred, indrelid) AS where
347 348
                 FROM pg_class, pg_index
                 WHERE oid IN (
349
                    SELECT indexrelid
350 351
                    FROM pg_index si, pg_class sc, pg_namespace sn
                    WHERE " . $this->getTableWhereClause($table, 'sc', 'sn')." AND sc.oid=si.indrelid AND sc.relnamespace = sn.oid
352
                 ) AND pg_index.indexrelid = oid";
353
    }
354

355 356 357 358
    /**
     * @param string $table
     * @param string $classAlias
     * @param string $namespaceAlias
359
     *
360 361
     * @return string
     */
362 363
    private function getTableWhereClause($table, $classAlias = 'c', $namespaceAlias = 'n')
    {
364
        $whereClause = $namespaceAlias.".nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast') AND ";
365 366
        if (strpos($table, ".") !== false) {
            list($schema, $table) = explode(".", $table);
367
            $schema = "'" . $schema . "'";
368
        } else {
369
            $schema = "ANY(string_to_array((select replace(replace(setting,'\"\$user\"',user),' ','') from pg_catalog.pg_settings where name = 'search_path'),','))";
370
        }
371 372 373

        $table = new Identifier($table);
        $whereClause .= "$classAlias.relname = '" . $table->getName() . "' AND $namespaceAlias.nspname = $schema";
374

375 376 377
        return $whereClause;
    }

Benjamin Morel's avatar
Benjamin Morel committed
378 379 380
    /**
     * {@inheritDoc}
     */
381
    public function getListTableColumnsSQL($table, $database = null)
382 383 384
    {
        return "SELECT
                    a.attnum,
385
                    quote_ident(a.attname) AS field,
386 387
                    t.typname AS type,
                    format_type(a.atttypid, a.atttypmod) AS complete_type,
388
                    (SELECT t1.typname FROM pg_catalog.pg_type t1 WHERE t1.oid = t.typbasetype) AS domain_type,
389 390
                    (SELECT format_type(t2.typbasetype, t2.typtypmod) FROM
                      pg_catalog.pg_type t2 WHERE t2.typtype = 'd' AND t2.oid = a.atttypid) AS domain_complete_type,
391 392 393 394 395 396 397
                    a.attnotnull AS isnotnull,
                    (SELECT 't'
                     FROM pg_index
                     WHERE c.oid = pg_index.indrelid
                        AND pg_index.indkey[0] = a.attnum
                        AND pg_index.indisprimary = 't'
                    ) AS pri,
398
                    (SELECT pg_get_expr(adbin, adrelid)
399 400 401
                     FROM pg_attrdef
                     WHERE c.oid = pg_attrdef.adrelid
                        AND pg_attrdef.adnum=a.attnum
402 403
                    ) AS default,
                    (SELECT pg_description.description
404
                        FROM pg_description WHERE pg_description.objoid = c.oid AND a.attnum = pg_description.objsubid
405 406
                    ) AS comment
                    FROM pg_attribute a, pg_class c, pg_type t, pg_namespace n
407
                    WHERE ".$this->getTableWhereClause($table, 'c', 'n') ."
408 409 410
                        AND a.attnum > 0
                        AND a.attrelid = c.oid
                        AND a.atttypid = t.oid
411
                        AND n.oid = c.relnamespace
412 413
                    ORDER BY a.attnum";
    }
414

415
    /**
416
     * {@inheritDoc}
417
     */
418
    public function getCreateDatabaseSQL($name)
419
    {
420
        return 'CREATE DATABASE ' . $name;
421
    }
422

423
    /**
424
     * {@inheritDoc}
425
     */
426
    public function getAdvancedForeignKeyOptionsSQL(\Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey)
427 428
    {
        $query = '';
429

430 431
        if ($foreignKey->hasOption('match')) {
            $query .= ' MATCH ' . $foreignKey->getOption('match');
432
        }
433

434
        $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
435

436
        if ($foreignKey->hasOption('deferrable') && $foreignKey->getOption('deferrable') !== false) {
437 438 439 440
            $query .= ' DEFERRABLE';
        } else {
            $query .= ' NOT DEFERRABLE';
        }
441

442 443 444
        if (($foreignKey->hasOption('feferred') && $foreignKey->getOption('feferred') !== false)
            || ($foreignKey->hasOption('deferred') && $foreignKey->getOption('deferred') !== false)
        ) {
445 446 447 448
            $query .= ' INITIALLY DEFERRED';
        } else {
            $query .= ' INITIALLY IMMEDIATE';
        }
449

450 451
        return $query;
    }
452

453
    /**
454
     * {@inheritDoc}
455
     */
456
    public function getAlterTableSQL(TableDiff $diff)
457
    {
458
        $sql = array();
459
        $commentsSQL = array();
460
        $columnSql = array();
461 462

        foreach ($diff->addedColumns as $column) {
463 464
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
465 466
            }

467
            $query = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
468
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
469 470 471 472

            $comment = $this->getColumnComment($column);

            if (null !== $comment && '' !== $comment) {
473 474 475 476 477
                $commentsSQL[] = $this->getCommentOnColumnSQL(
                    $diff->getName($this)->getQuotedName($this),
                    $column->getQuotedName($this),
                    $comment
                );
478
            }
479 480
        }

481
        foreach ($diff->removedColumns as $column) {
482 483
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
484 485
            }

486
            $query = 'DROP ' . $column->getQuotedName($this);
487
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
488 489
        }

490
        foreach ($diff->changedColumns as $columnDiff) {
491
            /** @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */
492 493
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
494 495
            }

Steve Müller's avatar
Steve Müller committed
496 497 498 499
            if ($this->isUnchangedBinaryColumn($columnDiff)) {
                continue;
            }

500
            $oldColumnName = $columnDiff->getOldColumnName()->getQuotedName($this);
501
            $column = $columnDiff->column;
502

503
            if ($columnDiff->hasChanged('type') || $columnDiff->hasChanged('precision') || $columnDiff->hasChanged('scale') || $columnDiff->hasChanged('fixed')) {
504
                $type = $column->getType();
505

506 507
                // here was a server version check before, but DBAL API does not support this anymore.
                $query = 'ALTER ' . $oldColumnName . ' TYPE ' . $type->getSqlDeclaration($column->toArray(), $this);
508
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
509
            }
510

511
            if ($columnDiff->hasChanged('default') || $columnDiff->hasChanged('type')) {
512 513 514 515
                $defaultClause = null === $column->getDefault()
                    ? ' DROP DEFAULT'
                    : ' SET' . $this->getDefaultValueDeclarationSQL($column->toArray());
                $query = 'ALTER ' . $oldColumnName . $defaultClause;
516
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
517
            }
518

519 520
            if ($columnDiff->hasChanged('notnull')) {
                $query = 'ALTER ' . $oldColumnName . ' ' . ($column->getNotNull() ? 'SET' : 'DROP') . ' NOT NULL';
521
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
522
            }
523

524 525 526
            if ($columnDiff->hasChanged('autoincrement')) {
                if ($column->getAutoincrement()) {
                    // add autoincrement
527
                    $seqName = $this->getIdentitySequenceName($diff->name, $oldColumnName);
528 529

                    $sql[] = "CREATE SEQUENCE " . $seqName;
530
                    $sql[] = "SELECT setval('" . $seqName . "', (SELECT MAX(" . $oldColumnName . ") FROM " . $diff->getName($this)->getQuotedName($this) . "))";
531
                    $query = "ALTER " . $oldColumnName . " SET DEFAULT nextval('" . $seqName . "')";
532
                    $sql[] = "ALTER TABLE " . $diff->getName($this)->getQuotedName($this) . " " . $query;
533 534 535
                } else {
                    // Drop autoincrement, but do NOT drop the sequence. It might be re-used by other tables or have
                    $query = "ALTER " . $oldColumnName . " " . "DROP DEFAULT";
536
                    $sql[] = "ALTER TABLE " . $diff->getName($this)->getQuotedName($this) . " " . $query;
537 538
                }
            }
539

540 541
            if ($columnDiff->hasChanged('comment')) {
                $commentsSQL[] = $this->getCommentOnColumnSQL(
542 543
                    $diff->getName($this)->getQuotedName($this),
                    $column->getQuotedName($this),
544 545
                    $this->getColumnComment($column)
                );
546
            }
547 548

            if ($columnDiff->hasChanged('length')) {
549
                $query = 'ALTER ' . $oldColumnName . ' TYPE ' . $column->getType()->getSqlDeclaration($column->toArray(), $this);
550
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
551
            }
552 553
        }

554
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
555 556
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
557 558
            }

559 560
            $oldColumnName = new Identifier($oldColumnName);

561
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) .
562
                ' RENAME COLUMN ' . $oldColumnName->getQuotedName($this) . ' TO ' . $column->getQuotedName($this);
563 564
        }

565 566
        $tableSql = array();

567
        if ( ! $this->onSchemaAlterTable($diff, $tableSql)) {
568 569
            $sql = array_merge($sql, $commentsSQL);

570
            if ($diff->newName !== false) {
571
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' RENAME TO ' . $diff->getNewName()->getQuotedName($this);
572 573
            }

574 575 576 577 578
            $sql = array_merge(
                $this->getPreAlterTableIndexForeignKeySQL($diff),
                $sql,
                $this->getPostAlterTableIndexForeignKeySQL($diff)
            );
579 580
        }

581
        return array_merge($sql, $tableSql, $columnSql);
582
    }
583

Steve Müller's avatar
Steve Müller committed
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
    /**
     * Checks whether a given column diff is a logically unchanged binary type column.
     *
     * Used to determine whether a column alteration for a binary type column can be skipped.
     * Doctrine's {@link \Doctrine\DBAL\Types\BinaryType} and {@link \Doctrine\DBAL\Types\BlobType}
     * are mapped to the same database column type on this platform as this platform
     * does not have a native VARBINARY/BINARY column type. Therefore the {@link \Doctrine\DBAL\Schema\Comparator}
     * might detect differences for binary type columns which do not have to be propagated
     * to database as there actually is no difference at database level.
     *
     * @param ColumnDiff $columnDiff The column diff to check against.
     *
     * @return boolean True if the given column diff is an unchanged binary type column, false otherwise.
     */
    private function isUnchangedBinaryColumn(ColumnDiff $columnDiff)
    {
        $columnType = $columnDiff->column->getType();

        if ( ! $columnType instanceof BinaryType && ! $columnType instanceof BlobType) {
            return false;
        }

        $fromColumn = $columnDiff->fromColumn instanceof Column ? $columnDiff->fromColumn : null;

        if ($fromColumn) {
            $fromColumnType = $fromColumn->getType();

            if ( ! $fromColumnType instanceof BinaryType && ! $fromColumnType instanceof BlobType) {
                return false;
            }

            return count(array_diff($columnDiff->changedProperties, array('type', 'length', 'fixed'))) === 0;
        }

        if ($columnDiff->hasChanged('type')) {
            return false;
        }

        return count(array_diff($columnDiff->changedProperties, array('length', 'fixed'))) === 0;
    }

625 626 627 628 629
    /**
     * {@inheritdoc}
     */
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
    {
630 631 632 633 634
        if (strpos($tableName, '.') !== false) {
            list($schema) = explode('.', $tableName);
            $oldIndexName = $schema . '.' . $oldIndexName;
        }

635 636 637
        return array('ALTER INDEX ' . $oldIndexName . ' RENAME TO ' . $index->getQuotedName($this));
    }

638 639 640 641 642
    /**
     * {@inheritdoc}
     */
    public function getCommentOnColumnSQL($tableName, $columnName, $comment)
    {
643 644
        $tableName = new Identifier($tableName);
        $columnName = new Identifier($columnName);
645
        $comment = $comment === null ? 'NULL' : $this->quoteStringLiteral($comment);
646

647 648
        return "COMMENT ON COLUMN " . $tableName->getQuotedName($this) . "." . $columnName->getQuotedName($this) .
            " IS $comment";
649 650
    }

651
    /**
652
     * {@inheritDoc}
653
     */
jeroendedauw's avatar
jeroendedauw committed
654
    public function getCreateSequenceSQL(Sequence $sequence)
655
    {
656
        return 'CREATE SEQUENCE ' . $sequence->getQuotedName($this) .
657
               ' INCREMENT BY ' . $sequence->getAllocationSize() .
658
               ' MINVALUE ' . $sequence->getInitialValue() .
659 660
               ' START ' . $sequence->getInitialValue() .
               $this->getSequenceCacheSQL($sequence);
661
    }
662

663 664 665
    /**
     * {@inheritDoc}
     */
jeroendedauw's avatar
jeroendedauw committed
666
    public function getAlterSequenceSQL(Sequence $sequence)
667
    {
668
        return 'ALTER SEQUENCE ' . $sequence->getQuotedName($this) .
669 670 671 672 673 674 675
               ' INCREMENT BY ' . $sequence->getAllocationSize() .
               $this->getSequenceCacheSQL($sequence);
    }

    /**
     * Cache definition for sequences
     *
jeroendedauw's avatar
jeroendedauw committed
676 677
     * @param Sequence $sequence
     *
678 679
     * @return string
     */
jeroendedauw's avatar
jeroendedauw committed
680
    private function getSequenceCacheSQL(Sequence $sequence)
681 682 683 684 685 686
    {
        if ($sequence->getCache() > 1) {
            return ' CACHE ' . $sequence->getCache();
        }

        return '';
687
    }
688

689
    /**
690
     * {@inheritDoc}
691
     */
692
    public function getDropSequenceSQL($sequence)
693
    {
jeroendedauw's avatar
jeroendedauw committed
694
        if ($sequence instanceof Sequence) {
695
            $sequence = $sequence->getQuotedName($this);
696
        }
697

698
        return 'DROP SEQUENCE ' . $sequence . ' CASCADE';
699
    }
700

701 702 703 704 705 706 707 708
    /**
     * {@inheritDoc}
     */
    public function getCreateSchemaSQL($schemaName)
    {
        return 'CREATE SCHEMA ' . $schemaName;
    }

709
    /**
710
     * {@inheritDoc}
711
     */
712
    public function getDropForeignKeySQL($foreignKey, $table)
713
    {
714
        return $this->getDropConstraintSQL($foreignKey, $table);
715
    }
716

717
    /**
718
     * {@inheritDoc}
719
     */
720
    protected function _getCreateTableSQL($tableName, array $columns, array $options = array())
721
    {
722
        $queryFields = $this->getColumnDeclarationListSQL($columns);
723 724

        if (isset($options['primary']) && ! empty($options['primary'])) {
725
            $keyColumns = array_unique(array_values($options['primary']));
726 727 728
            $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
        }

729
        $query = 'CREATE TABLE ' . $tableName . ' (' . $queryFields . ')';
730 731 732 733

        $sql[] = $query;

        if (isset($options['indexes']) && ! empty($options['indexes'])) {
734
            foreach ($options['indexes'] as $index) {
735
                $sql[] = $this->getCreateIndexSQL($index, $tableName);
736 737 738 739
            }
        }

        if (isset($options['foreignKeys'])) {
740
            foreach ((array) $options['foreignKeys'] as $definition) {
741
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
742 743 744 745 746
            }
        }

        return $sql;
    }
747

748 749 750 751 752 753 754 755 756 757 758
    /**
     * Converts a single boolean value.
     *
     * First converts the value to its native PHP boolean type
     * and passes it to the given callback function to be reconverted
     * into any custom representation.
     *
     * @param mixed    $value    The value to convert.
     * @param callable $callback The callback function to use for converting the real boolean value.
     *
     * @return mixed
jeroendedauw's avatar
jeroendedauw committed
759
     * @throws \UnexpectedValueException
760 761 762 763
     */
    private function convertSingleBooleanValue($value, $callback)
    {
        if (null === $value) {
764
            return $callback(null);
765 766 767 768 769 770
        }

        if (is_bool($value) || is_numeric($value)) {
            return $callback($value ? true : false);
        }

771 772 773 774 775 776 777 778 779 780 781 782 783
        if (!is_string($value)) {
            return $callback(true);
        }

        /**
         * Better safe than sorry: http://php.net/in_array#106319
         */
        if (in_array(trim(strtolower($value)), $this->booleanLiterals['false'], true)) {
            return $callback(false);
        }

        if (in_array(trim(strtolower($value)), $this->booleanLiterals['true'], true)) {
            return $callback(true);
784 785
        }

786
        throw new \UnexpectedValueException("Unrecognized boolean literal '${value}'");
787 788 789 790 791 792 793 794 795
    }

    /**
     * Converts one or multiple boolean values.
     *
     * First converts the value(s) to their native PHP boolean type
     * and passes them to the given callback function to be reconverted
     * into any custom representation.
     *
796
     * @param mixed    $item     The value(s) to convert.
797
     * @param callable $callback The callback function to use for converting the real boolean value(s).
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
     *
     * @return mixed
     */
    private function doConvertBooleans($item, $callback)
    {
        if (is_array($item)) {
            foreach ($item as $key => $value) {
                $item[$key] = $this->convertSingleBooleanValue($value, $callback);
            }

            return $item;
        }

        return $this->convertSingleBooleanValue($item, $callback);
    }

814
    /**
815
     * {@inheritDoc}
816
     *
817
     * Postgres wants boolean values converted to the strings 'true'/'false'.
818
     */
819
    public function convertBooleans($item)
820
    {
821
        if ( ! $this->useBooleanTrueFalseStrings) {
822
            return parent::convertBooleans($item);
823 824
        }

825 826 827
        return $this->doConvertBooleans(
            $item,
            function ($boolean) {
828
                if (null === $boolean) {
829
                    return 'NULL';
830
                }
831

832
                return true === $boolean ? 'true' : 'false';
833
            }
834
        );
835 836 837 838 839
    }

    /**
     * {@inheritDoc}
     */
840
    public function convertBooleansToDatabaseValue($item)
841
    {
842
        if ( ! $this->useBooleanTrueFalseStrings) {
843
            return parent::convertBooleansToDatabaseValue($item);
844 845
        }

846 847 848
        return $this->doConvertBooleans(
            $item,
            function ($boolean) {
849
                return null === $boolean ? null : (int) $boolean;
850 851
            }
        );
852
    }
853

854
    /**
855 856
     * {@inheritDoc}
     */
857 858
    public function convertFromBoolean($item)
    {
859
        if (in_array(strtolower($item), $this->booleanLiterals['false'], true)) {
860
            return false;
861 862
        }

863
        return parent::convertFromBoolean($item);
864
    }
865

Benjamin Morel's avatar
Benjamin Morel committed
866 867 868
    /**
     * {@inheritDoc}
     */
869
    public function getSequenceNextValSQL($sequenceName)
870 871 872
    {
        return "SELECT NEXTVAL('" . $sequenceName . "')";
    }
873

874 875 876
    /**
     * {@inheritDoc}
     */
877
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
878 879
    {
        return 'SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL '
880
                . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
881
    }
882

883
    /**
884
     * {@inheritDoc}
885
     */
886
    public function getBooleanTypeDeclarationSQL(array $field)
887 888 889
    {
        return 'BOOLEAN';
    }
890 891

    /**
892
     * {@inheritDoc}
893
     */
894
    public function getIntegerTypeDeclarationSQL(array $field)
895 896 897 898
    {
        if ( ! empty($field['autoincrement'])) {
            return 'SERIAL';
        }
899

900 901 902 903
        return 'INT';
    }

    /**
904
     * {@inheritDoc}
905
     */
906
    public function getBigIntTypeDeclarationSQL(array $field)
907 908 909 910
    {
        if ( ! empty($field['autoincrement'])) {
            return 'BIGSERIAL';
        }
911

912 913 914 915
        return 'BIGINT';
    }

    /**
916
     * {@inheritDoc}
917
     */
918
    public function getSmallIntTypeDeclarationSQL(array $field)
919 920 921 922
    {
        return 'SMALLINT';
    }

rivaros's avatar
rivaros committed
923
    /**
924
     * {@inheritDoc}
rivaros's avatar
rivaros committed
925
     */
926
    public function getGuidTypeDeclarationSQL(array $field)
rivaros's avatar
rivaros committed
927 928 929 930
    {
        return 'UUID';
    }

931
    /**
932
     * {@inheritDoc}
933
     */
934
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
935 936 937 938 939
    {
        return 'TIMESTAMP(0) WITHOUT TIME ZONE';
    }

    /**
940
     * {@inheritDoc}
941
     */
942
    public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration)
943
    {
944 945
        return 'TIMESTAMP(0) WITH TIME ZONE';
    }
946

947
    /**
948
     * {@inheritDoc}
949
     */
950
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
951 952
    {
        return 'DATE';
953 954
    }

955
    /**
956
     * {@inheritDoc}
957
     */
958
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
959
    {
960
        return 'TIME(0) WITHOUT TIME ZONE';
961 962
    }

963 964 965 966 967 968 969 970
    /**
     * {@inheritDoc}
     */
    public function getGuidExpression()
    {
        return 'UUID_GENERATE_V4()';
    }

971
    /**
972
     * {@inheritDoc}
973
     */
974
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
975 976 977 978 979
    {
        return '';
    }

    /**
980
     * {@inheritDoc}
981
     */
982
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
983 984
    {
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
985
                : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)');
986
    }
987

Steve Müller's avatar
Steve Müller committed
988 989 990 991 992 993 994 995
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
        return 'BYTEA';
    }

996 997 998
    /**
     * {@inheritDoc}
     */
999
    public function getClobTypeDeclarationSQL(array $field)
1000 1001 1002
    {
        return 'TEXT';
    }
1003 1004

    /**
1005
     * {@inheritDoc}
1006 1007 1008 1009 1010
     */
    public function getName()
    {
        return 'postgresql';
    }
1011

1012
    /**
1013
     * {@inheritDoc}
1014
     *
1015 1016
     * PostgreSQL returns all column names in SQL result sets in lowercase.
     */
1017
    public function getSQLResultCasing($column)
1018 1019 1020
    {
        return strtolower($column);
    }
1021

1022 1023 1024
    /**
     * {@inheritDoc}
     */
1025
    public function getDateTimeTzFormatString()
1026
    {
1027 1028
        return 'Y-m-d H:i:sO';
    }
1029 1030

    /**
1031
     * {@inheritDoc}
1032
     */
1033
    public function getEmptyIdentityInsertSQL($quotedTableName, $quotedIdentifierColumnName)
1034 1035 1036
    {
        return 'INSERT INTO ' . $quotedTableName . ' (' . $quotedIdentifierColumnName . ') VALUES (DEFAULT)';
    }
1037 1038

    /**
1039
     * {@inheritDoc}
1040
     */
1041
    public function getTruncateTableSQL($tableName, $cascade = false)
1042
    {
1043
        return 'TRUNCATE '.$tableName.' '.(($cascade)?'CASCADE':'');
1044
    }
1045

1046 1047 1048
    /**
     * {@inheritDoc}
     */
1049 1050 1051 1052
    public function getReadLockSQL()
    {
        return 'FOR SHARE';
    }
1053

1054 1055 1056
    /**
     * {@inheritDoc}
     */
1057 1058 1059
    protected function initializeDoctrineTypeMappings()
    {
        $this->doctrineTypeMapping = array(
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
            'smallint'      => 'smallint',
            'int2'          => 'smallint',
            'serial'        => 'integer',
            'serial4'       => 'integer',
            'int'           => 'integer',
            'int4'          => 'integer',
            'integer'       => 'integer',
            'bigserial'     => 'bigint',
            'serial8'       => 'bigint',
            'bigint'        => 'bigint',
            'int8'          => 'bigint',
            'bool'          => 'boolean',
            'boolean'       => 'boolean',
            'text'          => 'text',
            'varchar'       => 'string',
            'interval'      => 'string',
            '_varchar'      => 'string',
            'char'          => 'string',
            'bpchar'        => 'string',
1079
            'inet'          => 'string',
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
            'date'          => 'date',
            'datetime'      => 'datetime',
            'timestamp'     => 'datetime',
            'timestamptz'   => 'datetimetz',
            'time'          => 'time',
            'timetz'        => 'time',
            'float'         => 'float',
            'float4'        => 'float',
            'float8'        => 'float',
            'double'        => 'float',
            'double precision' => 'float',
            'real'          => 'float',
            'decimal'       => 'decimal',
            'money'         => 'decimal',
            'numeric'       => 'decimal',
            'year'          => 'date',
1096
            'uuid'          => 'guid',
1097
            'bytea'         => 'blob',
1098 1099
        );
    }
1100

1101 1102 1103
    /**
     * {@inheritDoc}
     */
1104 1105 1106 1107
    public function getVarcharMaxLength()
    {
        return 65535;
    }
1108

Steve Müller's avatar
Steve Müller committed
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
    /**
     * {@inheritdoc}
     */
    public function getBinaryMaxLength()
    {
        return 0;
    }

    /**
     * {@inheritdoc}
     */
    public function getBinaryDefaultLength()
    {
        return 0;
    }

1125 1126 1127
    /**
     * {@inheritDoc}
     */
1128 1129 1130 1131
    protected function getReservedKeywordsClass()
    {
        return 'Doctrine\DBAL\Platforms\Keywords\PostgreSQLKeywords';
    }
1132 1133

    /**
1134
     * {@inheritDoc}
1135 1136 1137 1138 1139
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'BYTEA';
    }
1140
}