PostgreSqlPlatform.php 34.4 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
        $table = new Identifier($table);
321
        $table = $this->quoteStringLiteral($table->getName());
322

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 = $this->quoteStringLiteral($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

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

376 377 378
        return $whereClause;
    }

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

416
    /**
417
     * {@inheritDoc}
418
     */
419
    public function getCreateDatabaseSQL($name)
420
    {
421
        return 'CREATE DATABASE ' . $name;
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
    /**
     * 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)
    {
449 450 451
        $database = $this->quoteStringLiteral($database);

        return "SELECT pg_terminate_backend(procpid) FROM pg_stat_activity WHERE datname = $database";
452 453
    }

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

461 462
        if ($foreignKey->hasOption('match')) {
            $query .= ' MATCH ' . $foreignKey->getOption('match');
463
        }
464

465
        $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
466

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

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

481 482
        return $query;
    }
483

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

        foreach ($diff->addedColumns as $column) {
494 495
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
496 497
            }

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

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

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

512
        foreach ($diff->removedColumns as $column) {
513 514
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
515 516
            }

517
            $query = 'DROP ' . $column->getQuotedName($this);
518
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
519 520
        }

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

Steve Müller's avatar
Steve Müller committed
527 528 529 530
            if ($this->isUnchangedBinaryColumn($columnDiff)) {
                continue;
            }

531
            $oldColumnName = $columnDiff->getOldColumnName()->getQuotedName($this);
532
            $column = $columnDiff->column;
533

534
            if ($columnDiff->hasChanged('type') || $columnDiff->hasChanged('precision') || $columnDiff->hasChanged('scale') || $columnDiff->hasChanged('fixed')) {
535
                $type = $column->getType();
536

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

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

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

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

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

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

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

585
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
586 587
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
588 589
            }

590 591
            $oldColumnName = new Identifier($oldColumnName);

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

596 597
        $tableSql = array();

598
        if ( ! $this->onSchemaAlterTable($diff, $tableSql)) {
599 600
            $sql = array_merge($sql, $commentsSQL);

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

605 606 607 608 609
            $sql = array_merge(
                $this->getPreAlterTableIndexForeignKeySQL($diff),
                $sql,
                $this->getPostAlterTableIndexForeignKeySQL($diff)
            );
610 611
        }

612
        return array_merge($sql, $tableSql, $columnSql);
613
    }
614

Steve Müller's avatar
Steve Müller committed
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 653 654 655
    /**
     * 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;
    }

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

666 667 668
        return array('ALTER INDEX ' . $oldIndexName . ' RENAME TO ' . $index->getQuotedName($this));
    }

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

678 679
        return "COMMENT ON COLUMN " . $tableName->getQuotedName($this) . "." . $columnName->getQuotedName($this) .
            " IS $comment";
680 681
    }

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

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

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

        return '';
718
    }
719

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

729
        return 'DROP SEQUENCE ' . $sequence . ' CASCADE';
730
    }
731

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

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

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

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

760
        $query = 'CREATE TABLE ' . $tableName . ' (' . $queryFields . ')';
761 762 763 764

        $sql[] = $query;

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

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

        return $sql;
    }
778

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

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

802 803 804 805 806 807 808 809 810 811 812 813 814
        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);
815 816
        }

817
        throw new \UnexpectedValueException("Unrecognized boolean literal '${value}'");
818 819 820 821 822 823 824 825 826
    }

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

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

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

863
                return true === $boolean ? 'true' : 'false';
864
            }
865
        );
866 867 868 869 870
    }

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

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

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

894
        return parent::convertFromBoolean($item);
895
    }
896

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

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

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

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

931 932 933 934
        return 'INT';
    }

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

943 944 945 946
        return 'BIGINT';
    }

    /**
947
     * {@inheritDoc}
948
     */
949
    public function getSmallIntTypeDeclarationSQL(array $field)
950 951 952 953
    {
        return 'SMALLINT';
    }

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

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

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

978
    /**
979
     * {@inheritDoc}
980
     */
981
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
982 983
    {
        return 'DATE';
984 985
    }

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

994 995 996 997 998 999 1000 1001
    /**
     * {@inheritDoc}
     */
    public function getGuidExpression()
    {
        return 'UUID_GENERATE_V4()';
    }

1002
    /**
1003
     * {@inheritDoc}
1004
     */
1005
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
1006 1007 1008 1009 1010
    {
        return '';
    }

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

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

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

    /**
1036
     * {@inheritDoc}
1037 1038 1039 1040 1041
     */
    public function getName()
    {
        return 'postgresql';
    }
1042

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

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

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

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

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

        return $sql;
1082
    }
1083

1084 1085 1086
    /**
     * {@inheritDoc}
     */
1087 1088 1089 1090
    public function getReadLockSQL()
    {
        return 'FOR SHARE';
    }
1091

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

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

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

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

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

    /**
1172
     * {@inheritDoc}
1173 1174 1175 1176 1177
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'BYTEA';
    }
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187

    /**
     * {@inheritdoc}
     */
    public function quoteStringLiteral($str)
    {
        $str = str_replace('\\', '\\\\', $str); // PostgreSQL requires backslashes to be escaped aswell.

        return parent::quoteStringLiteral($str);
    }
1188
}