DB2Platform.php 24.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
Benjamin Eberlei's avatar
Benjamin Eberlei committed
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
Benjamin Morel's avatar
Benjamin Morel committed
18
 */
19 20 21

namespace Doctrine\DBAL\Platforms;

22
use Doctrine\DBAL\DBALException;
23
use Doctrine\DBAL\Schema\ColumnDiff;
24
use Doctrine\DBAL\Schema\Identifier;
25
use Doctrine\DBAL\Schema\Index;
26
use Doctrine\DBAL\Schema\Table;
27
use Doctrine\DBAL\Schema\TableDiff;
28
use Doctrine\DBAL\Types\Type;
29 30 31 32 33 34 35 36
use function array_merge;
use function count;
use function current;
use function explode;
use function implode;
use function sprintf;
use function strpos;
use function strtoupper;
37

38
class DB2Platform extends AbstractPlatform
39
{
Steve Müller's avatar
Steve Müller committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
    /**
     * {@inheritdoc}
     */
    public function getBinaryMaxLength()
    {
        return 32704;
    }

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

56
    /**
57
     * {@inheritDoc}
58 59 60
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
61 62
        // todo blob(n) with $field['length'];
        return 'BLOB(1M)';
63 64
    }

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

89 90 91 92 93 94 95 96 97 98 99 100 101 102
    /**
     * {@inheritdoc}
     */
    public function isCommentedDoctrineType(Type $doctrineType)
    {
        if ($doctrineType->getName() === Type::BOOLEAN) {
            // 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);
    }

103
    /**
104
     * {@inheritDoc}
105
     */
106
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
107 108 109 110 111
    {
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
                : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)');
    }

Steve Müller's avatar
Steve Müller committed
112 113 114 115 116 117 118 119
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
        return $fixed ? 'BINARY(' . ($length ?: 255) . ')' : 'VARBINARY(' . ($length ?: 255) . ')';
    }

120
    /**
121
     * {@inheritDoc}
122 123 124 125 126 127 128 129
     */
    public function getClobTypeDeclarationSQL(array $field)
    {
        // todo clob(n) with $field['length'];
        return 'CLOB(1M)';
    }

    /**
130
     * {@inheritDoc}
131 132 133 134 135 136 137
     */
    public function getName()
    {
        return 'db2';
    }

    /**
138
     * {@inheritDoc}
139 140 141 142 143 144 145
     */
    public function getBooleanTypeDeclarationSQL(array $columnDef)
    {
        return 'SMALLINT';
    }

    /**
146
     * {@inheritDoc}
147 148 149
     */
    public function getIntegerTypeDeclarationSQL(array $columnDef)
    {
150
        return 'INTEGER' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
151 152 153
    }

    /**
154
     * {@inheritDoc}
155 156 157
     */
    public function getBigIntTypeDeclarationSQL(array $columnDef)
    {
158
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
159 160 161
    }

    /**
162
     * {@inheritDoc}
163 164 165
     */
    public function getSmallIntTypeDeclarationSQL(array $columnDef)
    {
166
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
167 168 169
    }

    /**
170
     * {@inheritDoc}
171 172 173
     */
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
    {
174 175 176 177
        $autoinc = '';
        if ( ! empty($columnDef['autoincrement'])) {
            $autoinc = ' GENERATED BY DEFAULT AS IDENTITY';
        }
178

179
        return $autoinc;
180 181
    }

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

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

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

209
            case DateIntervalUnit::QUARTER:
210
                $interval *= 3;
211
                $unit      = DateIntervalUnit::MONTH;
212 213
                break;
        }
214

215
        return $date . ' ' . $operator . ' ' . $interval . ' ' . $unit;
216 217 218 219 220 221 222 223 224 225
    }

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

226
    /**
227
     * {@inheritDoc}
228 229 230
     */
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
    {
231 232 233 234
        if (isset($fieldDeclaration['version']) && $fieldDeclaration['version'] == true) {
            return "TIMESTAMP(0) WITH DEFAULT";
        }

235 236 237 238
        return 'TIMESTAMP(0)';
    }

    /**
239
     * {@inheritDoc}
240 241 242 243 244 245 246
     */
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
    {
        return 'DATE';
    }

    /**
247
     * {@inheritDoc}
248 249 250 251 252 253
     */
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
    {
        return 'TIME';
    }

254 255 256 257 258
    /**
     * {@inheritdoc}
     */
    public function getTruncateTableSQL($tableName, $cascade = false)
    {
259 260 261
        $tableIdentifier = new Identifier($tableName);

        return 'TRUNCATE ' . $tableIdentifier->getQuotedName($this) . ' IMMEDIATE';
262 263
    }

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

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
        // 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,
297
                 c.remarks AS comment,
298 299 300 301 302 303 304 305 306 307 308 309 310
                 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)
311
               WHERE UPPER(c.tabname) = UPPER(" . $table . ")
312 313 314 315 316 317 318 319
               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
        ";
320 321
    }

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

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

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

345 346 347 348 349 350 351 352 353 354 355 356 357
        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
358
                WHERE    idx.TABNAME = UPPER(" . $table . ")
359
                ORDER BY idxcol.COLSEQ ASC";
360 361
    }

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

369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
        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
392
                WHERE    fk.TABNAME = UPPER(" . $table . ")
393
                ORDER BY fkcol.COLSEQ ASC";
394 395
    }

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

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

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

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

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

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

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

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

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

    /**
469
     * {@inheritDoc}
470
     */
471
    public function getCurrentTimestampSQL()
472
    {
473
        return "CURRENT TIMESTAMP";
474
    }
475 476

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

    /**
486
     * {@inheritDoc}
487
     */
488
    protected function _getCreateTableSQL($tableName, array $columns, array $options = [])
489
    {
490
        $indexes = [];
491 492 493
        if (isset($options['indexes'])) {
            $indexes = $options['indexes'];
        }
494
        $options['indexes'] = [];
495

496 497
        $sqls = parent::_getCreateTableSQL($tableName, $columns, $options);

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

    /**
505
     * {@inheritDoc}
506 507 508
     */
    public function getAlterTableSQL(TableDiff $diff)
    {
509 510 511
        $sql = [];
        $columnSql = [];
        $commentsSQL = [];
512

513
        $queryParts = [];
514
        foreach ($diff->addedColumns as $column) {
515 516
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
517 518
            }

519 520 521 522 523 524 525 526 527 528 529 530
            $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.
            if ( ! empty($columnDef['notnull']) &&
                ! isset($columnDef['default']) &&
                empty($columnDef['autoincrement'])
            ) {
                $queryPart .= ' WITH DEFAULT';
            }

            $queryParts[] = $queryPart;
531 532 533 534 535 536 537 538 539 540

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

            if (null !== $comment && '' !== $comment) {
                $commentsSQL[] = $this->getCommentOnColumnSQL(
                    $diff->getName($this)->getQuotedName($this),
                    $column->getQuotedName($this),
                    $comment
                );
            }
541 542
        }

543
        foreach ($diff->removedColumns as $column) {
544 545
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
546 547
            }

548
            $queryParts[] =  'DROP COLUMN ' . $column->getQuotedName($this);
549 550
        }

551
        foreach ($diff->changedColumns as $columnDiff) {
552 553
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
554 555
            }

556 557 558 559 560 561 562 563 564 565 566 567 568
            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;
                }
            }

            $this->gatherAlterColumnSQL($diff->fromTable, $columnDiff, $sql, $queryParts);
569 570
        }

571
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
572 573
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
574 575
            }

576 577 578 579
            $oldColumnName = new Identifier($oldColumnName);

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

582
        $tableSql = [];
583

584
        if ( ! $this->onSchemaAlterTable($diff, $tableSql)) {
585
            if (count($queryParts) > 0) {
586
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . implode(" ", $queryParts);
587
            }
588

589 590
            // Some table alteration operations require a table reorganization.
            if ( ! empty($diff->removedColumns) || ! empty($diff->changedColumns)) {
591 592 593
                $sql[] = "CALL SYSPROC.ADMIN_CMD ('REORG TABLE " . $diff->getName($this)->getQuotedName($this) . "')";
            }

594 595
            $sql = array_merge($sql, $commentsSQL);

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

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

607
        return array_merge($sql, $tableSql, $columnSql);
608 609
    }

610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
    /**
     * Gathers the table alteration SQL for a given column diff.
     *
     * @param Table      $table      The table to gather the SQL for.
     * @param ColumnDiff $columnDiff The column diff to evaluate.
     * @param array      $sql        The sequence of table alteration statements to fill.
     * @param array      $queryParts The sequence of column alteration clauses to fill.
     */
    private function gatherAlterColumnSQL(Table $table, ColumnDiff $columnDiff, array &$sql, array &$queryParts)
    {
        $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.
     *
     * @return array
     */
    private function getAlterColumnClausesSQL(ColumnDiff $columnDiff)
    {
        $column = $columnDiff->column->toArray();

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

        if ($column['columnDefinition']) {
655
            return [$alterClause . ' ' . $column['columnDefinition']];
656 657
        }

658
        $clauses = [];
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687

        if ($columnDiff->hasChanged('type') ||
            $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);

                if ($defaultClause) {
                    $clauses[] = $alterClause . ' SET' . $defaultClause;
                }
            } else {
                $clauses[] = $alterClause . ' DROP DEFAULT';
            }
        }

        return $clauses;
    }

688 689 690 691 692
    /**
     * {@inheritDoc}
     */
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
    {
693
        $sql = [];
694
        $table = $diff->getName($this)->getQuotedName($this);
695 696 697 698 699 700 701 702 703 704 705 706 707 708

        foreach ($diff->removedIndexes as $remKey => $remIndex) {
            foreach ($diff->addedIndexes as $addKey => $addIndex) {
                if ($remIndex->getColumns() == $addIndex->getColumns()) {
                    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);
                    }

                    $sql[] = $this->getCreateIndexSQL($addIndex, $table);

709
                    unset($diff->removedIndexes[$remKey], $diff->addedIndexes[$addKey]);
710 711 712 713 714 715 716 717 718 719 720

                    break;
                }
            }
        }

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

        return $sql;
    }

721 722 723 724 725
    /**
     * {@inheritdoc}
     */
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
    {
726 727 728 729 730
        if (strpos($tableName, '.') !== false) {
            list($schema) = explode('.', $tableName);
            $oldIndexName = $schema . '.' . $oldIndexName;
        }

731
        return ['RENAME INDEX ' . $oldIndexName . ' TO ' . $index->getQuotedName($this)];
732 733
    }

734 735 736
    /**
     * {@inheritDoc}
     */
737 738
    public function getDefaultValueDeclarationSQL($field)
    {
739 740
        if ( ! empty($field['autoincrement'])) {
            return '';
741 742
        }

743
        if (isset($field['version']) && $field['version']) {
744
            if ((string) $field['type'] != "DateTime") {
745 746 747 748
                $field['default'] = "1";
            }
        }

749 750 751
        return parent::getDefaultValueDeclarationSQL($field);
    }

752
    /**
753
     * {@inheritDoc}
754 755 756 757 758 759
     */
    public function getEmptyIdentityInsertSQL($tableName, $identifierColumnName)
    {
        return 'INSERT INTO ' . $tableName . ' (' . $identifierColumnName . ') VALUES (DEFAULT)';
    }

Benjamin Morel's avatar
Benjamin Morel committed
760 761 762
    /**
     * {@inheritDoc}
     */
763 764 765 766 767 768
    public function getCreateTemporaryTableSnippetSQL()
    {
        return "DECLARE GLOBAL TEMPORARY TABLE";
    }

    /**
769
     * {@inheritDoc}
770 771 772 773 774 775
     */
    public function getTemporaryTableName($tableName)
    {
        return "SESSION." . $tableName;
    }

776 777 778
    /**
     * {@inheritDoc}
     */
779
    protected function doModifyLimitQuery($query, $limit, $offset = null)
780
    {
781
        $where = [];
782 783 784

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

787 788 789
        if ($limit !== null) {
            $where[] = sprintf('db22.DC_ROWNUM <= %d', $offset + $limit);
        }
790

791 792 793
        if (empty($where)) {
            return $query;
        }
794

795 796 797 798 799 800
        // 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)
        );
801 802 803
    }

    /**
804
     * {@inheritDoc}
805 806 807 808 809 810
     */
    public function getLocateExpression($str, $substr, $startPos = false)
    {
        if ($startPos == false) {
            return 'LOCATE(' . $substr . ', ' . $str . ')';
        }
811 812

        return 'LOCATE(' . $substr . ', ' . $str . ', '.$startPos.')';
813 814 815
    }

    /**
816
     * {@inheritDoc}
817
     */
818
    public function getSubstringExpression($value, $from, $length = null)
819
    {
820
        if ($length === null) {
821 822
            return 'SUBSTR(' . $value . ', ' . $from . ')';
        }
823 824

        return 'SUBSTR(' . $value . ', ' . $from . ', ' . $length . ')';
825 826
    }

827 828 829
    /**
     * {@inheritDoc}
     */
830 831 832 833 834
    public function supportsIdentityColumns()
    {
        return true;
    }

835 836 837
    /**
     * {@inheritDoc}
     */
838 839 840 841
    public function prefersIdentityColumns()
    {
        return true;
    }
842 843

    /**
844
     * {@inheritDoc}
845 846 847 848 849 850 851
     *
     * DB2 returns all column names in SQL result sets in uppercase.
     */
    public function getSQLResultCasing($column)
    {
        return strtoupper($column);
    }
852

Benjamin Morel's avatar
Benjamin Morel committed
853 854 855
    /**
     * {@inheritDoc}
     */
856 857 858 859
    public function getForUpdateSQL()
    {
        return ' WITH RR USE AND KEEP UPDATE LOCKS';
    }
860

861 862 863
    /**
     * {@inheritDoc}
     */
864 865 866 867
    public function getDummySelectSQL()
    {
        return 'SELECT 1 FROM sysibm.sysdummy1';
    }
868 869

    /**
870 871
     * {@inheritDoc}
     *
872 873 874 875 876 877 878 879
     * 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;
    }
880

881 882 883
    /**
     * {@inheritDoc}
     */
884 885
    protected function getReservedKeywordsClass()
    {
886
        return Keywords\DB2Keywords::class;
887
    }
888
}