PostgreSqlPlatform.php 36.1 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);

Sergei Morozov's avatar
Sergei Morozov committed
617 618 619 620 621 622 623 624
            $newName = $diff->getNewName();

            if ($newName !== false) {
                $sql[] = sprintf(
                    'ALTER TABLE %s RENAME TO %s',
                    $diff->getName($this)->getQuotedName($this),
                    $newName->getQuotedName($this)
                );
625 626
            }

627 628 629 630 631
            $sql = array_merge(
                $this->getPreAlterTableIndexForeignKeySQL($diff),
                $sql,
                $this->getPostAlterTableIndexForeignKeySQL($diff)
            );
632 633
        }

634
        return array_merge($sql, $tableSql, $columnSql);
635
    }
636

Steve Müller's avatar
Steve Müller committed
637 638 639 640 641 642 643 644 645 646 647 648
    /**
     * 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.
     *
649
     * @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
650 651 652 653 654
     */
    private function isUnchangedBinaryColumn(ColumnDiff $columnDiff)
    {
        $columnType = $columnDiff->column->getType();

655
        if (! $columnType instanceof BinaryType && ! $columnType instanceof BlobType) {
Steve Müller's avatar
Steve Müller committed
656 657 658 659 660 661 662 663
            return false;
        }

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

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

664
            if (! $fromColumnType instanceof BinaryType && ! $fromColumnType instanceof BlobType) {
Steve Müller's avatar
Steve Müller committed
665 666 667
                return false;
            }

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

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

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

678 679 680 681 682
    /**
     * {@inheritdoc}
     */
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
    {
683
        if (strpos($tableName, '.') !== false) {
684
            [$schema]     = explode('.', $tableName);
685 686 687
            $oldIndexName = $schema . '.' . $oldIndexName;
        }

688
        return ['ALTER INDEX ' . $oldIndexName . ' RENAME TO ' . $index->getQuotedName($this)];
689 690
    }

691 692 693 694 695
    /**
     * {@inheritdoc}
     */
    public function getCommentOnColumnSQL($tableName, $columnName, $comment)
    {
696
        $tableName  = new Identifier($tableName);
697
        $columnName = new Identifier($columnName);
698
        $comment    = $comment === null ? 'NULL' : $this->quoteStringLiteral($comment);
699

700 701 702 703 704 705
        return sprintf(
            'COMMENT ON COLUMN %s.%s IS %s',
            $tableName->getQuotedName($this),
            $columnName->getQuotedName($this),
            $comment
        );
706 707
    }

708
    /**
709
     * {@inheritDoc}
710
     */
jeroendedauw's avatar
jeroendedauw committed
711
    public function getCreateSequenceSQL(Sequence $sequence)
712
    {
713
        return 'CREATE SEQUENCE ' . $sequence->getQuotedName($this) .
714 715 716 717
            ' INCREMENT BY ' . $sequence->getAllocationSize() .
            ' MINVALUE ' . $sequence->getInitialValue() .
            ' START ' . $sequence->getInitialValue() .
            $this->getSequenceCacheSQL($sequence);
718
    }
719

720 721 722
    /**
     * {@inheritDoc}
     */
jeroendedauw's avatar
jeroendedauw committed
723
    public function getAlterSequenceSQL(Sequence $sequence)
724
    {
725
        return 'ALTER SEQUENCE ' . $sequence->getQuotedName($this) .
726 727
            ' INCREMENT BY ' . $sequence->getAllocationSize() .
            $this->getSequenceCacheSQL($sequence);
728 729 730 731 732 733 734
    }

    /**
     * Cache definition for sequences
     *
     * @return string
     */
jeroendedauw's avatar
jeroendedauw committed
735
    private function getSequenceCacheSQL(Sequence $sequence)
736 737 738 739 740 741
    {
        if ($sequence->getCache() > 1) {
            return ' CACHE ' . $sequence->getCache();
        }

        return '';
742
    }
743

744
    /**
745
     * {@inheritDoc}
746
     */
747
    public function getDropSequenceSQL($sequence)
748
    {
jeroendedauw's avatar
jeroendedauw committed
749
        if ($sequence instanceof Sequence) {
750
            $sequence = $sequence->getQuotedName($this);
751
        }
752

753
        return 'DROP SEQUENCE ' . $sequence . ' CASCADE';
754
    }
755

756 757 758 759 760 761 762 763
    /**
     * {@inheritDoc}
     */
    public function getCreateSchemaSQL($schemaName)
    {
        return 'CREATE SCHEMA ' . $schemaName;
    }

764
    /**
765
     * {@inheritDoc}
766
     */
767
    public function getDropForeignKeySQL($foreignKey, $table)
768
    {
769
        return $this->getDropConstraintSQL($foreignKey, $table);
770
    }
771

772
    /**
773
     * {@inheritDoc}
774
     */
775
    protected function _getCreateTableSQL($tableName, array $columns, array $options = [])
776
    {
777
        $queryFields = $this->getColumnDeclarationListSQL($columns);
778 779

        if (isset($options['primary']) && ! empty($options['primary'])) {
780
            $keyColumns   = array_unique(array_values($options['primary']));
781 782 783
            $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
        }

784
        $query = 'CREATE TABLE ' . $tableName . ' (' . $queryFields . ')';
785

786
        $sql = [$query];
787 788

        if (isset($options['indexes']) && ! empty($options['indexes'])) {
789
            foreach ($options['indexes'] as $index) {
790
                $sql[] = $this->getCreateIndexSQL($index, $tableName);
791 792 793 794
            }
        }

        if (isset($options['foreignKeys'])) {
795
            foreach ((array) $options['foreignKeys'] as $definition) {
796
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
797 798 799 800 801
            }
        }

        return $sql;
    }
802

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

        if (is_bool($value) || is_numeric($value)) {
824
            return $callback((bool) $value);
825 826
        }

827
        if (! is_string($value)) {
828 829 830 831 832 833
            return $callback(true);
        }

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

838
        if (in_array(strtolower(trim($value)), $this->booleanLiterals['true'], true)) {
839
            return $callback(true);
840 841
        }

842
        throw new UnexpectedValueException("Unrecognized boolean literal '${value}'");
843 844 845 846 847 848 849 850 851
    }

    /**
     * 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.
     *
852
     * @param mixed    $item     The value(s) to convert.
853
     * @param callable $callback The callback function to use for converting the real boolean value(s).
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
     *
     * @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);
    }

870
    /**
871
     * {@inheritDoc}
872
     *
873
     * Postgres wants boolean values converted to the strings 'true'/'false'.
874
     */
875
    public function convertBooleans($item)
876
    {
877
        if (! $this->useBooleanTrueFalseStrings) {
878
            return parent::convertBooleans($item);
879 880
        }

881 882
        return $this->doConvertBooleans(
            $item,
883 884
            static function ($boolean) {
                if ($boolean === null) {
885
                    return 'NULL';
886
                }
887

888
                return $boolean === true ? 'true' : 'false';
889
            }
890
        );
891 892 893 894 895
    }

    /**
     * {@inheritDoc}
     */
896
    public function convertBooleansToDatabaseValue($item)
897
    {
898
        if (! $this->useBooleanTrueFalseStrings) {
899
            return parent::convertBooleansToDatabaseValue($item);
900 901
        }

902 903
        return $this->doConvertBooleans(
            $item,
904 905
            static function ($boolean) {
                return $boolean === null ? null : (int) $boolean;
906 907
            }
        );
908
    }
909

910
    /**
911 912
     * {@inheritDoc}
     */
913 914
    public function convertFromBoolean($item)
    {
915
        if (in_array(strtolower($item), $this->booleanLiterals['false'], true)) {
916
            return false;
917 918
        }

919
        return parent::convertFromBoolean($item);
920
    }
921

Benjamin Morel's avatar
Benjamin Morel committed
922 923 924
    /**
     * {@inheritDoc}
     */
925
    public function getSequenceNextValSQL($sequenceName)
926 927 928
    {
        return "SELECT NEXTVAL('" . $sequenceName . "')";
    }
929

930 931 932
    /**
     * {@inheritDoc}
     */
933
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
934 935
    {
        return 'SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL '
936
            . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
937
    }
938

939
    /**
940
     * {@inheritDoc}
941
     */
942
    public function getBooleanTypeDeclarationSQL(array $field)
943 944 945
    {
        return 'BOOLEAN';
    }
946 947

    /**
948
     * {@inheritDoc}
949
     */
950
    public function getIntegerTypeDeclarationSQL(array $field)
951
    {
952
        if (! empty($field['autoincrement'])) {
953 954
            return 'SERIAL';
        }
955

956 957 958 959
        return 'INT';
    }

    /**
960
     * {@inheritDoc}
961
     */
962
    public function getBigIntTypeDeclarationSQL(array $field)
963
    {
964
        if (! empty($field['autoincrement'])) {
965 966
            return 'BIGSERIAL';
        }
967

968 969 970 971
        return 'BIGINT';
    }

    /**
972
     * {@inheritDoc}
973
     */
974
    public function getSmallIntTypeDeclarationSQL(array $field)
975 976 977 978
    {
        return 'SMALLINT';
    }

rivaros's avatar
rivaros committed
979
    /**
980
     * {@inheritDoc}
rivaros's avatar
rivaros committed
981
     */
982
    public function getGuidTypeDeclarationSQL(array $field)
rivaros's avatar
rivaros committed
983 984 985 986
    {
        return 'UUID';
    }

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

    /**
996
     * {@inheritDoc}
997
     */
998
    public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration)
999
    {
1000 1001
        return 'TIMESTAMP(0) WITH TIME ZONE';
    }
1002

1003
    /**
1004
     * {@inheritDoc}
1005
     */
1006
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
1007 1008
    {
        return 'DATE';
1009 1010
    }

1011
    /**
1012
     * {@inheritDoc}
1013
     */
1014
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
1015
    {
1016
        return 'TIME(0) WITHOUT TIME ZONE';
1017 1018
    }

1019 1020
    /**
     * {@inheritDoc}
1021 1022
     *
     * @deprecated Use application-generated UUIDs instead
1023 1024 1025 1026 1027 1028
     */
    public function getGuidExpression()
    {
        return 'UUID_GENERATE_V4()';
    }

1029
    /**
1030
     * {@inheritDoc}
1031
     */
1032
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
1033 1034 1035 1036 1037
    {
        return '';
    }

    /**
1038
     * {@inheritDoc}
1039
     */
1040
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
1041 1042
    {
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
1043
            : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)');
1044
    }
1045

Steve Müller's avatar
Steve Müller committed
1046 1047 1048 1049 1050 1051 1052 1053
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
        return 'BYTEA';
    }

1054 1055 1056
    /**
     * {@inheritDoc}
     */
1057
    public function getClobTypeDeclarationSQL(array $field)
1058 1059 1060
    {
        return 'TEXT';
    }
1061 1062

    /**
1063
     * {@inheritDoc}
1064 1065 1066 1067 1068
     */
    public function getName()
    {
        return 'postgresql';
    }
1069

1070
    /**
1071
     * {@inheritDoc}
1072
     *
1073 1074
     * PostgreSQL returns all column names in SQL result sets in lowercase.
     */
1075
    public function getSQLResultCasing($column)
1076 1077 1078
    {
        return strtolower($column);
    }
1079

1080 1081 1082
    /**
     * {@inheritDoc}
     */
1083
    public function getDateTimeTzFormatString()
1084
    {
1085 1086
        return 'Y-m-d H:i:sO';
    }
1087 1088

    /**
1089
     * {@inheritDoc}
1090
     */
1091
    public function getEmptyIdentityInsertSQL($quotedTableName, $quotedIdentifierColumnName)
1092 1093 1094
    {
        return 'INSERT INTO ' . $quotedTableName . ' (' . $quotedIdentifierColumnName . ') VALUES (DEFAULT)';
    }
1095 1096

    /**
1097
     * {@inheritDoc}
1098
     */
1099
    public function getTruncateTableSQL($tableName, $cascade = false)
1100
    {
1101
        $tableIdentifier = new Identifier($tableName);
1102
        $sql             = 'TRUNCATE ' . $tableIdentifier->getQuotedName($this);
1103 1104 1105 1106 1107 1108

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

        return $sql;
1109
    }
1110

1111 1112 1113
    /**
     * {@inheritDoc}
     */
1114 1115 1116 1117
    public function getReadLockSQL()
    {
        return 'FOR SHARE';
    }
1118

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

1167 1168 1169
    /**
     * {@inheritDoc}
     */
1170 1171 1172 1173
    public function getVarcharMaxLength()
    {
        return 65535;
    }
1174

Steve Müller's avatar
Steve Müller committed
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
    /**
     * {@inheritdoc}
     */
    public function getBinaryMaxLength()
    {
        return 0;
    }

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

1191 1192 1193
    /**
     * {@inheritDoc}
     */
1194 1195
    protected function getReservedKeywordsClass()
    {
1196
        return Keywords\PostgreSQLKeywords::class;
1197
    }
1198 1199

    /**
1200
     * {@inheritDoc}
1201 1202 1203 1204 1205
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'BYTEA';
    }
1206

1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
    /**
     * {@inheritdoc}
     */
    public function getDefaultValueDeclarationSQL($field)
    {
        if ($this->isSerialField($field)) {
            return '';
        }

        return parent::getDefaultValueDeclarationSQL($field);
    }

1219 1220 1221
    /**
     * @param mixed[] $field
     */
1222 1223
    private function isSerialField(array $field) : bool
    {
Sergei Morozov's avatar
Sergei Morozov committed
1224 1225
        return isset($field['type'], $field['autoincrement'])
            && $field['autoincrement'] === true
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
            && $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;
1249
    }
1250 1251 1252 1253 1254

    private function getOldColumnComment(ColumnDiff $columnDiff) : ?string
    {
        return $columnDiff->fromColumn ? $this->getColumnComment($columnDiff->fromColumn) : null;
    }
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269

    public function getListTableMetadataSQL(string $table, ?string $schema = null) : string
    {
        if ($schema !== null) {
            $table = $schema . '.' . $table;
        }

        return sprintf(
            <<<'SQL'
SELECT obj_description(%s::regclass) AS table_comment;
SQL
            ,
            $this->quoteStringLiteral($table)
        );
    }
1270
}