PostgreSqlPlatform.php 35.6 KB
Newer Older
1 2
<?php

3
namespace Doctrine\DBAL\Platforms;
4

Steve Müller's avatar
Steve Müller committed
5 6
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\ColumnDiff;
7
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
8
use Doctrine\DBAL\Schema\Identifier;
9
use Doctrine\DBAL\Schema\Index;
jeroendedauw's avatar
jeroendedauw committed
10
use Doctrine\DBAL\Schema\Sequence;
Benjamin Morel's avatar
Benjamin Morel committed
11
use Doctrine\DBAL\Schema\TableDiff;
12
use Doctrine\DBAL\Types\BigIntType;
13
use Doctrine\DBAL\Types\BinaryType;
Steve Müller's avatar
Steve Müller committed
14
use Doctrine\DBAL\Types\BlobType;
15
use Doctrine\DBAL\Types\IntegerType;
16
use Doctrine\DBAL\Types\Type;
17
use UnexpectedValueException;
18 19 20 21 22 23 24 25 26 27 28 29
use function array_diff;
use function array_merge;
use function array_unique;
use function array_values;
use function count;
use function explode;
use function implode;
use function in_array;
use function is_array;
use function is_bool;
use function is_numeric;
use function is_string;
30
use function sprintf;
31 32 33
use function strpos;
use function strtolower;
use function trim;
34

35 36 37
/**
 * PostgreSqlPlatform.
 *
Benjamin Morel's avatar
Benjamin Morel committed
38
 * @todo   Rename: PostgreSQLPlatform
39
 */
40
class PostgreSqlPlatform extends AbstractPlatform
41
{
42
    /** @var bool */
43 44
    private $useBooleanTrueFalseStrings = true;

45
    /** @var string[][] PostgreSQL booleans literals */
46 47
    private $booleanLiterals = [
        'true' => [
48 49 50 51 52
            't',
            'true',
            'y',
            'yes',
            'on',
53
            '1',
54 55
        ],
        'false' => [
56 57 58 59 60
            'f',
            'false',
            'n',
            'no',
            'off',
61 62
            '0',
        ],
63
    ];
64

65 66 67 68 69 70 71 72 73 74
    /**
     * 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)
    {
75
        $this->useBooleanTrueFalseStrings = (bool) $flag;
76 77
    }

78
    /**
79
     * {@inheritDoc}
80
     */
81
    public function getSubstringExpression($value, $from, $length = null)
82
    {
83
        if ($length === null) {
84
            return 'SUBSTRING(' . $value . ' FROM ' . $from . ')';
85
        }
86

87
        return 'SUBSTRING(' . $value . ' FROM ' . $from . ' FOR ' . $length . ')';
88 89 90
    }

    /**
91
     * {@inheritDoc}
92 93 94 95 96 97 98
     */
    public function getNowExpression()
    {
        return 'LOCALTIMESTAMP(0)';
    }

    /**
99
     * {@inheritDoc}
100 101 102 103 104
     */
    public function getRegexpExpression()
    {
        return 'SIMILAR TO';
    }
105 106

    /**
107
     * {@inheritDoc}
108 109 110 111 112
     */
    public function getLocateExpression($str, $substr, $startPos = false)
    {
        if ($startPos !== false) {
            $str = $this->getSubstringExpression($str, $startPos);
113

114
            return 'CASE WHEN (POSITION(' . $substr . ' IN ' . $str . ') = 0) THEN 0 ELSE (POSITION(' . $substr . ' IN ' . $str . ') + ' . ($startPos-1) . ') END';
115
        }
116

117
        return 'POSITION(' . $substr . ' IN ' . $str . ')';
118
    }
119

120
    /**
121
     * {@inheritdoc}
122
     */
123
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
124
    {
125
        if ($unit === DateIntervalUnit::QUARTER) {
126
            $interval *= 3;
127
            $unit      = DateIntervalUnit::MONTH;
128
        }
129

130
        return '(' . $date . ' ' . $operator . ' (' . $interval . " || ' " . $unit . "')::interval)";
131 132
    }

133 134 135
    /**
     * {@inheritDoc}
     */
136
    public function getDateDiffExpression($date1, $date2)
137
    {
138
        return '(DATE(' . $date1 . ')-DATE(' . $date2 . '))';
139
    }
140

141
    /**
142
     * {@inheritDoc}
romanb's avatar
romanb committed
143 144 145 146 147
     */
    public function supportsSequences()
    {
        return true;
    }
148

149
    /**
150
     * {@inheritDoc}
151 152 153 154 155
     */
    public function supportsSchemas()
    {
        return true;
    }
156

157 158 159 160 161 162 163 164
    /**
     * {@inheritdoc}
     */
    public function getDefaultSchemaName()
    {
        return 'public';
    }

romanb's avatar
romanb committed
165
    /**
166
     * {@inheritDoc}
romanb's avatar
romanb committed
167 168 169 170 171
     */
    public function supportsIdentityColumns()
    {
        return true;
    }
172

173
    /**
174
     * {@inheritdoc}
175 176 177 178 179 180
     */
    public function supportsPartialIndexes()
    {
        return true;
    }

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
    /**
     * {@inheritdoc}
     */
    public function usesSequenceEmulatedIdentityColumns()
    {
        return true;
    }

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

197 198 199
    /**
     * {@inheritDoc}
     */
200 201 202 203
    public function supportsCommentOnStatement()
    {
        return true;
    }
204

romanb's avatar
romanb committed
205
    /**
206
     * {@inheritDoc}
romanb's avatar
romanb committed
207 208 209 210 211
     */
    public function prefersSequences()
    {
        return true;
    }
212

213 214 215 216 217 218 219 220
    /**
     * {@inheritDoc}
     */
    public function hasNativeGuidType()
    {
        return true;
    }

Benjamin Morel's avatar
Benjamin Morel committed
221 222 223
    /**
     * {@inheritDoc}
     */
224
    public function getListDatabasesSQL()
225 226 227
    {
        return 'SELECT datname FROM pg_database';
    }
228

229 230 231 232 233
    /**
     * {@inheritDoc}
     */
    public function getListNamespacesSQL()
    {
234 235
        return "SELECT schema_name AS nspname
                FROM   information_schema.schemata
236
                WHERE  schema_name NOT LIKE 'pg\_%'
237
                AND    schema_name != 'information_schema'";
238 239
    }

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

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

267 268 269
    /**
     * {@inheritDoc}
     */
270
    public function getListViewsSQL($database)
271
    {
272 273 274 275 276
        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';
277
    }
278

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

Benjamin Morel's avatar
Benjamin Morel committed
295 296 297
    /**
     * {@inheritDoc}
     */
298
    public function getCreateViewSQL($name, $sql)
299 300 301 302
    {
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
    }

Benjamin Morel's avatar
Benjamin Morel committed
303 304 305
    /**
     * {@inheritDoc}
     */
306
    public function getDropViewSQL($name)
307
    {
308
        return 'DROP VIEW ' . $name;
309 310
    }

Benjamin Morel's avatar
Benjamin Morel committed
311 312 313
    /**
     * {@inheritDoc}
     */
314
    public function getListTableConstraintsSQL($table)
315
    {
316
        $table = new Identifier($table);
317
        $table = $this->quoteStringLiteral($table->getName());
318

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
        return sprintf(
            <<<'SQL'
SELECT
    quote_ident(relname) as relname
FROM
    pg_class
WHERE oid IN (
    SELECT indexrelid
    FROM pg_index, pg_class
    WHERE pg_class.relname = %s
        AND pg_class.oid = pg_index.indrelid
        AND (indisunique = 't' OR indisprimary = 't')
    )
SQL
            ,
            $table
        );
336
    }
337

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

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

        $table = new Identifier($table);
374
        $table = $this->quoteStringLiteral($table->getName());
375 376 377 378 379 380 381 382

        return $whereClause . sprintf(
            '%s.relname = %s AND %s.nspname = %s',
            $classAlias,
            $table,
            $namespaceAlias,
            $schema
        );
383 384
    }

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

422
    /**
423
     * {@inheritDoc}
424
     */
425
    public function getCreateDatabaseSQL($name)
426
    {
427
        return 'CREATE DATABASE ' . $name;
428
    }
429

430 431 432 433 434 435 436 437 438 439 440
    /**
     * 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)
    {
441
        return "UPDATE pg_database SET datallowconn = 'false' WHERE datname = " . $this->quoteStringLiteral($database);
442 443 444 445 446 447 448 449 450 451 452 453 454
    }

    /**
     * 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)
    {
455 456
        return 'SELECT pg_terminate_backend(procpid) FROM pg_stat_activity WHERE datname = '
            . $this->quoteStringLiteral($database);
457 458
    }

459
    /**
460
     * {@inheritDoc}
461
     */
462
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
463 464
    {
        $query = '';
465

466 467
        if ($foreignKey->hasOption('match')) {
            $query .= ' MATCH ' . $foreignKey->getOption('match');
468
        }
469

470
        $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
471

472
        if ($foreignKey->hasOption('deferrable') && $foreignKey->getOption('deferrable') !== false) {
473 474 475 476
            $query .= ' DEFERRABLE';
        } else {
            $query .= ' NOT DEFERRABLE';
        }
477

478 479 480
        if (($foreignKey->hasOption('feferred') && $foreignKey->getOption('feferred') !== false)
            || ($foreignKey->hasOption('deferred') && $foreignKey->getOption('deferred') !== false)
        ) {
481 482 483 484
            $query .= ' INITIALLY DEFERRED';
        } else {
            $query .= ' INITIALLY IMMEDIATE';
        }
485

486 487
        return $query;
    }
488

489
    /**
490
     * {@inheritDoc}
491
     */
492
    public function getAlterTableSQL(TableDiff $diff)
493
    {
494
        $sql         = [];
495
        $commentsSQL = [];
496
        $columnSql   = [];
497 498

        foreach ($diff->addedColumns as $column) {
499 500
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
501 502
            }

503
            $query = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
504
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
505 506 507

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

508 509
            if ($comment === null || $comment === '') {
                continue;
510
            }
511 512 513 514 515 516

            $commentsSQL[] = $this->getCommentOnColumnSQL(
                $diff->getName($this)->getQuotedName($this),
                $column->getQuotedName($this),
                $comment
            );
517 518
        }

519
        foreach ($diff->removedColumns as $column) {
520 521
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
522 523
            }

524
            $query = 'DROP ' . $column->getQuotedName($this);
525
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
526 527
        }

528
        foreach ($diff->changedColumns as $columnDiff) {
529
            /** @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */
530 531
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
532 533
            }

Steve Müller's avatar
Steve Müller committed
534 535 536 537
            if ($this->isUnchangedBinaryColumn($columnDiff)) {
                continue;
            }

538
            $oldColumnName = $columnDiff->getOldColumnName()->getQuotedName($this);
539
            $column        = $columnDiff->column;
540

541
            if ($columnDiff->hasChanged('type') || $columnDiff->hasChanged('precision') || $columnDiff->hasChanged('scale') || $columnDiff->hasChanged('fixed')) {
542
                $type = $column->getType();
543

544
                // SERIAL/BIGSERIAL are not "real" types and we can't alter a column to that type
545
                $columnDefinition                  = $column->toArray();
546 547
                $columnDefinition['autoincrement'] = false;

548
                // here was a server version check before, but DBAL API does not support this anymore.
549
                $query = 'ALTER ' . $oldColumnName . ' TYPE ' . $type->getSQLDeclaration($columnDefinition, $this);
550
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
551
            }
552

553
            if ($columnDiff->hasChanged('default') || $this->typeChangeBreaksDefaultValue($columnDiff)) {
554
                $defaultClause = $column->getDefault() === null
555 556
                    ? ' DROP DEFAULT'
                    : ' SET' . $this->getDefaultValueDeclarationSQL($column->toArray());
557 558
                $query         = 'ALTER ' . $oldColumnName . $defaultClause;
                $sql[]         = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
559
            }
560

561
            if ($columnDiff->hasChanged('notnull')) {
562
                $query = 'ALTER ' . $oldColumnName . ' ' . ($column->getNotnull() ? 'SET' : 'DROP') . ' NOT NULL';
563
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
564
            }
565

566 567 568
            if ($columnDiff->hasChanged('autoincrement')) {
                if ($column->getAutoincrement()) {
                    // add autoincrement
569
                    $seqName = $this->getIdentitySequenceName($diff->name, $oldColumnName);
570

571 572 573 574
                    $sql[] = 'CREATE SEQUENCE ' . $seqName;
                    $sql[] = "SELECT setval('" . $seqName . "', (SELECT MAX(" . $oldColumnName . ') FROM ' . $diff->getName($this)->getQuotedName($this) . '))';
                    $query = 'ALTER ' . $oldColumnName . " SET DEFAULT nextval('" . $seqName . "')";
                    $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
575 576
                } else {
                    // Drop autoincrement, but do NOT drop the sequence. It might be re-used by other tables or have
577
                    $query = 'ALTER ' . $oldColumnName . ' DROP DEFAULT';
578
                    $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
579 580
                }
            }
581

582
            $newComment = $this->getColumnComment($column);
583
            $oldComment = $this->getOldColumnComment($columnDiff);
584 585

            if ($columnDiff->hasChanged('comment') || ($columnDiff->fromColumn !== null && $oldComment !== $newComment)) {
586
                $commentsSQL[] = $this->getCommentOnColumnSQL(
587 588
                    $diff->getName($this)->getQuotedName($this),
                    $column->getQuotedName($this),
589
                    $newComment
590
                );
591
            }
592

593 594
            if (! $columnDiff->hasChanged('length')) {
                continue;
595
            }
596 597 598

            $query = 'ALTER ' . $oldColumnName . ' TYPE ' . $column->getType()->getSQLDeclaration($column->toArray(), $this);
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
599 600
        }

601
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
602 603
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
604 605
            }

606 607
            $oldColumnName = new Identifier($oldColumnName);

608
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) .
609
                ' RENAME COLUMN ' . $oldColumnName->getQuotedName($this) . ' TO ' . $column->getQuotedName($this);
610 611
        }

612
        $tableSql = [];
613

614
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
615 616
            $sql = array_merge($sql, $commentsSQL);

617
            if ($diff->newName !== false) {
618
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' RENAME TO ' . $diff->getNewName()->getQuotedName($this);
619 620
            }

621 622 623 624 625
            $sql = array_merge(
                $this->getPreAlterTableIndexForeignKeySQL($diff),
                $sql,
                $this->getPostAlterTableIndexForeignKeySQL($diff)
            );
626 627
        }

628
        return array_merge($sql, $tableSql, $columnSql);
629
    }
630

Steve Müller's avatar
Steve Müller committed
631 632 633 634 635 636 637 638 639 640 641 642
    /**
     * 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.
     *
643
     * @return bool True if the given column diff is an unchanged binary type column, false otherwise.
Steve Müller's avatar
Steve Müller committed
644 645 646 647 648
     */
    private function isUnchangedBinaryColumn(ColumnDiff $columnDiff)
    {
        $columnType = $columnDiff->column->getType();

649
        if (! $columnType instanceof BinaryType && ! $columnType instanceof BlobType) {
Steve Müller's avatar
Steve Müller committed
650 651 652 653 654 655 656 657
            return false;
        }

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

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

658
            if (! $fromColumnType instanceof BinaryType && ! $fromColumnType instanceof BlobType) {
Steve Müller's avatar
Steve Müller committed
659 660 661
                return false;
            }

662
            return count(array_diff($columnDiff->changedProperties, ['type', 'length', 'fixed'])) === 0;
Steve Müller's avatar
Steve Müller committed
663 664 665 666 667 668
        }

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

669
        return count(array_diff($columnDiff->changedProperties, ['length', 'fixed'])) === 0;
Steve Müller's avatar
Steve Müller committed
670 671
    }

672 673 674 675 676
    /**
     * {@inheritdoc}
     */
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
    {
677
        if (strpos($tableName, '.') !== false) {
678
            [$schema]     = explode('.', $tableName);
679 680 681
            $oldIndexName = $schema . '.' . $oldIndexName;
        }

682
        return ['ALTER INDEX ' . $oldIndexName . ' RENAME TO ' . $index->getQuotedName($this)];
683 684
    }

685 686 687 688 689
    /**
     * {@inheritdoc}
     */
    public function getCommentOnColumnSQL($tableName, $columnName, $comment)
    {
690
        $tableName  = new Identifier($tableName);
691
        $columnName = new Identifier($columnName);
692
        $comment    = $comment === null ? 'NULL' : $this->quoteStringLiteral($comment);
693

694 695 696 697 698 699
        return sprintf(
            'COMMENT ON COLUMN %s.%s IS %s',
            $tableName->getQuotedName($this),
            $columnName->getQuotedName($this),
            $comment
        );
700 701
    }

702
    /**
703
     * {@inheritDoc}
704
     */
jeroendedauw's avatar
jeroendedauw committed
705
    public function getCreateSequenceSQL(Sequence $sequence)
706
    {
707
        return 'CREATE SEQUENCE ' . $sequence->getQuotedName($this) .
708 709 710 711
            ' INCREMENT BY ' . $sequence->getAllocationSize() .
            ' MINVALUE ' . $sequence->getInitialValue() .
            ' START ' . $sequence->getInitialValue() .
            $this->getSequenceCacheSQL($sequence);
712
    }
713

714 715 716
    /**
     * {@inheritDoc}
     */
jeroendedauw's avatar
jeroendedauw committed
717
    public function getAlterSequenceSQL(Sequence $sequence)
718
    {
719
        return 'ALTER SEQUENCE ' . $sequence->getQuotedName($this) .
720 721
            ' INCREMENT BY ' . $sequence->getAllocationSize() .
            $this->getSequenceCacheSQL($sequence);
722 723 724 725 726 727 728
    }

    /**
     * Cache definition for sequences
     *
     * @return string
     */
jeroendedauw's avatar
jeroendedauw committed
729
    private function getSequenceCacheSQL(Sequence $sequence)
730 731 732 733 734 735
    {
        if ($sequence->getCache() > 1) {
            return ' CACHE ' . $sequence->getCache();
        }

        return '';
736
    }
737

738
    /**
739
     * {@inheritDoc}
740
     */
741
    public function getDropSequenceSQL($sequence)
742
    {
jeroendedauw's avatar
jeroendedauw committed
743
        if ($sequence instanceof Sequence) {
744
            $sequence = $sequence->getQuotedName($this);
745
        }
746

747
        return 'DROP SEQUENCE ' . $sequence . ' CASCADE';
748
    }
749

750 751 752 753 754 755 756 757
    /**
     * {@inheritDoc}
     */
    public function getCreateSchemaSQL($schemaName)
    {
        return 'CREATE SCHEMA ' . $schemaName;
    }

758
    /**
759
     * {@inheritDoc}
760
     */
761
    public function getDropForeignKeySQL($foreignKey, $table)
762
    {
763
        return $this->getDropConstraintSQL($foreignKey, $table);
764
    }
765

766
    /**
767
     * {@inheritDoc}
768
     */
769
    protected function _getCreateTableSQL($tableName, array $columns, array $options = [])
770
    {
771
        $queryFields = $this->getColumnDeclarationListSQL($columns);
772 773

        if (isset($options['primary']) && ! empty($options['primary'])) {
774
            $keyColumns   = array_unique(array_values($options['primary']));
775 776 777
            $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
        }

778
        $query = 'CREATE TABLE ' . $tableName . ' (' . $queryFields . ')';
779

780
        $sql = [$query];
781 782

        if (isset($options['indexes']) && ! empty($options['indexes'])) {
783
            foreach ($options['indexes'] as $index) {
784
                $sql[] = $this->getCreateIndexSQL($index, $tableName);
785 786 787 788
            }
        }

        if (isset($options['foreignKeys'])) {
789
            foreach ((array) $options['foreignKeys'] as $definition) {
790
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
791 792 793 794 795
            }
        }

        return $sql;
    }
796

797 798 799 800 801 802 803 804 805 806 807
    /**
     * 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
808 809
     *
     * @throws UnexpectedValueException
810 811 812
     */
    private function convertSingleBooleanValue($value, $callback)
    {
813
        if ($value === null) {
814
            return $callback(null);
815 816 817 818 819 820
        }

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

821
        if (! is_string($value)) {
822 823 824 825 826 827
            return $callback(true);
        }

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

832
        if (in_array(strtolower(trim($value)), $this->booleanLiterals['true'], true)) {
833
            return $callback(true);
834 835
        }

836
        throw new UnexpectedValueException("Unrecognized boolean literal '${value}'");
837 838 839 840 841 842 843 844 845
    }

    /**
     * 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.
     *
846
     * @param mixed    $item     The value(s) to convert.
847
     * @param callable $callback The callback function to use for converting the real boolean value(s).
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
     *
     * @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);
    }

864
    /**
865
     * {@inheritDoc}
866
     *
867
     * Postgres wants boolean values converted to the strings 'true'/'false'.
868
     */
869
    public function convertBooleans($item)
870
    {
871
        if (! $this->useBooleanTrueFalseStrings) {
872
            return parent::convertBooleans($item);
873 874
        }

875 876
        return $this->doConvertBooleans(
            $item,
877 878
            static function ($boolean) {
                if ($boolean === null) {
879
                    return 'NULL';
880
                }
881

882
                return $boolean === true ? 'true' : 'false';
883
            }
884
        );
885 886 887 888 889
    }

    /**
     * {@inheritDoc}
     */
890
    public function convertBooleansToDatabaseValue($item)
891
    {
892
        if (! $this->useBooleanTrueFalseStrings) {
893
            return parent::convertBooleansToDatabaseValue($item);
894 895
        }

896 897
        return $this->doConvertBooleans(
            $item,
898 899
            static function ($boolean) {
                return $boolean === null ? null : (int) $boolean;
900 901
            }
        );
902
    }
903

904
    /**
905 906
     * {@inheritDoc}
     */
907 908
    public function convertFromBoolean($item)
    {
909
        if (in_array(strtolower($item), $this->booleanLiterals['false'], true)) {
910
            return false;
911 912
        }

913
        return parent::convertFromBoolean($item);
914
    }
915

Benjamin Morel's avatar
Benjamin Morel committed
916 917 918
    /**
     * {@inheritDoc}
     */
919
    public function getSequenceNextValSQL($sequenceName)
920 921 922
    {
        return "SELECT NEXTVAL('" . $sequenceName . "')";
    }
923

924 925 926
    /**
     * {@inheritDoc}
     */
927
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
928 929
    {
        return 'SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL '
930
            . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
931
    }
932

933
    /**
934
     * {@inheritDoc}
935
     */
936
    public function getBooleanTypeDeclarationSQL(array $field)
937 938 939
    {
        return 'BOOLEAN';
    }
940 941

    /**
942
     * {@inheritDoc}
943
     */
944
    public function getIntegerTypeDeclarationSQL(array $field)
945
    {
946
        if (! empty($field['autoincrement'])) {
947 948
            return 'SERIAL';
        }
949

950 951 952 953
        return 'INT';
    }

    /**
954
     * {@inheritDoc}
955
     */
956
    public function getBigIntTypeDeclarationSQL(array $field)
957
    {
958
        if (! empty($field['autoincrement'])) {
959 960
            return 'BIGSERIAL';
        }
961

962 963 964 965
        return 'BIGINT';
    }

    /**
966
     * {@inheritDoc}
967
     */
968
    public function getSmallIntTypeDeclarationSQL(array $field)
969 970 971 972
    {
        return 'SMALLINT';
    }

rivaros's avatar
rivaros committed
973
    /**
974
     * {@inheritDoc}
rivaros's avatar
rivaros committed
975
     */
976
    public function getGuidTypeDeclarationSQL(array $field)
rivaros's avatar
rivaros committed
977 978 979 980
    {
        return 'UUID';
    }

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

    /**
990
     * {@inheritDoc}
991
     */
992
    public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration)
993
    {
994 995
        return 'TIMESTAMP(0) WITH TIME ZONE';
    }
996

997
    /**
998
     * {@inheritDoc}
999
     */
1000
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
1001 1002
    {
        return 'DATE';
1003 1004
    }

1005
    /**
1006
     * {@inheritDoc}
1007
     */
1008
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
1009
    {
1010
        return 'TIME(0) WITHOUT TIME ZONE';
1011 1012
    }

1013 1014
    /**
     * {@inheritDoc}
1015 1016
     *
     * @deprecated Use application-generated UUIDs instead
1017 1018 1019 1020 1021 1022
     */
    public function getGuidExpression()
    {
        return 'UUID_GENERATE_V4()';
    }

1023
    /**
1024
     * {@inheritDoc}
1025
     */
1026
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
1027 1028 1029 1030 1031
    {
        return '';
    }

    /**
1032
     * {@inheritDoc}
1033
     */
1034
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
1035 1036
    {
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
1037
            : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)');
1038
    }
1039

Steve Müller's avatar
Steve Müller committed
1040 1041 1042 1043 1044 1045 1046 1047
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
        return 'BYTEA';
    }

1048 1049 1050
    /**
     * {@inheritDoc}
     */
1051
    public function getClobTypeDeclarationSQL(array $field)
1052 1053 1054
    {
        return 'TEXT';
    }
1055 1056

    /**
1057
     * {@inheritDoc}
1058 1059 1060 1061 1062
     */
    public function getName()
    {
        return 'postgresql';
    }
1063

1064
    /**
1065
     * {@inheritDoc}
1066
     *
1067 1068
     * PostgreSQL returns all column names in SQL result sets in lowercase.
     */
1069
    public function getSQLResultCasing($column)
1070 1071 1072
    {
        return strtolower($column);
    }
1073

1074 1075 1076
    /**
     * {@inheritDoc}
     */
1077
    public function getDateTimeTzFormatString()
1078
    {
1079 1080
        return 'Y-m-d H:i:sO';
    }
1081 1082

    /**
1083
     * {@inheritDoc}
1084
     */
1085
    public function getEmptyIdentityInsertSQL($quotedTableName, $quotedIdentifierColumnName)
1086 1087 1088
    {
        return 'INSERT INTO ' . $quotedTableName . ' (' . $quotedIdentifierColumnName . ') VALUES (DEFAULT)';
    }
1089 1090

    /**
1091
     * {@inheritDoc}
1092
     */
1093
    public function getTruncateTableSQL($tableName, $cascade = false)
1094
    {
1095
        $tableIdentifier = new Identifier($tableName);
1096
        $sql             = 'TRUNCATE ' . $tableIdentifier->getQuotedName($this);
1097 1098 1099 1100 1101 1102

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

        return $sql;
1103
    }
1104

1105 1106 1107
    /**
     * {@inheritDoc}
     */
1108 1109 1110 1111
    public function getReadLockSQL()
    {
        return 'FOR SHARE';
    }
1112

1113 1114 1115
    /**
     * {@inheritDoc}
     */
1116 1117
    protected function initializeDoctrineTypeMappings()
    {
1118
        $this->doctrineTypeMapping = [
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
            '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',
1133
            'tsvector'      => 'text',
1134 1135 1136 1137 1138
            'varchar'       => 'string',
            'interval'      => 'string',
            '_varchar'      => 'string',
            'char'          => 'string',
            'bpchar'        => 'string',
1139
            'inet'          => 'string',
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
            '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',
1156
            'uuid'          => 'guid',
1157
            'bytea'         => 'blob',
1158
        ];
1159
    }
1160

1161 1162 1163
    /**
     * {@inheritDoc}
     */
1164 1165 1166 1167
    public function getVarcharMaxLength()
    {
        return 65535;
    }
1168

Steve Müller's avatar
Steve Müller committed
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
    /**
     * {@inheritdoc}
     */
    public function getBinaryMaxLength()
    {
        return 0;
    }

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

1185 1186 1187
    /**
     * {@inheritDoc}
     */
1188 1189
    protected function getReservedKeywordsClass()
    {
1190
        return Keywords\PostgreSQLKeywords::class;
1191
    }
1192 1193

    /**
1194
     * {@inheritDoc}
1195 1196 1197 1198 1199
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'BYTEA';
    }
1200

1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
    /**
     * {@inheritdoc}
     */
    public function getDefaultValueDeclarationSQL($field)
    {
        if ($this->isSerialField($field)) {
            return '';
        }

        return parent::getDefaultValueDeclarationSQL($field);
    }

1213 1214 1215
    /**
     * @param mixed[] $field
     */
1216 1217 1218
    private function isSerialField(array $field) : bool
    {
        return $field['autoincrement'] ?? false === true && isset($field['type'])
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
            && $this->isNumericType($field['type']);
    }

    /**
     * Check whether the type of a column is changed in a way that invalidates the default value for the column
     */
    private function typeChangeBreaksDefaultValue(ColumnDiff $columnDiff) : bool
    {
        if (! $columnDiff->fromColumn) {
            return $columnDiff->hasChanged('type');
        }

        $oldTypeIsNumeric = $this->isNumericType($columnDiff->fromColumn->getType());
        $newTypeIsNumeric = $this->isNumericType($columnDiff->column->getType());

        // default should not be changed when switching between numeric types and the default comes from a sequence
        return $columnDiff->hasChanged('type')
            && ! ($oldTypeIsNumeric && $newTypeIsNumeric && $columnDiff->column->getAutoincrement());
    }

    private function isNumericType(Type $type) : bool
    {
        return $type instanceof IntegerType || $type instanceof BigIntType;
1242
    }
1243 1244 1245 1246 1247

    private function getOldColumnComment(ColumnDiff $columnDiff) : ?string
    {
        return $columnDiff->fromColumn ? $this->getColumnComment($columnDiff->fromColumn) : null;
    }
1248
}