PostgreSqlPlatform.php 34.1 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 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
    /**
     * Returns the SQL statement for disallowing new connections on the given database.
     *
     * This is useful to force DROP DATABASE operations which could fail because of active connections.
     *
     * @param string $database The name of the database to disallow new connections for.
     *
     * @return string
     */
    public function getDisallowDatabaseConnectionsSQL($database)
    {
        return "UPDATE pg_database SET datallowconn = 'false' WHERE datname = '$database'";
    }

    /**
     * Returns the SQL statement for closing currently active connections on the given database.
     *
     * This is useful to force DROP DATABASE operations which could fail because of active connections.
     *
     * @param string $database The name of the database to close currently active connections for.
     *
     * @return string
     */
    public function getCloseActiveDatabaseConnectionsSQL($database)
    {
        return "SELECT pg_terminate_backend(procpid) FROM pg_stat_activity WHERE datname = '$database'";
    }

451
    /**
452
     * {@inheritDoc}
453
     */
454
    public function getAdvancedForeignKeyOptionsSQL(\Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey)
455 456
    {
        $query = '';
457

458 459
        if ($foreignKey->hasOption('match')) {
            $query .= ' MATCH ' . $foreignKey->getOption('match');
460
        }
461

462
        $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
463

464
        if ($foreignKey->hasOption('deferrable') && $foreignKey->getOption('deferrable') !== false) {
465 466 467 468
            $query .= ' DEFERRABLE';
        } else {
            $query .= ' NOT DEFERRABLE';
        }
469

470 471 472
        if (($foreignKey->hasOption('feferred') && $foreignKey->getOption('feferred') !== false)
            || ($foreignKey->hasOption('deferred') && $foreignKey->getOption('deferred') !== false)
        ) {
473 474 475 476
            $query .= ' INITIALLY DEFERRED';
        } else {
            $query .= ' INITIALLY IMMEDIATE';
        }
477

478 479
        return $query;
    }
480

481
    /**
482
     * {@inheritDoc}
483
     */
484
    public function getAlterTableSQL(TableDiff $diff)
485
    {
486
        $sql = array();
487
        $commentsSQL = array();
488
        $columnSql = array();
489 490

        foreach ($diff->addedColumns as $column) {
491 492
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
493 494
            }

495
            $query = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
496
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
497 498 499 500

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

            if (null !== $comment && '' !== $comment) {
501 502 503 504 505
                $commentsSQL[] = $this->getCommentOnColumnSQL(
                    $diff->getName($this)->getQuotedName($this),
                    $column->getQuotedName($this),
                    $comment
                );
506
            }
507 508
        }

509
        foreach ($diff->removedColumns as $column) {
510 511
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
512 513
            }

514
            $query = 'DROP ' . $column->getQuotedName($this);
515
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
516 517
        }

518
        foreach ($diff->changedColumns as $columnDiff) {
519
            /** @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */
520 521
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
522 523
            }

Steve Müller's avatar
Steve Müller committed
524 525 526 527
            if ($this->isUnchangedBinaryColumn($columnDiff)) {
                continue;
            }

528
            $oldColumnName = $columnDiff->getOldColumnName()->getQuotedName($this);
529
            $column = $columnDiff->column;
530

531
            if ($columnDiff->hasChanged('type') || $columnDiff->hasChanged('precision') || $columnDiff->hasChanged('scale') || $columnDiff->hasChanged('fixed')) {
532
                $type = $column->getType();
533

534
                // here was a server version check before, but DBAL API does not support this anymore.
535
                $query = 'ALTER ' . $oldColumnName . ' TYPE ' . $type->getSQLDeclaration($column->toArray(), $this);
536
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
537
            }
538

539
            if ($columnDiff->hasChanged('default') || $columnDiff->hasChanged('type')) {
540 541 542 543
                $defaultClause = null === $column->getDefault()
                    ? ' DROP DEFAULT'
                    : ' SET' . $this->getDefaultValueDeclarationSQL($column->toArray());
                $query = 'ALTER ' . $oldColumnName . $defaultClause;
544
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
545
            }
546

547
            if ($columnDiff->hasChanged('notnull')) {
548
                $query = 'ALTER ' . $oldColumnName . ' ' . ($column->getNotnull() ? 'SET' : 'DROP') . ' NOT NULL';
549
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
550
            }
551

552 553 554
            if ($columnDiff->hasChanged('autoincrement')) {
                if ($column->getAutoincrement()) {
                    // add autoincrement
555
                    $seqName = $this->getIdentitySequenceName($diff->name, $oldColumnName);
556 557

                    $sql[] = "CREATE SEQUENCE " . $seqName;
558
                    $sql[] = "SELECT setval('" . $seqName . "', (SELECT MAX(" . $oldColumnName . ") FROM " . $diff->getName($this)->getQuotedName($this) . "))";
559
                    $query = "ALTER " . $oldColumnName . " SET DEFAULT nextval('" . $seqName . "')";
560
                    $sql[] = "ALTER TABLE " . $diff->getName($this)->getQuotedName($this) . " " . $query;
561 562 563
                } else {
                    // Drop autoincrement, but do NOT drop the sequence. It might be re-used by other tables or have
                    $query = "ALTER " . $oldColumnName . " " . "DROP DEFAULT";
564
                    $sql[] = "ALTER TABLE " . $diff->getName($this)->getQuotedName($this) . " " . $query;
565 566
                }
            }
567

568 569
            if ($columnDiff->hasChanged('comment')) {
                $commentsSQL[] = $this->getCommentOnColumnSQL(
570 571
                    $diff->getName($this)->getQuotedName($this),
                    $column->getQuotedName($this),
572 573
                    $this->getColumnComment($column)
                );
574
            }
575 576

            if ($columnDiff->hasChanged('length')) {
577
                $query = 'ALTER ' . $oldColumnName . ' TYPE ' . $column->getType()->getSQLDeclaration($column->toArray(), $this);
578
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
579
            }
580 581
        }

582
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
583 584
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
585 586
            }

587 588
            $oldColumnName = new Identifier($oldColumnName);

589
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) .
590
                ' RENAME COLUMN ' . $oldColumnName->getQuotedName($this) . ' TO ' . $column->getQuotedName($this);
591 592
        }

593 594
        $tableSql = array();

595
        if ( ! $this->onSchemaAlterTable($diff, $tableSql)) {
596 597
            $sql = array_merge($sql, $commentsSQL);

598
            if ($diff->newName !== false) {
599
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' RENAME TO ' . $diff->getNewName()->getQuotedName($this);
600 601
            }

602 603 604 605 606
            $sql = array_merge(
                $this->getPreAlterTableIndexForeignKeySQL($diff),
                $sql,
                $this->getPostAlterTableIndexForeignKeySQL($diff)
            );
607 608
        }

609
        return array_merge($sql, $tableSql, $columnSql);
610
    }
611

Steve Müller's avatar
Steve Müller committed
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
    /**
     * 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;
    }

653 654 655 656 657
    /**
     * {@inheritdoc}
     */
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
    {
658 659 660 661 662
        if (strpos($tableName, '.') !== false) {
            list($schema) = explode('.', $tableName);
            $oldIndexName = $schema . '.' . $oldIndexName;
        }

663 664 665
        return array('ALTER INDEX ' . $oldIndexName . ' RENAME TO ' . $index->getQuotedName($this));
    }

666 667 668 669 670
    /**
     * {@inheritdoc}
     */
    public function getCommentOnColumnSQL($tableName, $columnName, $comment)
    {
671 672
        $tableName = new Identifier($tableName);
        $columnName = new Identifier($columnName);
673
        $comment = $comment === null ? 'NULL' : $this->quoteStringLiteral($comment);
674

675 676
        return "COMMENT ON COLUMN " . $tableName->getQuotedName($this) . "." . $columnName->getQuotedName($this) .
            " IS $comment";
677 678
    }

679
    /**
680
     * {@inheritDoc}
681
     */
jeroendedauw's avatar
jeroendedauw committed
682
    public function getCreateSequenceSQL(Sequence $sequence)
683
    {
684
        return 'CREATE SEQUENCE ' . $sequence->getQuotedName($this) .
685
               ' INCREMENT BY ' . $sequence->getAllocationSize() .
686
               ' MINVALUE ' . $sequence->getInitialValue() .
687 688
               ' START ' . $sequence->getInitialValue() .
               $this->getSequenceCacheSQL($sequence);
689
    }
690

691 692 693
    /**
     * {@inheritDoc}
     */
jeroendedauw's avatar
jeroendedauw committed
694
    public function getAlterSequenceSQL(Sequence $sequence)
695
    {
696
        return 'ALTER SEQUENCE ' . $sequence->getQuotedName($this) .
697 698 699 700 701 702 703
               ' INCREMENT BY ' . $sequence->getAllocationSize() .
               $this->getSequenceCacheSQL($sequence);
    }

    /**
     * Cache definition for sequences
     *
jeroendedauw's avatar
jeroendedauw committed
704 705
     * @param Sequence $sequence
     *
706 707
     * @return string
     */
jeroendedauw's avatar
jeroendedauw committed
708
    private function getSequenceCacheSQL(Sequence $sequence)
709 710 711 712 713 714
    {
        if ($sequence->getCache() > 1) {
            return ' CACHE ' . $sequence->getCache();
        }

        return '';
715
    }
716

717
    /**
718
     * {@inheritDoc}
719
     */
720
    public function getDropSequenceSQL($sequence)
721
    {
jeroendedauw's avatar
jeroendedauw committed
722
        if ($sequence instanceof Sequence) {
723
            $sequence = $sequence->getQuotedName($this);
724
        }
725

726
        return 'DROP SEQUENCE ' . $sequence . ' CASCADE';
727
    }
728

729 730 731 732 733 734 735 736
    /**
     * {@inheritDoc}
     */
    public function getCreateSchemaSQL($schemaName)
    {
        return 'CREATE SCHEMA ' . $schemaName;
    }

737
    /**
738
     * {@inheritDoc}
739
     */
740
    public function getDropForeignKeySQL($foreignKey, $table)
741
    {
742
        return $this->getDropConstraintSQL($foreignKey, $table);
743
    }
744

745
    /**
746
     * {@inheritDoc}
747
     */
748
    protected function _getCreateTableSQL($tableName, array $columns, array $options = array())
749
    {
750
        $queryFields = $this->getColumnDeclarationListSQL($columns);
751 752

        if (isset($options['primary']) && ! empty($options['primary'])) {
753
            $keyColumns = array_unique(array_values($options['primary']));
754 755 756
            $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
        }

757
        $query = 'CREATE TABLE ' . $tableName . ' (' . $queryFields . ')';
758 759 760 761

        $sql[] = $query;

        if (isset($options['indexes']) && ! empty($options['indexes'])) {
762
            foreach ($options['indexes'] as $index) {
763
                $sql[] = $this->getCreateIndexSQL($index, $tableName);
764 765 766 767
            }
        }

        if (isset($options['foreignKeys'])) {
768
            foreach ((array) $options['foreignKeys'] as $definition) {
769
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
770 771 772 773 774
            }
        }

        return $sql;
    }
775

776 777 778 779 780 781 782 783 784 785 786
    /**
     * 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
787
     * @throws \UnexpectedValueException
788 789 790 791
     */
    private function convertSingleBooleanValue($value, $callback)
    {
        if (null === $value) {
792
            return $callback(null);
793 794 795 796 797 798
        }

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

799 800 801 802 803 804 805 806 807 808 809 810 811
        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);
812 813
        }

814
        throw new \UnexpectedValueException("Unrecognized boolean literal '${value}'");
815 816 817 818 819 820 821 822 823
    }

    /**
     * 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.
     *
824
     * @param mixed    $item     The value(s) to convert.
825
     * @param callable $callback The callback function to use for converting the real boolean value(s).
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
     *
     * @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);
    }

842
    /**
843
     * {@inheritDoc}
844
     *
845
     * Postgres wants boolean values converted to the strings 'true'/'false'.
846
     */
847
    public function convertBooleans($item)
848
    {
849
        if ( ! $this->useBooleanTrueFalseStrings) {
850
            return parent::convertBooleans($item);
851 852
        }

853 854 855
        return $this->doConvertBooleans(
            $item,
            function ($boolean) {
856
                if (null === $boolean) {
857
                    return 'NULL';
858
                }
859

860
                return true === $boolean ? 'true' : 'false';
861
            }
862
        );
863 864 865 866 867
    }

    /**
     * {@inheritDoc}
     */
868
    public function convertBooleansToDatabaseValue($item)
869
    {
870
        if ( ! $this->useBooleanTrueFalseStrings) {
871
            return parent::convertBooleansToDatabaseValue($item);
872 873
        }

874 875 876
        return $this->doConvertBooleans(
            $item,
            function ($boolean) {
877
                return null === $boolean ? null : (int) $boolean;
878 879
            }
        );
880
    }
881

882
    /**
883 884
     * {@inheritDoc}
     */
885 886
    public function convertFromBoolean($item)
    {
887
        if (in_array(strtolower($item), $this->booleanLiterals['false'], true)) {
888
            return false;
889 890
        }

891
        return parent::convertFromBoolean($item);
892
    }
893

Benjamin Morel's avatar
Benjamin Morel committed
894 895 896
    /**
     * {@inheritDoc}
     */
897
    public function getSequenceNextValSQL($sequenceName)
898 899 900
    {
        return "SELECT NEXTVAL('" . $sequenceName . "')";
    }
901

902 903 904
    /**
     * {@inheritDoc}
     */
905
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
906 907
    {
        return 'SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL '
908
                . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
909
    }
910

911
    /**
912
     * {@inheritDoc}
913
     */
914
    public function getBooleanTypeDeclarationSQL(array $field)
915 916 917
    {
        return 'BOOLEAN';
    }
918 919

    /**
920
     * {@inheritDoc}
921
     */
922
    public function getIntegerTypeDeclarationSQL(array $field)
923 924 925 926
    {
        if ( ! empty($field['autoincrement'])) {
            return 'SERIAL';
        }
927

928 929 930 931
        return 'INT';
    }

    /**
932
     * {@inheritDoc}
933
     */
934
    public function getBigIntTypeDeclarationSQL(array $field)
935 936 937 938
    {
        if ( ! empty($field['autoincrement'])) {
            return 'BIGSERIAL';
        }
939

940 941 942 943
        return 'BIGINT';
    }

    /**
944
     * {@inheritDoc}
945
     */
946
    public function getSmallIntTypeDeclarationSQL(array $field)
947 948 949 950
    {
        return 'SMALLINT';
    }

rivaros's avatar
rivaros committed
951
    /**
952
     * {@inheritDoc}
rivaros's avatar
rivaros committed
953
     */
954
    public function getGuidTypeDeclarationSQL(array $field)
rivaros's avatar
rivaros committed
955 956 957 958
    {
        return 'UUID';
    }

959
    /**
960
     * {@inheritDoc}
961
     */
962
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
963 964 965 966 967
    {
        return 'TIMESTAMP(0) WITHOUT TIME ZONE';
    }

    /**
968
     * {@inheritDoc}
969
     */
970
    public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration)
971
    {
972 973
        return 'TIMESTAMP(0) WITH TIME ZONE';
    }
974

975
    /**
976
     * {@inheritDoc}
977
     */
978
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
979 980
    {
        return 'DATE';
981 982
    }

983
    /**
984
     * {@inheritDoc}
985
     */
986
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
987
    {
988
        return 'TIME(0) WITHOUT TIME ZONE';
989 990
    }

991 992 993 994 995 996 997 998
    /**
     * {@inheritDoc}
     */
    public function getGuidExpression()
    {
        return 'UUID_GENERATE_V4()';
    }

999
    /**
1000
     * {@inheritDoc}
1001
     */
1002
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
1003 1004 1005 1006 1007
    {
        return '';
    }

    /**
1008
     * {@inheritDoc}
1009
     */
1010
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
1011 1012
    {
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
1013
                : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)');
1014
    }
1015

Steve Müller's avatar
Steve Müller committed
1016 1017 1018 1019 1020 1021 1022 1023
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
        return 'BYTEA';
    }

1024 1025 1026
    /**
     * {@inheritDoc}
     */
1027
    public function getClobTypeDeclarationSQL(array $field)
1028 1029 1030
    {
        return 'TEXT';
    }
1031 1032

    /**
1033
     * {@inheritDoc}
1034 1035 1036 1037 1038
     */
    public function getName()
    {
        return 'postgresql';
    }
1039

1040
    /**
1041
     * {@inheritDoc}
1042
     *
1043 1044
     * PostgreSQL returns all column names in SQL result sets in lowercase.
     */
1045
    public function getSQLResultCasing($column)
1046 1047 1048
    {
        return strtolower($column);
    }
1049

1050 1051 1052
    /**
     * {@inheritDoc}
     */
1053
    public function getDateTimeTzFormatString()
1054
    {
1055 1056
        return 'Y-m-d H:i:sO';
    }
1057 1058

    /**
1059
     * {@inheritDoc}
1060
     */
1061
    public function getEmptyIdentityInsertSQL($quotedTableName, $quotedIdentifierColumnName)
1062 1063 1064
    {
        return 'INSERT INTO ' . $quotedTableName . ' (' . $quotedIdentifierColumnName . ') VALUES (DEFAULT)';
    }
1065 1066

    /**
1067
     * {@inheritDoc}
1068
     */
1069
    public function getTruncateTableSQL($tableName, $cascade = false)
1070
    {
1071 1072 1073 1074 1075 1076 1077 1078
        $tableIdentifier = new Identifier($tableName);
        $sql = 'TRUNCATE ' . $tableIdentifier->getQuotedName($this);

        if ($cascade) {
            $sql .= ' CASCADE';
        }

        return $sql;
1079
    }
1080

1081 1082 1083
    /**
     * {@inheritDoc}
     */
1084 1085 1086 1087
    public function getReadLockSQL()
    {
        return 'FOR SHARE';
    }
1088

1089 1090 1091
    /**
     * {@inheritDoc}
     */
1092 1093 1094
    protected function initializeDoctrineTypeMappings()
    {
        $this->doctrineTypeMapping = array(
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
            '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',
1109
            'tsvector'      => 'text',
1110 1111 1112 1113 1114
            'varchar'       => 'string',
            'interval'      => 'string',
            '_varchar'      => 'string',
            'char'          => 'string',
            'bpchar'        => 'string',
1115
            'inet'          => 'string',
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
            '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',
1132
            'uuid'          => 'guid',
1133
            'bytea'         => 'blob',
1134 1135
        );
    }
1136

1137 1138 1139
    /**
     * {@inheritDoc}
     */
1140 1141 1142 1143
    public function getVarcharMaxLength()
    {
        return 65535;
    }
1144

Steve Müller's avatar
Steve Müller committed
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
    /**
     * {@inheritdoc}
     */
    public function getBinaryMaxLength()
    {
        return 0;
    }

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

1161 1162 1163
    /**
     * {@inheritDoc}
     */
1164 1165 1166 1167
    protected function getReservedKeywordsClass()
    {
        return 'Doctrine\DBAL\Platforms\Keywords\PostgreSQLKeywords';
    }
1168 1169

    /**
1170
     * {@inheritDoc}
1171 1172 1173 1174 1175
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'BYTEA';
    }
1176
}