OraclePlatform.php 32.4 KB
Newer Older
1 2
<?php

3
namespace Doctrine\DBAL\Platforms;
4

5
use Doctrine\DBAL\DBALException;
6
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
7
use Doctrine\DBAL\Schema\Identifier;
8 9 10
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\Sequence;
use Doctrine\DBAL\Schema\Table;
11
use Doctrine\DBAL\Schema\TableDiff;
12
use Doctrine\DBAL\TransactionIsolationLevel;
Steve Müller's avatar
Steve Müller committed
13
use Doctrine\DBAL\Types\BinaryType;
14
use InvalidArgumentException;
15 16 17
use function array_merge;
use function count;
use function explode;
18 19
use function func_get_arg;
use function func_num_args;
20 21 22 23 24 25 26
use function implode;
use function preg_match;
use function sprintf;
use function strlen;
use function strpos;
use function strtoupper;
use function substr;
27

romanb's avatar
romanb committed
28
/**
29
 * OraclePlatform.
romanb's avatar
romanb committed
30
 */
31
class OraclePlatform extends AbstractPlatform
32
{
33
    /**
Benjamin Morel's avatar
Benjamin Morel committed
34
     * Assertion for Oracle identifiers.
35 36
     *
     * @link http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements008.htm
37
     *
Benjamin Morel's avatar
Benjamin Morel committed
38
     * @param string $identifier
39
     *
40 41
     * @throws DBALException
     */
42
    public static function assertValidIdentifier($identifier)
43
    {
44 45
        if (! preg_match('(^(([a-zA-Z]{1}[a-zA-Z0-9_$#]{0,})|("[^"]+"))$)', $identifier)) {
            throw new DBALException('Invalid Oracle identifier');
46 47 48
        }
    }

49
    /**
50
     * {@inheritDoc}
51 52 53
     */
    public function getSubstringExpression($value, $position, $length = null)
    {
54
        if ($length !== null) {
55
            return sprintf('SUBSTR(%s, %d, %d)', $value, $position, $length);
56
        }
57

58
        return sprintf('SUBSTR(%s, %d)', $value, $position);
59 60 61
    }

    /**
62
     * {@inheritDoc}
63 64 65 66 67 68 69 70 71 72 73 74
     */
    public function getNowExpression($type = 'timestamp')
    {
        switch ($type) {
            case 'date':
            case 'time':
            case 'timestamp':
            default:
                return 'TO_CHAR(CURRENT_TIMESTAMP, \'YYYY-MM-DD HH24:MI:SS\')';
        }
    }

75
    /**
76
     * {@inheritDoc}
77 78 79
     */
    public function getLocateExpression($str, $substr, $startPos = false)
    {
80 81
        if ($startPos === false) {
            return 'INSTR(' . $str . ', ' . $substr . ')';
82
        }
83

84
        return 'INSTR(' . $str . ', ' . $substr . ', ' . $startPos . ')';
85 86
    }

87
    /**
88
     * {@inheritDoc}
89 90
     *
     * @deprecated Use application-generated UUIDs instead
91 92 93 94 95
     */
    public function getGuidExpression()
    {
        return 'SYS_GUID()';
    }
96

97
    /**
98
     * {@inheritdoc}
99
     */
100
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
101
    {
102
        switch ($unit) {
103 104 105
            case DateIntervalUnit::MONTH:
            case DateIntervalUnit::QUARTER:
            case DateIntervalUnit::YEAR:
106
                switch ($unit) {
107
                    case DateIntervalUnit::QUARTER:
108 109 110
                        $interval *= 3;
                        break;

111
                    case DateIntervalUnit::YEAR:
112 113 114 115 116
                        $interval *= 12;
                        break;
                }

                return 'ADD_MONTHS(' . $date . ', ' . $operator . $interval . ')';
117

118 119
            default:
                $calculationClause = '';
120

121
                switch ($unit) {
122
                    case DateIntervalUnit::SECOND:
123 124
                        $calculationClause = '/24/60/60';
                        break;
125

126
                    case DateIntervalUnit::MINUTE:
127 128
                        $calculationClause = '/24/60';
                        break;
129

130
                    case DateIntervalUnit::HOUR:
131 132
                        $calculationClause = '/24';
                        break;
133

134
                    case DateIntervalUnit::WEEK:
135 136 137 138 139 140
                        $calculationClause = '*7';
                        break;
                }

                return '(' . $date . $operator . $interval . $calculationClause . ')';
        }
141 142
    }

143
    /**
144
     * {@inheritDoc}
145
     */
146
    public function getDateDiffExpression($date1, $date2)
147
    {
148
        return sprintf('TRUNC(%s) - TRUNC(%s)', $date1, $date2);
149
    }
Fabio B. Silva's avatar
Fabio B. Silva committed
150

151
    /**
152
     * {@inheritDoc}
153 154 155
     */
    public function getBitAndComparisonExpression($value1, $value2)
    {
156
        return 'BITAND(' . $value1 . ', ' . $value2 . ')';
157 158 159
    }

    /**
160
     * {@inheritDoc}
161 162 163
     */
    public function getBitOrComparisonExpression($value1, $value2)
    {
164 165
        return '(' . $value1 . '-' .
                $this->getBitAndComparisonExpression($value1, $value2)
166 167
                . '+' . $value2 . ')';
    }
168

169
    /**
170
     * {@inheritDoc}
171
     *
172 173 174
     * Need to specifiy minvalue, since start with is hidden in the system and MINVALUE <= START WITH.
     * Therefore we can use MINVALUE to be able to get a hint what START WITH was for later introspection
     * in {@see listSequences()}
175
     */
176
    public function getCreateSequenceSQL(Sequence $sequence)
177
    {
178
        return 'CREATE SEQUENCE ' . $sequence->getQuotedName($this) .
179
               ' START WITH ' . $sequence->getInitialValue() .
180
               ' MINVALUE ' . $sequence->getInitialValue() .
181 182
               ' INCREMENT BY ' . $sequence->getAllocationSize() .
               $this->getSequenceCacheSQL($sequence);
183
    }
184

185 186 187
    /**
     * {@inheritDoc}
     */
jeroendedauw's avatar
jeroendedauw committed
188
    public function getAlterSequenceSQL(Sequence $sequence)
189
    {
190
        return 'ALTER SEQUENCE ' . $sequence->getQuotedName($this) .
191 192 193 194 195 196 197 198 199
               ' INCREMENT BY ' . $sequence->getAllocationSize()
               . $this->getSequenceCacheSQL($sequence);
    }

    /**
     * Cache definition for sequences
     *
     * @return string
     */
jeroendedauw's avatar
jeroendedauw committed
200
    private function getSequenceCacheSQL(Sequence $sequence)
201 202 203
    {
        if ($sequence->getCache() === 0) {
            return ' NOCACHE';
204
        } elseif ($sequence->getCache() === 1) {
205
            return ' NOCACHE';
206
        } elseif ($sequence->getCache() > 1) {
207 208 209 210
            return ' CACHE ' . $sequence->getCache();
        }

        return '';
211
    }
212

romanb's avatar
romanb committed
213
    /**
214
     * {@inheritDoc}
romanb's avatar
romanb committed
215
     */
216
    public function getSequenceNextValSQL($sequenceName)
romanb's avatar
romanb committed
217
    {
218
        return 'SELECT ' . $sequenceName . '.nextval FROM DUAL';
romanb's avatar
romanb committed
219
    }
220

romanb's avatar
romanb committed
221
    /**
222
     * {@inheritDoc}
romanb's avatar
romanb committed
223
     */
224
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
225
    {
226
        return 'SET TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
227
    }
228

229 230 231
    /**
     * {@inheritDoc}
     */
232
    protected function _getTransactionIsolationLevelSQL($level)
romanb's avatar
romanb committed
233 234
    {
        switch ($level) {
235
            case TransactionIsolationLevel::READ_UNCOMMITTED:
236
                return 'READ UNCOMMITTED';
237
            case TransactionIsolationLevel::READ_COMMITTED:
238
                return 'READ COMMITTED';
239 240
            case TransactionIsolationLevel::REPEATABLE_READ:
            case TransactionIsolationLevel::SERIALIZABLE:
romanb's avatar
romanb committed
241 242
                return 'SERIALIZABLE';
            default:
243
                return parent::_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
244 245
        }
    }
246

247
    /**
248
     * {@inheritDoc}
249
     */
250
    public function getBooleanTypeDeclarationSQL(array $field)
251 252 253
    {
        return 'NUMBER(1)';
    }
254

255
    /**
256
     * {@inheritDoc}
257
     */
258
    public function getIntegerTypeDeclarationSQL(array $field)
259 260 261 262 263
    {
        return 'NUMBER(10)';
    }

    /**
264
     * {@inheritDoc}
265
     */
266
    public function getBigIntTypeDeclarationSQL(array $field)
267 268 269 270 271
    {
        return 'NUMBER(20)';
    }

    /**
272
     * {@inheritDoc}
273
     */
274
    public function getSmallIntTypeDeclarationSQL(array $field)
275 276 277 278
    {
        return 'NUMBER(5)';
    }

279
    /**
280
     * {@inheritDoc}
281
     */
282
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
283 284 285 286 287
    {
        return 'TIMESTAMP(0)';
    }

    /**
288
     * {@inheritDoc}
289 290
     */
    public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration)
291
    {
292
        return 'TIMESTAMP(0) WITH TIME ZONE';
293 294
    }

295
    /**
296
     * {@inheritDoc}
297
     */
298
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
299 300 301 302 303
    {
        return 'DATE';
    }

    /**
304
     * {@inheritDoc}
305
     */
306
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
307 308 309 310
    {
        return 'DATE';
    }

311
    /**
312
     * {@inheritDoc}
313
     */
314
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
315 316 317 318 319
    {
        return '';
    }

    /**
320
     * {@inheritDoc}
321
     */
322 323
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
    {
324 325 326
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(2000)')
                : ($length ? 'VARCHAR2(' . $length . ')' : 'VARCHAR2(4000)');
    }
327

Steve Müller's avatar
Steve Müller committed
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
        return 'RAW(' . ($length ?: $this->getBinaryMaxLength()) . ')';
    }

    /**
     * {@inheritdoc}
     */
    public function getBinaryMaxLength()
    {
        return 2000;
    }

344 345 346
    /**
     * {@inheritDoc}
     */
347
    public function getClobTypeDeclarationSQL(array $field)
348 349 350
    {
        return 'CLOB';
    }
351

Benjamin Morel's avatar
Benjamin Morel committed
352 353 354
    /**
     * {@inheritDoc}
     */
355
    public function getListDatabasesSQL()
356
    {
357
        return 'SELECT username FROM all_users';
358 359
    }

Benjamin Morel's avatar
Benjamin Morel committed
360 361 362
    /**
     * {@inheritDoc}
     */
363
    public function getListSequencesSQL($database)
jwage's avatar
jwage committed
364
    {
365
        $database = $this->normalizeIdentifier($database);
366
        $database = $this->quoteStringLiteral($database->getName());
367

368 369
        return 'SELECT sequence_name, min_value, increment_by FROM sys.all_sequences ' .
               'WHERE SEQUENCE_OWNER = ' . $database;
jwage's avatar
jwage committed
370 371
    }

372
    /**
373
     * {@inheritDoc}
374
     */
375
    protected function _getCreateTableSQL($table, array $columns, array $options = [])
376
    {
Gabriel Caruso's avatar
Gabriel Caruso committed
377
        $indexes            = $options['indexes'] ?? [];
378
        $options['indexes'] = [];
Gabriel Caruso's avatar
Gabriel Caruso committed
379
        $sql                = parent::_getCreateTableSQL($table, $columns, $options);
380 381 382

        foreach ($columns as $name => $column) {
            if (isset($column['sequence'])) {
383
                $sql[] = $this->getCreateSequenceSQL($column['sequence']);
384 385
            }

386 387 388
            if (! isset($column['autoincrement']) || ! $column['autoincrement'] &&
               (! isset($column['autoinc']) || ! $column['autoinc'])) {
                continue;
389
            }
390 391

            $sql = array_merge($sql, $this->getCreateAutoincrementSql($name, $table));
392
        }
393

394
        if (isset($indexes) && ! empty($indexes)) {
395
            foreach ($indexes as $index) {
396
                $sql[] = $this->getCreateIndexSQL($index, $table);
397 398 399 400 401 402
            }
        }

        return $sql;
    }

403
    /**
404 405
     * {@inheritDoc}
     *
406 407
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaOracleReader.html
     */
408
    public function getListTableIndexesSQL($table, $currentDatabase = null)
409
    {
410
        $table = $this->normalizeIdentifier($table);
411
        $table = $this->quoteStringLiteral($table->getName());
412

413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
        return "SELECT uind_col.index_name AS name,
                       (
                           SELECT uind.index_type
                           FROM   user_indexes uind
                           WHERE  uind.index_name = uind_col.index_name
                       ) AS type,
                       decode(
                           (
                               SELECT uind.uniqueness
                               FROM   user_indexes uind
                               WHERE  uind.index_name = uind_col.index_name
                           ),
                           'NONUNIQUE',
                           0,
                           'UNIQUE',
                           1
                       ) AS is_unique,
                       uind_col.column_name AS column_name,
                       uind_col.column_position AS column_pos,
                       (
                           SELECT ucon.constraint_type
                           FROM   user_constraints ucon
435
                           WHERE  ucon.index_name = uind_col.index_name
436 437
                       ) AS is_primary
             FROM      user_ind_columns uind_col
438 439
             WHERE     uind_col.table_name = " . $table . '
             ORDER BY  uind_col.column_position ASC';
440 441
    }

Benjamin Morel's avatar
Benjamin Morel committed
442 443 444
    /**
     * {@inheritDoc}
     */
445
    public function getListTablesSQL()
446 447 448 449
    {
        return 'SELECT * FROM sys.user_tables';
    }

450 451 452
    /**
     * {@inheritDoc}
     */
453
    public function getListViewsSQL($database)
454
    {
455
        return 'SELECT view_name, text FROM sys.user_views';
456 457
    }

Benjamin Morel's avatar
Benjamin Morel committed
458 459 460
    /**
     * {@inheritDoc}
     */
461
    public function getCreateViewSQL($name, $sql)
462 463 464 465
    {
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
    }

Benjamin Morel's avatar
Benjamin Morel committed
466 467 468
    /**
     * {@inheritDoc}
     */
469
    public function getDropViewSQL($name)
470
    {
471
        return 'DROP VIEW ' . $name;
472 473
    }

Benjamin Morel's avatar
Benjamin Morel committed
474
    /**
475 476 477
     * @param string $name
     * @param string $table
     * @param int    $start
Benjamin Morel's avatar
Benjamin Morel committed
478
     *
479
     * @return string[]
Benjamin Morel's avatar
Benjamin Morel committed
480
     */
481 482
    public function getCreateAutoincrementSql($name, $table, $start = 1)
    {
483 484
        $tableIdentifier   = $this->normalizeIdentifier($table);
        $quotedTableName   = $tableIdentifier->getQuotedName($this);
485 486 487
        $unquotedTableName = $tableIdentifier->getName();

        $nameIdentifier = $this->normalizeIdentifier($name);
488 489
        $quotedName     = $nameIdentifier->getQuotedName($this);
        $unquotedName   = $nameIdentifier->getName();
490

491
        $sql = [];
492

493
        $autoincrementIdentifierName = $this->getAutoincrementIdentifierName($tableIdentifier);
494

495
        $idx = new Index($autoincrementIdentifierName, [$quotedName], true, true);
496

497 498 499
        $sql[] = 'DECLARE
  constraints_Count NUMBER;
BEGIN
500
  SELECT COUNT(CONSTRAINT_NAME) INTO constraints_Count FROM USER_CONSTRAINTS WHERE TABLE_NAME = \'' . $unquotedTableName . '\' AND CONSTRAINT_TYPE = \'P\';
501
  IF constraints_Count = 0 OR constraints_Count = \'\' THEN
502
    EXECUTE IMMEDIATE \'' . $this->getCreateConstraintSQL($idx, $quotedTableName) . '\';
503
  END IF;
504
END;';
505

506 507 508 509
        $sequenceName = $this->getIdentitySequenceName(
            $tableIdentifier->isQuoted() ? $quotedTableName : $unquotedTableName,
            $nameIdentifier->isQuoted() ? $quotedName : $unquotedName
        );
510 511
        $sequence     = new Sequence($sequenceName, $start);
        $sql[]        = $this->getCreateSequenceSQL($sequence);
512

513
        $sql[] = 'CREATE TRIGGER ' . $autoincrementIdentifierName . '
514
   BEFORE INSERT
515
   ON ' . $quotedTableName . '
516 517 518 519 520
   FOR EACH ROW
DECLARE
   last_Sequence NUMBER;
   last_InsertID NUMBER;
BEGIN
521
   SELECT ' . $sequenceName . '.NEXTVAL INTO :NEW.' . $quotedName . ' FROM DUAL;
522
   IF (:NEW.' . $quotedName . ' IS NULL OR :NEW.' . $quotedName . ' = 0) THEN
523
      SELECT ' . $sequenceName . '.NEXTVAL INTO :NEW.' . $quotedName . ' FROM DUAL;
524 525 526
   ELSE
      SELECT NVL(Last_Number, 0) INTO last_Sequence
        FROM User_Sequences
527
       WHERE Sequence_Name = \'' . $sequence->getName() . '\';
528
      SELECT :NEW.' . $quotedName . ' INTO last_InsertID FROM DUAL;
529
      WHILE (last_InsertID > last_Sequence) LOOP
530
         SELECT ' . $sequenceName . '.NEXTVAL INTO last_Sequence FROM DUAL;
531 532 533
      END LOOP;
   END IF;
END;';
534

535 536 537
        return $sql;
    }

Benjamin Morel's avatar
Benjamin Morel committed
538
    /**
539 540 541
     * Returns the SQL statements to drop the autoincrement for the given table name.
     *
     * @param string $table The table name to drop the autoincrement for.
Benjamin Morel's avatar
Benjamin Morel committed
542
     *
543
     * @return string[]
Benjamin Morel's avatar
Benjamin Morel committed
544
     */
545 546
    public function getDropAutoincrementSql($table)
    {
547
        $table                       = $this->normalizeIdentifier($table);
548
        $autoincrementIdentifierName = $this->getAutoincrementIdentifierName($table);
549
        $identitySequenceName        = $this->getIdentitySequenceName(
550 551 552
            $table->isQuoted() ? $table->getQuotedName($this) : $table->getName(),
            ''
        );
553

554
        return [
555
            'DROP TRIGGER ' . $autoincrementIdentifierName,
556 557
            $this->getDropSequenceSQL($identitySequenceName),
            $this->getDropConstraintSQL($autoincrementIdentifierName, $table->getQuotedName($this)),
558
        ];
559
    }
560

561 562 563 564 565 566 567 568 569 570 571 572 573
    /**
     * Normalizes the given identifier.
     *
     * Uppercases the given identifier if it is not quoted by intention
     * to reflect Oracle's internal auto uppercasing strategy of unquoted identifiers.
     *
     * @param string $name The identifier to normalize.
     *
     * @return Identifier The normalized identifier.
     */
    private function normalizeIdentifier($name)
    {
        $identifier = new Identifier($name);
574

575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
        return $identifier->isQuoted() ? $identifier : new Identifier(strtoupper($name));
    }

    /**
     * Returns the autoincrement primary key identifier name for the given table identifier.
     *
     * Quotes the autoincrement primary key identifier name
     * if the given table name is quoted by intention.
     *
     * @param Identifier $table The table identifier to return the autoincrement primary key identifier name for.
     *
     * @return string
     */
    private function getAutoincrementIdentifierName(Identifier $table)
    {
        $identifierName = $table->getName() . '_AI_PK';

        return $table->isQuoted()
            ? $this->quoteSingleIdentifier($identifierName)
            : $identifierName;
595 596
    }

Benjamin Morel's avatar
Benjamin Morel committed
597 598 599
    /**
     * {@inheritDoc}
     */
600
    public function getListTableForeignKeysSQL($table)
601
    {
602 603
        $table = $this->normalizeIdentifier($table);
        $table = $this->quoteStringLiteral($table->getName());
604

605 606 607 608
        return "SELECT alc.constraint_name,
          alc.DELETE_RULE,
          cols.column_name \"local_column\",
          cols.position,
609 610 611 612 613 614 615 616 617 618 619 620
          (
              SELECT r_cols.table_name
              FROM   user_cons_columns r_cols
              WHERE  alc.r_constraint_name = r_cols.constraint_name
              AND    r_cols.position = cols.position
          ) AS \"references_table\",
          (
              SELECT r_cols.column_name
              FROM   user_cons_columns r_cols
              WHERE  alc.r_constraint_name = r_cols.constraint_name
              AND    r_cols.position = cols.position
          ) AS \"foreign_column\"
621
     FROM user_cons_columns cols
622
     JOIN user_constraints alc
623 624
       ON alc.constraint_name = cols.constraint_name
      AND alc.constraint_type = 'R'
625 626
      AND alc.table_name = " . $table . '
    ORDER BY cols.constraint_name ASC, cols.position ASC';
627 628
    }

Benjamin Morel's avatar
Benjamin Morel committed
629 630 631
    /**
     * {@inheritDoc}
     */
632
    public function getListTableConstraintsSQL($table)
633
    {
634
        $table = $this->normalizeIdentifier($table);
635
        $table = $this->quoteStringLiteral($table->getName());
636

637
        return 'SELECT * FROM user_constraints WHERE table_name = ' . $table;
638 639
    }

Benjamin Morel's avatar
Benjamin Morel committed
640 641 642
    /**
     * {@inheritDoc}
     */
643
    public function getListTableColumnsSQL($table, $database = null)
644
    {
645
        $table = $this->normalizeIdentifier($table);
646
        $table = $this->quoteStringLiteral($table->getName());
647

648 649 650
        $tabColumnsTableName       = 'user_tab_columns';
        $colCommentsTableName      = 'user_col_comments';
        $tabColumnsOwnerCondition  = '';
651
        $colCommentsOwnerCondition = '';
652

653 654 655 656 657
        if ($database !== null && $database !== '/') {
            $database                  = $this->normalizeIdentifier($database);
            $database                  = $this->quoteStringLiteral($database->getName());
            $tabColumnsTableName       = 'all_tab_columns';
            $colCommentsTableName      = 'all_col_comments';
658 659
            $tabColumnsOwnerCondition  = ' AND c.owner = ' . $database;
            $colCommentsOwnerCondition = ' AND d.OWNER = c.OWNER';
660
        }
661

662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
        return sprintf(
            <<<'SQL'
SELECT   c.*,
         (
             SELECT d.comments
             FROM   %s d
             WHERE  d.TABLE_NAME = c.TABLE_NAME%s
             AND    d.COLUMN_NAME = c.COLUMN_NAME
         ) AS comments
FROM     %s c
WHERE    c.table_name = %s%s
ORDER BY c.column_id
SQL
            ,
            $colCommentsTableName,
            $colCommentsOwnerCondition,
            $tabColumnsTableName,
            $table,
            $tabColumnsOwnerCondition
        );
682 683
    }

684
    /**
685
     * {@inheritDoc}
686
     */
687
    public function getDropSequenceSQL($sequence)
688
    {
689
        if ($sequence instanceof Sequence) {
690
            $sequence = $sequence->getQuotedName($this);
691 692 693
        }

        return 'DROP SEQUENCE ' . $sequence;
694 695
    }

696
    /**
697
     * {@inheritDoc}
698
     */
699
    public function getDropForeignKeySQL($foreignKey, $table)
700
    {
701 702
        if (! $foreignKey instanceof ForeignKeyConstraint) {
            $foreignKey = new Identifier($foreignKey);
703 704
        }

705 706
        if (! $table instanceof Table) {
            $table = new Identifier($table);
707 708
        }

709
        $foreignKey = $foreignKey->getQuotedName($this);
710
        $table      = $table->getQuotedName($this);
711

712 713 714
        return 'ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $foreignKey;
    }

715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
    /**
     * {@inheritdoc}
     */
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
    {
        $referentialAction = null;

        if ($foreignKey->hasOption('onDelete')) {
            $referentialAction = $this->getForeignKeyReferentialActionSQL($foreignKey->getOption('onDelete'));
        }

        return $referentialAction ? ' ON DELETE ' . $referentialAction : '';
    }

    /**
     * {@inheritdoc}
     */
    public function getForeignKeyReferentialActionSQL($action)
    {
        $action = strtoupper($action);

        switch ($action) {
            case 'RESTRICT': // RESTRICT is not supported, therefore falling back to NO ACTION.
            case 'NO ACTION':
                // NO ACTION cannot be declared explicitly,
                // therefore returning empty string to indicate to OMIT the referential clause.
                return '';

            case 'CASCADE':
            case 'SET NULL':
                return $action;

            default:
                // SET DEFAULT is not supported, throw exception instead.
749
                throw new InvalidArgumentException('Invalid foreign key action: ' . $action);
750 751 752
        }
    }

753 754 755
    /**
     * {@inheritDoc}
     */
756
    public function getDropDatabaseSQL($database)
757 758 759 760
    {
        return 'DROP USER ' . $database . ' CASCADE';
    }

761
    /**
762
     * {@inheritDoc}
763
     */
764
    public function getAlterTableSQL(TableDiff $diff)
765
    {
766
        $sql         = [];
767
        $commentsSQL = [];
768
        $columnSql   = [];
769

770
        $fields = [];
771

772
        foreach ($diff->addedColumns as $column) {
773 774
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
775 776
            }

777
            $fields[] = $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
778 779 780
            $comment  = $this->getColumnComment($column);

            if (! $comment) {
781
                continue;
782
            }
783 784 785 786 787 788

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

791
        if (count($fields)) {
792
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ADD (' . implode(', ', $fields) . ')';
793 794
        }

795
        $fields = [];
796
        foreach ($diff->changedColumns as $columnDiff) {
797 798
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
799 800
            }

801
            $column = $columnDiff->column;
Steve Müller's avatar
Steve Müller committed
802 803 804 805 806 807 808 809 810 811 812

            // Do not generate column alteration clause if type is binary and only fixed property has changed.
            // Oracle only supports binary type columns with variable length.
            // Avoids unnecessary table alteration statements.
            if ($column->getType() instanceof BinaryType &&
                $columnDiff->hasChanged('fixed') &&
                count($columnDiff->changedProperties) === 1
            ) {
                continue;
            }

813 814 815 816 817
            $columnHasChangedComment = $columnDiff->hasChanged('comment');

            /**
             * Do not add query part if only comment has changed
             */
818
            if (! ($columnHasChangedComment && count($columnDiff->changedProperties) === 1)) {
819 820
                $columnInfo = $column->toArray();

821
                if (! $columnDiff->hasChanged('notnull')) {
822
                    unset($columnInfo['notnull']);
823 824
                }

825
                $fields[] = $column->getQuotedName($this) . $this->getColumnDeclarationSQL('', $columnInfo);
826 827
            }

828 829
            if (! $columnHasChangedComment) {
                continue;
830
            }
831 832 833 834 835 836

            $commentsSQL[] = $this->getCommentOnColumnSQL(
                $diff->getName($this)->getQuotedName($this),
                $column->getQuotedName($this),
                $this->getColumnComment($column)
            );
837
        }
838

839
        if (count($fields)) {
840
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' MODIFY (' . implode(', ', $fields) . ')';
841 842
        }

843
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
844 845
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
846 847
            }

848 849
            $oldColumnName = new Identifier($oldColumnName);

850
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) .
851
                ' RENAME COLUMN ' . $oldColumnName->getQuotedName($this) . ' TO ' . $column->getQuotedName($this);
852 853
        }

854
        $fields = [];
855
        foreach ($diff->removedColumns as $column) {
856 857
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
858 859
            }

860
            $fields[] = $column->getQuotedName($this);
861
        }
862

863
        if (count($fields)) {
864
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' DROP (' . implode(', ', $fields) . ')';
865 866
        }

867
        $tableSql = [];
868

869
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
870 871
            $sql = array_merge($sql, $commentsSQL);

872
            if ($diff->newName !== false) {
873
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' RENAME TO ' . $diff->getNewName()->getQuotedName($this);
874 875
            }

876 877 878 879 880
            $sql = array_merge(
                $this->getPreAlterTableIndexForeignKeySQL($diff),
                $sql,
                $this->getPostAlterTableIndexForeignKeySQL($diff)
            );
881 882
        }

883
        return array_merge($sql, $tableSql, $columnSql);
884 885
    }

886 887 888 889 890 891 892 893 894 895
    /**
     * {@inheritdoc}
     */
    public function getColumnDeclarationSQL($name, array $field)
    {
        if (isset($field['columnDefinition'])) {
            $columnDef = $this->getCustomTypeDeclarationSQL($field);
        } else {
            $default = $this->getDefaultValueDeclarationSQL($field);

896 897 898 899 900
            $notnull = '';

            if (isset($field['notnull'])) {
                $notnull = $field['notnull'] ? ' NOT NULL' : ' NULL';
            }
901

902
            $unique = isset($field['unique']) && $field['unique'] ?
903 904
                ' ' . $this->getUniqueFieldDeclarationSQL() : '';

905
            $check = isset($field['check']) && $field['check'] ?
906 907
                ' ' . $field['check'] : '';

908
            $typeDecl  = $field['type']->getSQLDeclaration($field, $this);
909 910 911 912 913 914
            $columnDef = $typeDecl . $default . $notnull . $unique . $check;
        }

        return $name . ' ' . $columnDef;
    }

915 916 917 918 919
    /**
     * {@inheritdoc}
     */
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
    {
920
        if (strpos($tableName, '.') !== false) {
921
            [$schema]     = explode('.', $tableName);
922 923 924
            $oldIndexName = $schema . '.' . $oldIndexName;
        }

925
        return ['ALTER INDEX ' . $oldIndexName . ' RENAME TO ' . $index->getQuotedName($this)];
926 927
    }

928
    /**
929
     * {@inheritDoc}
930 931 932 933 934
     */
    public function prefersSequences()
    {
        return true;
    }
935

936 937 938 939 940 941 942 943 944 945 946 947 948
    /**
     * {@inheritdoc}
     */
    public function usesSequenceEmulatedIdentityColumns()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function getIdentitySequenceName($tableName, $columnName)
    {
949 950
        $table = new Identifier($tableName);

951 952 953 954
        // No usage of column name to preserve BC compatibility with <2.5
        $identitySequenceName = $table->getName() . '_SEQ';

        if ($table->isQuoted()) {
955 956 957 958 959 960
            $identitySequenceName = '"' . $identitySequenceName . '"';
        }

        $identitySequenceIdentifier = $this->normalizeIdentifier($identitySequenceName);

        return $identitySequenceIdentifier->getQuotedName($this);
961 962
    }

963 964 965
    /**
     * {@inheritDoc}
     */
966 967 968 969 970
    public function supportsCommentOnStatement()
    {
        return true;
    }

971
    /**
972
     * {@inheritDoc}
973 974 975 976 977
     */
    public function getName()
    {
        return 'oracle';
    }
978 979

    /**
980
     * {@inheritDoc}
981
     */
982
    protected function doModifyLimitQuery($query, $limit, $offset = null)
983
    {
984
        if ($limit === null && $offset <= 0) {
985 986
            return $query;
        }
987

988
        if (preg_match('/^\s*SELECT/i', $query)) {
989 990
            if (! preg_match('/\sFROM\s/i', $query)) {
                $query .= ' FROM dual';
991
            }
992

993
            $columns = ['a.*'];
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006

            if ($offset > 0) {
                $columns[] = 'ROWNUM AS doctrine_rownum';
            }

            $query = sprintf('SELECT %s FROM (%s) a', implode(', ', $columns), $query);

            if ($limit !== null) {
                $query .= sprintf(' WHERE ROWNUM <= %d', $offset + $limit);
            }

            if ($offset > 0) {
                $query = sprintf('SELECT * FROM (%s) WHERE doctrine_rownum >= %d', $query, $offset + 1);
1007 1008
            }
        }
1009

1010 1011
        return $query;
    }
1012

1013
    /**
1014
     * {@inheritDoc}
1015
     *
1016 1017
     * Oracle returns all column names in SQL result sets in uppercase.
     */
1018
    public function getSQLResultCasing($column)
1019 1020 1021
    {
        return strtoupper($column);
    }
1022

Benjamin Morel's avatar
Benjamin Morel committed
1023 1024 1025
    /**
     * {@inheritDoc}
     */
1026
    public function getCreateTemporaryTableSnippetSQL()
1027
    {
1028
        return 'CREATE GLOBAL TEMPORARY TABLE';
1029
    }
1030

1031 1032 1033
    /**
     * {@inheritDoc}
     */
1034
    public function getDateTimeTzFormatString()
1035 1036 1037
    {
        return 'Y-m-d H:i:sP';
    }
1038

1039 1040 1041
    /**
     * {@inheritDoc}
     */
1042 1043 1044 1045 1046
    public function getDateFormatString()
    {
        return 'Y-m-d 00:00:00';
    }

1047 1048 1049
    /**
     * {@inheritDoc}
     */
1050 1051 1052 1053
    public function getTimeFormatString()
    {
        return '1900-01-01 H:i:s';
    }
1054

1055 1056 1057
    /**
     * {@inheritDoc}
     */
1058 1059 1060 1061 1062 1063
    public function fixSchemaElementName($schemaElementName)
    {
        if (strlen($schemaElementName) > 30) {
            // Trim it
            return substr($schemaElementName, 0, 30);
        }
1064

1065 1066
        return $schemaElementName;
    }
1067

1068
    /**
1069
     * {@inheritDoc}
1070 1071 1072 1073 1074 1075
     */
    public function getMaxIdentifierLength()
    {
        return 30;
    }

1076
    /**
1077
     * {@inheritDoc}
1078 1079 1080 1081 1082
     */
    public function supportsSequences()
    {
        return true;
    }
1083

1084 1085 1086
    /**
     * {@inheritDoc}
     */
1087 1088 1089 1090
    public function supportsForeignKeyOnUpdate()
    {
        return false;
    }
1091

1092
    /**
1093
     * {@inheritDoc}
1094 1095 1096 1097 1098 1099
     */
    public function supportsReleaseSavepoints()
    {
        return false;
    }

1100
    /**
1101
     * {@inheritDoc}
1102
     */
1103
    public function getTruncateTableSQL($tableName, $cascade = false)
1104
    {
1105 1106 1107
        $tableIdentifier = new Identifier($tableName);

        return 'TRUNCATE TABLE ' . $tableIdentifier->getQuotedName($this);
1108
    }
1109 1110

    /**
1111
     * {@inheritDoc}
1112 1113 1114
     */
    public function getDummySelectSQL()
    {
1115 1116 1117
        $expression = func_num_args() > 0 ? func_get_arg(0) : '1';

        return sprintf('SELECT %s FROM DUAL', $expression);
1118
    }
1119

1120 1121 1122
    /**
     * {@inheritDoc}
     */
1123 1124
    protected function initializeDoctrineTypeMappings()
    {
1125
        $this->doctrineTypeMapping = [
1126 1127 1128 1129 1130 1131 1132 1133 1134
            'integer'           => 'integer',
            'number'            => 'integer',
            'pls_integer'       => 'boolean',
            'binary_integer'    => 'boolean',
            'varchar'           => 'string',
            'varchar2'          => 'string',
            'nvarchar2'         => 'string',
            'char'              => 'string',
            'nchar'             => 'string',
1135
            'date'              => 'date',
1136 1137
            'timestamp'         => 'datetime',
            'timestamptz'       => 'datetimetz',
1138
            'float'             => 'float',
1139 1140
            'binary_float'      => 'float',
            'binary_double'     => 'float',
1141 1142 1143
            'long'              => 'string',
            'clob'              => 'text',
            'nclob'             => 'text',
Steve Müller's avatar
Steve Müller committed
1144 1145
            'raw'               => 'binary',
            'long raw'          => 'blob',
1146
            'rowid'             => 'string',
1147
            'urowid'            => 'string',
1148
            'blob'              => 'blob',
1149
        ];
1150
    }
1151 1152

    /**
1153
     * {@inheritDoc}
1154 1155 1156 1157 1158
     */
    public function releaseSavePoint($savepoint)
    {
        return '';
    }
1159

1160 1161 1162
    /**
     * {@inheritDoc}
     */
1163 1164
    protected function getReservedKeywordsClass()
    {
1165
        return Keywords\OracleKeywords::class;
1166
    }
1167 1168

    /**
1169
     * {@inheritDoc}
1170 1171 1172 1173 1174
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'BLOB';
    }
1175
}