DB2Platform.php 24.7 KB
Newer Older
1 2 3 4
<?php

namespace Doctrine\DBAL\Platforms;

5
use Doctrine\DBAL\DBALException;
6
use Doctrine\DBAL\Schema\ColumnDiff;
7
use Doctrine\DBAL\Schema\Identifier;
8 9
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\TableDiff;
10
use Doctrine\DBAL\Types\Type;
11
use Doctrine\DBAL\Types\Types;
12

13 14 15 16
use function array_merge;
use function count;
use function current;
use function explode;
17 18
use function func_get_arg;
use function func_num_args;
19 20 21 22
use function implode;
use function sprintf;
use function strpos;
use function strtoupper;
23

24
class DB2Platform extends AbstractPlatform
25
{
26
    public function getCharMaxLength(): int
Sergei Morozov's avatar
Sergei Morozov committed
27 28 29 30
    {
        return 254;
    }

Steve Müller's avatar
Steve Müller committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
    /**
     * {@inheritdoc}
     */
    public function getBinaryMaxLength()
    {
        return 32704;
    }

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

Sergei Morozov's avatar
Sergei Morozov committed
47 48 49
    /**
     * {@inheritDoc}
     */
50
    public function getVarcharTypeDeclarationSQL(array $column)
Sergei Morozov's avatar
Sergei Morozov committed
51 52
    {
        // for IBM DB2, the CHAR max length is less than VARCHAR default length
53 54
        if (! isset($column['length']) && ! empty($column['fixed'])) {
            $column['length'] = $this->getCharMaxLength();
Sergei Morozov's avatar
Sergei Morozov committed
55 56
        }

57
        return parent::getVarcharTypeDeclarationSQL($column);
Sergei Morozov's avatar
Sergei Morozov committed
58 59
    }

60
    /**
61
     * {@inheritDoc}
62
     */
63
    public function getBlobTypeDeclarationSQL(array $column)
64
    {
65
        // todo blob(n) with $column['length'];
66
        return 'BLOB(1M)';
67 68
    }

69 70 71
    /**
     * {@inheritDoc}
     */
72 73
    public function initializeDoctrineTypeMappings()
    {
74
        $this->doctrineTypeMapping = [
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
            'bigint'    => 'bigint',
            'binary'    => 'binary',
            'blob'      => 'blob',
            'character' => 'string',
            'clob'      => 'text',
            'date'      => 'date',
            'decimal'   => 'decimal',
            'double'    => 'float',
            'integer'   => 'integer',
            'real'      => 'float',
            'smallint'  => 'smallint',
            'time'      => 'time',
            'timestamp' => 'datetime',
            'varbinary' => 'binary',
            'varchar'   => 'string',
90
        ];
91 92
    }

93 94 95 96 97
    /**
     * {@inheritdoc}
     */
    public function isCommentedDoctrineType(Type $doctrineType)
    {
98
        if ($doctrineType->getName() === Types::BOOLEAN) {
99 100 101 102 103 104 105 106
            // We require a commented boolean type in order to distinguish between boolean and smallint
            // as both (have to) map to the same native type.
            return true;
        }

        return parent::isCommentedDoctrineType($doctrineType);
    }

107
    /**
108
     * {@inheritDoc}
109
     */
110
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
111
    {
112 113
        return $fixed ? ($length > 0 ? 'CHAR(' . $length . ')' : 'CHAR(254)')
                : ($length > 0 ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)');
114 115
    }

Steve Müller's avatar
Steve Müller committed
116 117 118 119 120
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
Sergei Morozov's avatar
Sergei Morozov committed
121
        return $this->getVarcharTypeDeclarationSQLSnippet($length, $fixed) . ' FOR BIT DATA';
Steve Müller's avatar
Steve Müller committed
122 123
    }

124
    /**
125
     * {@inheritDoc}
126
     */
127
    public function getClobTypeDeclarationSQL(array $column)
128
    {
129
        // todo clob(n) with $column['length'];
130 131 132 133
        return 'CLOB(1M)';
    }

    /**
134
     * {@inheritDoc}
135 136 137 138 139 140 141
     */
    public function getName()
    {
        return 'db2';
    }

    /**
142
     * {@inheritDoc}
143
     */
144
    public function getBooleanTypeDeclarationSQL(array $column)
145 146 147 148 149
    {
        return 'SMALLINT';
    }

    /**
150
     * {@inheritDoc}
151
     */
152
    public function getIntegerTypeDeclarationSQL(array $column)
153
    {
154
        return 'INTEGER' . $this->_getCommonIntegerTypeDeclarationSQL($column);
155 156 157
    }

    /**
158
     * {@inheritDoc}
159
     */
160
    public function getBigIntTypeDeclarationSQL(array $column)
161
    {
162
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($column);
163 164 165
    }

    /**
166
     * {@inheritDoc}
167
     */
168
    public function getSmallIntTypeDeclarationSQL(array $column)
169
    {
170
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($column);
171 172 173
    }

    /**
174
     * {@inheritDoc}
175
     */
176
    protected function _getCommonIntegerTypeDeclarationSQL(array $column)
177
    {
178
        $autoinc = '';
179
        if (! empty($column['autoincrement'])) {
180 181
            $autoinc = ' GENERATED BY DEFAULT AS IDENTITY';
        }
182

183
        return $autoinc;
184 185
    }

186 187
    /**
     * {@inheritdoc}
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
     */
    public function getBitAndComparisonExpression($value1, $value2)
    {
        return 'BITAND(' . $value1 . ', ' . $value2 . ')';
    }

    /**
     * {@inheritdoc}
     */
    public function getBitOrComparisonExpression($value1, $value2)
    {
        return 'BITOR(' . $value1 . ', ' . $value2 . ')';
    }

    /**
     * {@inheritdoc}
204
     */
205 206 207
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
    {
        switch ($unit) {
208
            case DateIntervalUnit::WEEK:
209
                $interval *= 7;
210
                $unit      = DateIntervalUnit::DAY;
211 212
                break;

213
            case DateIntervalUnit::QUARTER:
214
                $interval *= 3;
215
                $unit      = DateIntervalUnit::MONTH;
216 217
                break;
        }
218

219
        return $date . ' ' . $operator . ' ' . $interval . ' ' . $unit;
220 221 222 223 224 225 226 227 228 229
    }

    /**
     * {@inheritdoc}
     */
    public function getDateDiffExpression($date1, $date2)
    {
        return 'DAYS(' . $date1 . ') - DAYS(' . $date2 . ')';
    }

230
    /**
231
     * {@inheritDoc}
232
     */
233
    public function getDateTimeTypeDeclarationSQL(array $column)
234
    {
235
        if (isset($column['version']) && $column['version'] === true) {
236
            return 'TIMESTAMP(0) WITH DEFAULT';
237 238
        }

239 240 241 242
        return 'TIMESTAMP(0)';
    }

    /**
243
     * {@inheritDoc}
244
     */
245
    public function getDateTypeDeclarationSQL(array $column)
246 247 248 249 250
    {
        return 'DATE';
    }

    /**
251
     * {@inheritDoc}
252
     */
253
    public function getTimeTypeDeclarationSQL(array $column)
254 255 256 257
    {
        return 'TIME';
    }

258 259 260 261 262
    /**
     * {@inheritdoc}
     */
    public function getTruncateTableSQL($tableName, $cascade = false)
    {
263 264 265
        $tableIdentifier = new Identifier($tableName);

        return 'TRUNCATE ' . $tableIdentifier->getQuotedName($this) . ' IMMEDIATE';
266 267
    }

268
    /**
269
     * This code fragment is originally from the Zend_Db_Adapter_Db2 class, but has been edited.
270
     *
Benjamin Morel's avatar
Benjamin Morel committed
271
     * @param string $table
Christophe Coevoet's avatar
Christophe Coevoet committed
272
     * @param string $database
Benjamin Morel's avatar
Benjamin Morel committed
273
     *
274 275
     * @return string
     */
276
    public function getListTableColumnsSQL($table, $database = null)
277
    {
278 279
        $table = $this->quoteStringLiteral($table);

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
        // We do the funky subquery and join syscat.columns.default this crazy way because
        // as of db2 v10, the column is CLOB(64k) and the distinct operator won't allow a CLOB,
        // it wants shorter stuff like a varchar.
        return "
        SELECT
          cols.default,
          subq.*
        FROM (
               SELECT DISTINCT
                 c.tabschema,
                 c.tabname,
                 c.colname,
                 c.colno,
                 c.typename,
                 c.nulls,
                 c.length,
                 c.scale,
                 c.identity,
                 tc.type AS tabconsttype,
299
                 c.remarks AS comment,
300 301 302 303 304 305 306 307 308 309 310 311 312
                 k.colseq,
                 CASE
                 WHEN c.generated = 'D' THEN 1
                 ELSE 0
                 END     AS autoincrement
               FROM syscat.columns c
                 LEFT JOIN (syscat.keycoluse k JOIN syscat.tabconst tc
                     ON (k.tabschema = tc.tabschema
                         AND k.tabname = tc.tabname
                         AND tc.type = 'P'))
                   ON (c.tabschema = k.tabschema
                       AND c.tabname = k.tabname
                       AND c.colname = k.colname)
313
               WHERE UPPER(c.tabname) = UPPER(" . $table . ')
314 315 316 317 318 319 320
               ORDER BY c.colno
             ) subq
          JOIN syscat.columns cols
            ON subq.tabschema = cols.tabschema
               AND subq.tabname = cols.tabname
               AND subq.colno = cols.colno
        ORDER BY subq.colno
321
        ';
322 323
    }

Benjamin Morel's avatar
Benjamin Morel committed
324 325 326
    /**
     * {@inheritDoc}
     */
327 328
    public function getListTablesSQL()
    {
329
        return "SELECT NAME FROM SYSIBM.SYSTABLES WHERE TYPE = 'T'";
330 331 332
    }

    /**
333
     * {@inheritDoc}
334 335 336
     */
    public function getListViewsSQL($database)
    {
337
        return 'SELECT NAME, TEXT FROM SYSIBM.SYSVIEWS';
338 339
    }

340 341 342
    /**
     * {@inheritDoc}
     */
343
    public function getListTableIndexesSQL($table, $database = null)
344
    {
345 346
        $table = $this->quoteStringLiteral($table);

347 348 349 350 351 352 353 354 355 356 357 358 359
        return "SELECT   idx.INDNAME AS key_name,
                         idxcol.COLNAME AS column_name,
                         CASE
                             WHEN idx.UNIQUERULE = 'P' THEN 1
                             ELSE 0
                         END AS primary,
                         CASE
                             WHEN idx.UNIQUERULE = 'D' THEN 1
                             ELSE 0
                         END AS non_unique
                FROM     SYSCAT.INDEXES AS idx
                JOIN     SYSCAT.INDEXCOLUSE AS idxcol
                ON       idx.INDSCHEMA = idxcol.INDSCHEMA AND idx.INDNAME = idxcol.INDNAME
360 361
                WHERE    idx.TABNAME = UPPER(" . $table . ')
                ORDER BY idxcol.COLSEQ ASC';
362 363
    }

Benjamin Morel's avatar
Benjamin Morel committed
364 365 366
    /**
     * {@inheritDoc}
     */
367 368
    public function getListTableForeignKeysSQL($table)
    {
369 370
        $table = $this->quoteStringLiteral($table);

371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
        return "SELECT   fkcol.COLNAME AS local_column,
                         fk.REFTABNAME AS foreign_table,
                         pkcol.COLNAME AS foreign_column,
                         fk.CONSTNAME AS index_name,
                         CASE
                             WHEN fk.UPDATERULE = 'R' THEN 'RESTRICT'
                             ELSE NULL
                         END AS on_update,
                         CASE
                             WHEN fk.DELETERULE = 'C' THEN 'CASCADE'
                             WHEN fk.DELETERULE = 'N' THEN 'SET NULL'
                             WHEN fk.DELETERULE = 'R' THEN 'RESTRICT'
                             ELSE NULL
                         END AS on_delete
                FROM     SYSCAT.REFERENCES AS fk
                JOIN     SYSCAT.KEYCOLUSE AS fkcol
                ON       fk.CONSTNAME = fkcol.CONSTNAME
                AND      fk.TABSCHEMA = fkcol.TABSCHEMA
                AND      fk.TABNAME = fkcol.TABNAME
                JOIN     SYSCAT.KEYCOLUSE AS pkcol
                ON       fk.REFKEYNAME = pkcol.CONSTNAME
                AND      fk.REFTABSCHEMA = pkcol.TABSCHEMA
                AND      fk.REFTABNAME = pkcol.TABNAME
394 395
                WHERE    fk.TABNAME = UPPER(" . $table . ')
                ORDER BY fkcol.COLSEQ ASC';
396 397
    }

Benjamin Morel's avatar
Benjamin Morel committed
398 399 400
    /**
     * {@inheritDoc}
     */
401 402
    public function getCreateViewSQL($name, $sql)
    {
403
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
404 405
    }

Benjamin Morel's avatar
Benjamin Morel committed
406 407 408
    /**
     * {@inheritDoc}
     */
409 410
    public function getDropViewSQL($name)
    {
411
        return 'DROP VIEW ' . $name;
412 413
    }

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

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

430 431 432
    /**
     * {@inheritDoc}
     */
433 434 435 436
    public function supportsCreateDropDatabase()
    {
        return false;
    }
437

438
    /**
439
     * {@inheritDoc}
440 441 442 443 444 445
     */
    public function supportsReleaseSavepoints()
    {
        return false;
    }

446 447 448 449 450 451 452 453
    /**
     * {@inheritdoc}
     */
    public function supportsCommentOnStatement()
    {
        return true;
    }

454
    /**
455
     * {@inheritDoc}
456 457 458
     */
    public function getCurrentDateSQL()
    {
459
        return 'CURRENT DATE';
460 461 462
    }

    /**
463
     * {@inheritDoc}
464 465 466
     */
    public function getCurrentTimeSQL()
    {
467
        return 'CURRENT TIME';
468 469 470
    }

    /**
471
     * {@inheritDoc}
472
     */
473
    public function getCurrentTimestampSQL()
474
    {
475
        return 'CURRENT TIMESTAMP';
476
    }
477 478

    /**
479
     * {@inheritDoc}
480 481 482
     */
    public function getIndexDeclarationSQL($name, Index $index)
    {
483 484
        // Index declaration in statements like CREATE TABLE is not supported.
        throw DBALException::notSupported(__METHOD__);
485 486 487
    }

    /**
488
     * {@inheritDoc}
489
     */
490
    protected function _getCreateTableSQL($tableName, array $columns, array $options = [])
491
    {
492
        $indexes = [];
493 494 495
        if (isset($options['indexes'])) {
            $indexes = $options['indexes'];
        }
Grégoire Paris's avatar
Grégoire Paris committed
496

497
        $options['indexes'] = [];
498

499 500
        $sqls = parent::_getCreateTableSQL($tableName, $columns, $options);

501
        foreach ($indexes as $definition) {
502 503
            $sqls[] = $this->getCreateIndexSQL($definition, $tableName);
        }
504

505 506 507 508
        return $sqls;
    }

    /**
509
     * {@inheritDoc}
510 511 512
     */
    public function getAlterTableSQL(TableDiff $diff)
    {
513 514
        $sql         = [];
        $columnSql   = [];
515
        $commentsSQL = [];
516

517
        $queryParts = [];
518
        foreach ($diff->addedColumns as $column) {
519 520
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
521 522
            }

523 524 525 526
            $columnDef = $column->toArray();
            $queryPart = 'ADD COLUMN ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnDef);

            // Adding non-nullable columns to a table requires a default value to be specified.
527 528
            if (
                ! empty($columnDef['notnull']) &&
529 530 531 532 533 534 535
                ! isset($columnDef['default']) &&
                empty($columnDef['autoincrement'])
            ) {
                $queryPart .= ' WITH DEFAULT';
            }

            $queryParts[] = $queryPart;
536 537 538

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

539 540
            if ($comment === null || $comment === '') {
                continue;
541
            }
542 543 544 545 546 547

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

550
        foreach ($diff->removedColumns as $column) {
551 552
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
553 554
            }

555
            $queryParts[] =  'DROP COLUMN ' . $column->getQuotedName($this);
556 557
        }

558
        foreach ($diff->changedColumns as $columnDiff) {
559 560
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
561 562
            }

563 564 565 566 567 568 569 570 571 572 573 574
            if ($columnDiff->hasChanged('comment')) {
                $commentsSQL[] = $this->getCommentOnColumnSQL(
                    $diff->getName($this)->getQuotedName($this),
                    $columnDiff->column->getQuotedName($this),
                    $this->getColumnComment($columnDiff->column)
                );

                if (count($columnDiff->changedProperties) === 1) {
                    continue;
                }
            }

Sergei Morozov's avatar
Sergei Morozov committed
575
            $this->gatherAlterColumnSQL($diff->getName($this), $columnDiff, $sql, $queryParts);
576 577
        }

578
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
579 580
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
581 582
            }

583 584 585 586
            $oldColumnName = new Identifier($oldColumnName);

            $queryParts[] =  'RENAME COLUMN ' . $oldColumnName->getQuotedName($this) .
                ' TO ' . $column->getQuotedName($this);
587 588
        }

589
        $tableSql = [];
590

591
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
592
            if (count($queryParts) > 0) {
593
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . implode(' ', $queryParts);
594
            }
595

596
            // Some table alteration operations require a table reorganization.
597
            if (! empty($diff->removedColumns) || ! empty($diff->changedColumns)) {
598 599 600
                $sql[] = "CALL SYSPROC.ADMIN_CMD ('REORG TABLE " . $diff->getName($this)->getQuotedName($this) . "')";
            }

601 602
            $sql = array_merge($sql, $commentsSQL);

Sergei Morozov's avatar
Sergei Morozov committed
603 604 605 606 607 608 609 610
            $newName = $diff->getNewName();

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

613 614 615 616 617
            $sql = array_merge(
                $this->getPreAlterTableIndexForeignKeySQL($diff),
                $sql,
                $this->getPostAlterTableIndexForeignKeySQL($diff)
            );
618 619
        }

620
        return array_merge($sql, $tableSql, $columnSql);
621 622
    }

623 624 625
    /**
     * Gathers the table alteration SQL for a given column diff.
     *
Sergei Morozov's avatar
Sergei Morozov committed
626
     * @param Identifier $table      The table to gather the SQL for.
627
     * @param ColumnDiff $columnDiff The column diff to evaluate.
628 629
     * @param string[]   $sql        The sequence of table alteration statements to fill.
     * @param mixed[]    $queryParts The sequence of column alteration clauses to fill.
630
     */
Sergei Morozov's avatar
Sergei Morozov committed
631 632 633 634 635 636
    private function gatherAlterColumnSQL(
        Identifier $table,
        ColumnDiff $columnDiff,
        array &$sql,
        array &$queryParts
    ): void {
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
        $alterColumnClauses = $this->getAlterColumnClausesSQL($columnDiff);

        if (empty($alterColumnClauses)) {
            return;
        }

        // If we have a single column alteration, we can append the clause to the main query.
        if (count($alterColumnClauses) === 1) {
            $queryParts[] = current($alterColumnClauses);

            return;
        }

        // We have multiple alterations for the same column,
        // so we need to trigger a complete ALTER TABLE statement
        // for each ALTER COLUMN clause.
        foreach ($alterColumnClauses as $alterColumnClause) {
            $sql[] = 'ALTER TABLE ' . $table->getQuotedName($this) . ' ' . $alterColumnClause;
        }
    }

    /**
     * Returns the ALTER COLUMN SQL clauses for altering a column described by the given column diff.
     *
     * @param ColumnDiff $columnDiff The column diff to evaluate.
     *
663
     * @return string[]
664 665 666 667 668 669 670
     */
    private function getAlterColumnClausesSQL(ColumnDiff $columnDiff)
    {
        $column = $columnDiff->column->toArray();

        $alterClause = 'ALTER COLUMN ' . $columnDiff->column->getQuotedName($this);

671
        if ($column['columnDefinition'] !== null) {
672
            return [$alterClause . ' ' . $column['columnDefinition']];
673 674
        }

675
        $clauses = [];
676

677 678
        if (
            $columnDiff->hasChanged('type') ||
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
            $columnDiff->hasChanged('length') ||
            $columnDiff->hasChanged('precision') ||
            $columnDiff->hasChanged('scale') ||
            $columnDiff->hasChanged('fixed')
        ) {
            $clauses[] = $alterClause . ' SET DATA TYPE ' . $column['type']->getSQLDeclaration($column, $this);
        }

        if ($columnDiff->hasChanged('notnull')) {
            $clauses[] = $column['notnull'] ? $alterClause . ' SET NOT NULL' : $alterClause . ' DROP NOT NULL';
        }

        if ($columnDiff->hasChanged('default')) {
            if (isset($column['default'])) {
                $defaultClause = $this->getDefaultValueDeclarationSQL($column);

695
                if ($defaultClause !== '') {
696 697 698 699 700 701 702 703 704 705
                    $clauses[] = $alterClause . ' SET' . $defaultClause;
                }
            } else {
                $clauses[] = $alterClause . ' DROP DEFAULT';
            }
        }

        return $clauses;
    }

706 707 708 709 710
    /**
     * {@inheritDoc}
     */
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
    {
711
        $sql   = [];
712
        $table = $diff->getName($this)->getQuotedName($this);
713 714 715

        foreach ($diff->removedIndexes as $remKey => $remIndex) {
            foreach ($diff->addedIndexes as $addKey => $addIndex) {
Grégoire Paris's avatar
Grégoire Paris committed
716 717 718
                if ($remIndex->getColumns() !== $addIndex->getColumns()) {
                    continue;
                }
719

Grégoire Paris's avatar
Grégoire Paris committed
720 721 722 723 724 725 726
                if ($remIndex->isPrimary()) {
                    $sql[] = 'ALTER TABLE ' . $table . ' DROP PRIMARY KEY';
                } elseif ($remIndex->isUnique()) {
                    $sql[] = 'ALTER TABLE ' . $table . ' DROP UNIQUE ' . $remIndex->getQuotedName($this);
                } else {
                    $sql[] = $this->getDropIndexSQL($remIndex, $table);
                }
727

Grégoire Paris's avatar
Grégoire Paris committed
728
                $sql[] = $this->getCreateIndexSQL($addIndex, $table);
729

Grégoire Paris's avatar
Grégoire Paris committed
730 731 732
                unset($diff->removedIndexes[$remKey], $diff->addedIndexes[$addKey]);

                break;
733 734 735 736 737 738 739 740
            }
        }

        $sql = array_merge($sql, parent::getPreAlterTableIndexForeignKeySQL($diff));

        return $sql;
    }

741 742 743 744 745
    /**
     * {@inheritdoc}
     */
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
    {
746
        if (strpos($tableName, '.') !== false) {
747
            [$schema]     = explode('.', $tableName);
748 749 750
            $oldIndexName = $schema . '.' . $oldIndexName;
        }

751
        return ['RENAME INDEX ' . $oldIndexName . ' TO ' . $index->getQuotedName($this)];
752 753
    }

754 755 756
    /**
     * {@inheritDoc}
     */
757
    public function getDefaultValueDeclarationSQL($column)
758
    {
759
        if (! empty($column['autoincrement'])) {
760
            return '';
761 762
        }

763
        if (! empty($column['version'])) {
764 765
            if ((string) $column['type'] !== 'DateTime') {
                $column['default'] = '1';
766 767 768
            }
        }

769
        return parent::getDefaultValueDeclarationSQL($column);
770 771
    }

772
    /**
773
     * {@inheritDoc}
774 775 776 777 778 779
     */
    public function getEmptyIdentityInsertSQL($tableName, $identifierColumnName)
    {
        return 'INSERT INTO ' . $tableName . ' (' . $identifierColumnName . ') VALUES (DEFAULT)';
    }

Benjamin Morel's avatar
Benjamin Morel committed
780 781 782
    /**
     * {@inheritDoc}
     */
783 784
    public function getCreateTemporaryTableSnippetSQL()
    {
785
        return 'DECLARE GLOBAL TEMPORARY TABLE';
786 787 788
    }

    /**
789
     * {@inheritDoc}
790 791 792
     */
    public function getTemporaryTableName($tableName)
    {
793
        return 'SESSION.' . $tableName;
794 795
    }

796 797 798
    /**
     * {@inheritDoc}
     */
799
    protected function doModifyLimitQuery($query, $limit, $offset = null)
800
    {
801
        $where = [];
802 803 804

        if ($offset > 0) {
            $where[] = sprintf('db22.DC_ROWNUM >= %d', $offset + 1);
805 806
        }

807 808 809
        if ($limit !== null) {
            $where[] = sprintf('db22.DC_ROWNUM <= %d', $offset + $limit);
        }
810

811 812 813
        if (empty($where)) {
            return $query;
        }
814

815 816 817 818 819 820
        // Todo OVER() needs ORDER BY data!
        return sprintf(
            'SELECT db22.* FROM (SELECT db21.*, ROW_NUMBER() OVER() AS DC_ROWNUM FROM (%s) db21) db22 WHERE %s',
            $query,
            implode(' AND ', $where)
        );
821 822 823
    }

    /**
824
     * {@inheritDoc}
825 826 827
     */
    public function getLocateExpression($str, $substr, $startPos = false)
    {
828
        if ($startPos === false) {
829 830
            return 'LOCATE(' . $substr . ', ' . $str . ')';
        }
831

832
        return 'LOCATE(' . $substr . ', ' . $str . ', ' . $startPos . ')';
833 834 835
    }

    /**
836
     * {@inheritDoc}
837
     */
838
    public function getSubstringExpression($value, $from, $length = null)
839
    {
840
        if ($length === null) {
841 842
            return 'SUBSTR(' . $value . ', ' . $from . ')';
        }
843 844

        return 'SUBSTR(' . $value . ', ' . $from . ', ' . $length . ')';
845 846
    }

847 848 849 850 851
    public function getCurrentDatabaseExpression(): string
    {
        return 'CURRENT_USER';
    }

852 853 854
    /**
     * {@inheritDoc}
     */
855 856 857 858 859
    public function supportsIdentityColumns()
    {
        return true;
    }

860 861 862
    /**
     * {@inheritDoc}
     */
863 864 865 866
    public function prefersIdentityColumns()
    {
        return true;
    }
867 868

    /**
869
     * {@inheritDoc}
870 871 872 873 874 875 876
     *
     * DB2 returns all column names in SQL result sets in uppercase.
     */
    public function getSQLResultCasing($column)
    {
        return strtoupper($column);
    }
877

Benjamin Morel's avatar
Benjamin Morel committed
878 879 880
    /**
     * {@inheritDoc}
     */
881 882 883 884
    public function getForUpdateSQL()
    {
        return ' WITH RR USE AND KEEP UPDATE LOCKS';
    }
885

886 887 888
    /**
     * {@inheritDoc}
     */
889 890
    public function getDummySelectSQL()
    {
891 892 893
        $expression = func_num_args() > 0 ? func_get_arg(0) : '1';

        return sprintf('SELECT %s FROM sysibm.sysdummy1', $expression);
894
    }
895 896

    /**
897 898
     * {@inheritDoc}
     *
899 900 901 902 903 904 905 906
     * DB2 supports savepoints, but they work semantically different than on other vendor platforms.
     *
     * TODO: We have to investigate how to get DB2 up and running with savepoints.
     */
    public function supportsSavepoints()
    {
        return false;
    }
907

908 909 910
    /**
     * {@inheritDoc}
     */
911 912
    protected function getReservedKeywordsClass()
    {
913
        return Keywords\DB2Keywords::class;
914
    }
915

916
    public function getListTableCommentsSQL(string $table): string
917 918 919 920 921 922 923 924 925 926 927
    {
        return sprintf(
            <<<'SQL'
SELECT REMARKS
  FROM SYSIBM.SYSTABLES
  WHERE NAME = UPPER( %s )
SQL
            ,
            $this->quoteStringLiteral($table)
        );
    }
928
}