DB2Platform.php 24.6 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
use function array_merge;
use function count;
use function current;
use function explode;
16 17
use function func_get_arg;
use function func_num_args;
18 19 20 21
use function implode;
use function sprintf;
use function strpos;
use function strtoupper;
22

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

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

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

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

        return parent::getVarcharTypeDeclarationSQL($field);
    }

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

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

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

106
    /**
107
     * {@inheritDoc}
108
     */
109
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
110
    {
Sergei Morozov's avatar
Sergei Morozov committed
111
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(254)')
112 113 114
                : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)');
    }

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

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

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

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

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

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

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

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

182
        return $autoinc;
183 184
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

504 505 506 507
        return $sqls;
    }

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

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

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

            $queryParts[] = $queryPart;
534 535 536

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

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

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

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

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

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

561 562 563 564 565 566 567 568 569 570 571 572
            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
573
            $this->gatherAlterColumnSQL($diff->getName($this), $columnDiff, $sql, $queryParts);
574 575
        }

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

581 582 583 584
            $oldColumnName = new Identifier($oldColumnName);

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

587
        $tableSql = [];
588

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

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

599 600
            $sql = array_merge($sql, $commentsSQL);

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

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

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

618
        return array_merge($sql, $tableSql, $columnSql);
619 620
    }

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

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

        if ($column['columnDefinition']) {
666
            return [$alterClause . ' ' . $column['columnDefinition']];
667 668
        }

669
        $clauses = [];
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698

        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;
    }

699 700 701 702 703
    /**
     * {@inheritDoc}
     */
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
    {
704
        $sql   = [];
705
        $table = $diff->getName($this)->getQuotedName($this);
706 707 708

        foreach ($diff->removedIndexes as $remKey => $remIndex) {
            foreach ($diff->addedIndexes as $addKey => $addIndex) {
Grégoire Paris's avatar
Grégoire Paris committed
709 710 711
                if ($remIndex->getColumns() !== $addIndex->getColumns()) {
                    continue;
                }
712

Grégoire Paris's avatar
Grégoire Paris committed
713 714 715 716 717 718 719
                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);
                }
720

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

Grégoire Paris's avatar
Grégoire Paris committed
723 724 725
                unset($diff->removedIndexes[$remKey], $diff->addedIndexes[$addKey]);

                break;
726 727 728 729 730 731 732 733
            }
        }

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

        return $sql;
    }

734 735 736 737 738
    /**
     * {@inheritdoc}
     */
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
    {
739
        if (strpos($tableName, '.') !== false) {
740
            [$schema]     = explode('.', $tableName);
741 742 743
            $oldIndexName = $schema . '.' . $oldIndexName;
        }

744
        return ['RENAME INDEX ' . $oldIndexName . ' TO ' . $index->getQuotedName($this)];
745 746
    }

747 748 749
    /**
     * {@inheritDoc}
     */
750 751
    public function getDefaultValueDeclarationSQL($field)
    {
752
        if (! empty($field['autoincrement'])) {
753
            return '';
754 755
        }

756
        if (isset($field['version']) && $field['version']) {
757 758
            if ((string) $field['type'] !== 'DateTime') {
                $field['default'] = '1';
759 760 761
            }
        }

762 763 764
        return parent::getDefaultValueDeclarationSQL($field);
    }

765
    /**
766
     * {@inheritDoc}
767 768 769 770 771 772
     */
    public function getEmptyIdentityInsertSQL($tableName, $identifierColumnName)
    {
        return 'INSERT INTO ' . $tableName . ' (' . $identifierColumnName . ') VALUES (DEFAULT)';
    }

Benjamin Morel's avatar
Benjamin Morel committed
773 774 775
    /**
     * {@inheritDoc}
     */
776 777
    public function getCreateTemporaryTableSnippetSQL()
    {
778
        return 'DECLARE GLOBAL TEMPORARY TABLE';
779 780 781
    }

    /**
782
     * {@inheritDoc}
783 784 785
     */
    public function getTemporaryTableName($tableName)
    {
786
        return 'SESSION.' . $tableName;
787 788
    }

789 790 791
    /**
     * {@inheritDoc}
     */
792
    protected function doModifyLimitQuery($query, $limit, $offset = null)
793
    {
794
        $where = [];
795 796 797

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

800 801 802
        if ($limit !== null) {
            $where[] = sprintf('db22.DC_ROWNUM <= %d', $offset + $limit);
        }
803

804 805 806
        if (empty($where)) {
            return $query;
        }
807

808 809 810 811 812 813
        // 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)
        );
814 815 816
    }

    /**
817
     * {@inheritDoc}
818 819 820
     */
    public function getLocateExpression($str, $substr, $startPos = false)
    {
821
        if ($startPos === false) {
822 823
            return 'LOCATE(' . $substr . ', ' . $str . ')';
        }
824

825
        return 'LOCATE(' . $substr . ', ' . $str . ', ' . $startPos . ')';
826 827 828
    }

    /**
829
     * {@inheritDoc}
830
     */
831
    public function getSubstringExpression($value, $from, $length = null)
832
    {
833
        if ($length === null) {
834 835
            return 'SUBSTR(' . $value . ', ' . $from . ')';
        }
836 837

        return 'SUBSTR(' . $value . ', ' . $from . ', ' . $length . ')';
838 839
    }

840 841 842
    /**
     * {@inheritDoc}
     */
843 844 845 846 847
    public function supportsIdentityColumns()
    {
        return true;
    }

848 849 850
    /**
     * {@inheritDoc}
     */
851 852 853 854
    public function prefersIdentityColumns()
    {
        return true;
    }
855 856

    /**
857
     * {@inheritDoc}
858 859 860 861 862 863 864
     *
     * DB2 returns all column names in SQL result sets in uppercase.
     */
    public function getSQLResultCasing($column)
    {
        return strtoupper($column);
    }
865

Benjamin Morel's avatar
Benjamin Morel committed
866 867 868
    /**
     * {@inheritDoc}
     */
869 870 871 872
    public function getForUpdateSQL()
    {
        return ' WITH RR USE AND KEEP UPDATE LOCKS';
    }
873

874 875 876
    /**
     * {@inheritDoc}
     */
877 878
    public function getDummySelectSQL()
    {
879 880 881
        $expression = func_num_args() > 0 ? func_get_arg(0) : '1';

        return sprintf('SELECT %s FROM sysibm.sysdummy1', $expression);
882
    }
883 884

    /**
885 886
     * {@inheritDoc}
     *
887 888 889 890 891 892 893 894
     * 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;
    }
895

896 897 898
    /**
     * {@inheritDoc}
     */
899 900
    protected function getReservedKeywordsClass()
    {
901
        return Keywords\DB2Keywords::class;
902
    }
903 904 905 906 907 908 909 910 911 912 913 914 915

    public function getListTableCommentsSQL(string $table) : string
    {
        return sprintf(
            <<<'SQL'
SELECT REMARKS
  FROM SYSIBM.SYSTABLES
  WHERE NAME = UPPER( %s )
SQL
            ,
            $this->quoteStringLiteral($table)
        );
    }
916
}