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

3
namespace Doctrine\DBAL\Platforms;
4

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

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

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

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

    /**
61
     * {@inheritDoc}
62 63 64 65 66 67 68 69 70 71 72 73
     */
    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\')';
        }
    }

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

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

86
    /**
87
     * {@inheritdoc}
88
     */
89
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
90
    {
91
        switch ($unit) {
92 93 94
            case DateIntervalUnit::MONTH:
            case DateIntervalUnit::QUARTER:
            case DateIntervalUnit::YEAR:
95
                switch ($unit) {
96
                    case DateIntervalUnit::QUARTER:
97 98 99
                        $interval *= 3;
                        break;

100
                    case DateIntervalUnit::YEAR:
101 102 103 104 105
                        $interval *= 12;
                        break;
                }

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

107 108
            default:
                $calculationClause = '';
109

110
                switch ($unit) {
111
                    case DateIntervalUnit::SECOND:
112 113
                        $calculationClause = '/24/60/60';
                        break;
114

115
                    case DateIntervalUnit::MINUTE:
116 117
                        $calculationClause = '/24/60';
                        break;
118

119
                    case DateIntervalUnit::HOUR:
120 121
                        $calculationClause = '/24';
                        break;
122

123
                    case DateIntervalUnit::WEEK:
124 125 126 127 128 129
                        $calculationClause = '*7';
                        break;
                }

                return '(' . $date . $operator . $interval . $calculationClause . ')';
        }
130 131
    }

132
    /**
133
     * {@inheritDoc}
134
     */
135
    public function getDateDiffExpression($date1, $date2)
136
    {
137
        return sprintf('TRUNC(%s) - TRUNC(%s)', $date1, $date2);
138
    }
Fabio B. Silva's avatar
Fabio B. Silva committed
139

140
    /**
141
     * {@inheritDoc}
142 143 144
     */
    public function getBitAndComparisonExpression($value1, $value2)
    {
145
        return 'BITAND(' . $value1 . ', ' . $value2 . ')';
146 147 148
    }

    /**
149
     * {@inheritDoc}
150 151 152
     */
    public function getBitOrComparisonExpression($value1, $value2)
    {
153 154
        return '(' . $value1 . '-' .
                $this->getBitAndComparisonExpression($value1, $value2)
155 156
                . '+' . $value2 . ')';
    }
157

158
    /**
159
     * {@inheritDoc}
160
     *
161 162 163
     * 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()}
164
     */
165
    public function getCreateSequenceSQL(Sequence $sequence)
166
    {
167
        return 'CREATE SEQUENCE ' . $sequence->getQuotedName($this) .
168
               ' START WITH ' . $sequence->getInitialValue() .
169
               ' MINVALUE ' . $sequence->getInitialValue() .
170 171
               ' INCREMENT BY ' . $sequence->getAllocationSize() .
               $this->getSequenceCacheSQL($sequence);
172
    }
173

174 175 176
    /**
     * {@inheritDoc}
     */
jeroendedauw's avatar
jeroendedauw committed
177
    public function getAlterSequenceSQL(Sequence $sequence)
178
    {
179
        return 'ALTER SEQUENCE ' . $sequence->getQuotedName($this) .
180 181 182 183 184 185 186 187 188
               ' INCREMENT BY ' . $sequence->getAllocationSize()
               . $this->getSequenceCacheSQL($sequence);
    }

    /**
     * Cache definition for sequences
     *
     * @return string
     */
jeroendedauw's avatar
jeroendedauw committed
189
    private function getSequenceCacheSQL(Sequence $sequence)
190 191 192
    {
        if ($sequence->getCache() === 0) {
            return ' NOCACHE';
193
        } elseif ($sequence->getCache() === 1) {
194
            return ' NOCACHE';
195
        } elseif ($sequence->getCache() > 1) {
196 197 198 199
            return ' CACHE ' . $sequence->getCache();
        }

        return '';
200
    }
201

romanb's avatar
romanb committed
202
    /**
203
     * {@inheritDoc}
romanb's avatar
romanb committed
204
     */
205
    public function getSequenceNextValSQL($sequenceName)
romanb's avatar
romanb committed
206
    {
207
        return 'SELECT ' . $sequenceName . '.nextval FROM DUAL';
romanb's avatar
romanb committed
208
    }
209

romanb's avatar
romanb committed
210
    /**
211
     * {@inheritDoc}
romanb's avatar
romanb committed
212
     */
213
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
214
    {
215
        return 'SET TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
216
    }
217

218 219 220
    /**
     * {@inheritDoc}
     */
221
    protected function _getTransactionIsolationLevelSQL($level)
romanb's avatar
romanb committed
222 223
    {
        switch ($level) {
224
            case TransactionIsolationLevel::READ_UNCOMMITTED:
225
                return 'READ UNCOMMITTED';
226
            case TransactionIsolationLevel::READ_COMMITTED:
227
                return 'READ COMMITTED';
228 229
            case TransactionIsolationLevel::REPEATABLE_READ:
            case TransactionIsolationLevel::SERIALIZABLE:
romanb's avatar
romanb committed
230 231
                return 'SERIALIZABLE';
            default:
232
                return parent::_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
233 234
        }
    }
235

236
    /**
237
     * {@inheritDoc}
238
     */
239
    public function getBooleanTypeDeclarationSQL(array $field)
240 241 242
    {
        return 'NUMBER(1)';
    }
243

244
    /**
245
     * {@inheritDoc}
246
     */
247
    public function getIntegerTypeDeclarationSQL(array $field)
248 249 250 251 252
    {
        return 'NUMBER(10)';
    }

    /**
253
     * {@inheritDoc}
254
     */
255
    public function getBigIntTypeDeclarationSQL(array $field)
256 257 258 259 260
    {
        return 'NUMBER(20)';
    }

    /**
261
     * {@inheritDoc}
262
     */
263
    public function getSmallIntTypeDeclarationSQL(array $field)
264 265 266 267
    {
        return 'NUMBER(5)';
    }

268
    /**
269
     * {@inheritDoc}
270
     */
271
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
272 273 274 275 276
    {
        return 'TIMESTAMP(0)';
    }

    /**
277
     * {@inheritDoc}
278 279
     */
    public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration)
280
    {
281
        return 'TIMESTAMP(0) WITH TIME ZONE';
282 283
    }

284
    /**
285
     * {@inheritDoc}
286
     */
287
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
288 289 290 291 292
    {
        return 'DATE';
    }

    /**
293
     * {@inheritDoc}
294
     */
295
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
296 297 298 299
    {
        return 'DATE';
    }

300
    /**
301
     * {@inheritDoc}
302
     */
303
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
304 305 306 307 308
    {
        return '';
    }

    /**
309
     * {@inheritDoc}
310
     */
311 312
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
    {
313 314 315
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(2000)')
                : ($length ? 'VARCHAR2(' . $length . ')' : 'VARCHAR2(4000)');
    }
316

Steve Müller's avatar
Steve Müller committed
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
        return 'RAW(' . ($length ?: $this->getBinaryMaxLength()) . ')';
    }

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

333 334 335
    /**
     * {@inheritDoc}
     */
336
    public function getClobTypeDeclarationSQL(array $field)
337 338 339
    {
        return 'CLOB';
    }
340

Benjamin Morel's avatar
Benjamin Morel committed
341 342 343
    /**
     * {@inheritDoc}
     */
344
    public function getListDatabasesSQL()
345
    {
346
        return 'SELECT username FROM all_users';
347 348
    }

Benjamin Morel's avatar
Benjamin Morel committed
349 350 351
    /**
     * {@inheritDoc}
     */
352
    public function getListSequencesSQL($database)
jwage's avatar
jwage committed
353
    {
354
        $database = $this->normalizeIdentifier($database);
355
        $database = $this->quoteStringLiteral($database->getName());
356

357 358
        return 'SELECT sequence_name, min_value, increment_by FROM sys.all_sequences ' .
               'WHERE SEQUENCE_OWNER = ' . $database;
jwage's avatar
jwage committed
359 360
    }

361
    /**
362
     * {@inheritDoc}
363
     */
364
    protected function _getCreateTableSQL($tableName, array $columns, array $options = [])
365
    {
Gabriel Caruso's avatar
Gabriel Caruso committed
366
        $indexes            = $options['indexes'] ?? [];
367
        $options['indexes'] = [];
368
        $sql                = parent::_getCreateTableSQL($tableName, $columns, $options);
369 370 371

        foreach ($columns as $name => $column) {
            if (isset($column['sequence'])) {
372
                $sql[] = $this->getCreateSequenceSQL($column['sequence']);
373 374
            }

375 376 377
            if (! isset($column['autoincrement']) || ! $column['autoincrement'] &&
               (! isset($column['autoinc']) || ! $column['autoinc'])) {
                continue;
378
            }
379

380
            $sql = array_merge($sql, $this->getCreateAutoincrementSql($name, $tableName));
381
        }
382

383
        if (isset($indexes) && ! empty($indexes)) {
384
            foreach ($indexes as $index) {
385
                $sql[] = $this->getCreateIndexSQL($index, $tableName);
386 387 388 389 390 391
            }
        }

        return $sql;
    }

392
    /**
393 394
     * {@inheritDoc}
     *
395 396
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaOracleReader.html
     */
397
    public function getListTableIndexesSQL($table, $currentDatabase = null)
398
    {
399
        $table = $this->normalizeIdentifier($table);
400
        $table = $this->quoteStringLiteral($table->getName());
401

402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
        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
424
                           WHERE  ucon.index_name = uind_col.index_name
425 426
                       ) AS is_primary
             FROM      user_ind_columns uind_col
427 428
             WHERE     uind_col.table_name = " . $table . '
             ORDER BY  uind_col.column_position ASC';
429 430
    }

Benjamin Morel's avatar
Benjamin Morel committed
431 432 433
    /**
     * {@inheritDoc}
     */
434
    public function getListTablesSQL()
435 436 437 438
    {
        return 'SELECT * FROM sys.user_tables';
    }

439 440 441
    /**
     * {@inheritDoc}
     */
442
    public function getListViewsSQL($database)
443
    {
444
        return 'SELECT view_name, text FROM sys.user_views';
445 446
    }

Benjamin Morel's avatar
Benjamin Morel committed
447 448 449
    /**
     * {@inheritDoc}
     */
450
    public function getCreateViewSQL($name, $sql)
451 452 453 454
    {
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
    }

Benjamin Morel's avatar
Benjamin Morel committed
455 456 457
    /**
     * {@inheritDoc}
     */
458
    public function getDropViewSQL($name)
459
    {
460
        return 'DROP VIEW ' . $name;
461 462
    }

Benjamin Morel's avatar
Benjamin Morel committed
463
    /**
464 465 466
     * @param string $name
     * @param string $table
     * @param int    $start
Benjamin Morel's avatar
Benjamin Morel committed
467
     *
468
     * @return string[]
Benjamin Morel's avatar
Benjamin Morel committed
469
     */
470 471
    public function getCreateAutoincrementSql($name, $table, $start = 1)
    {
472 473
        $tableIdentifier   = $this->normalizeIdentifier($table);
        $quotedTableName   = $tableIdentifier->getQuotedName($this);
474 475 476
        $unquotedTableName = $tableIdentifier->getName();

        $nameIdentifier = $this->normalizeIdentifier($name);
477 478
        $quotedName     = $nameIdentifier->getQuotedName($this);
        $unquotedName   = $nameIdentifier->getName();
479

480
        $sql = [];
481

482
        $autoincrementIdentifierName = $this->getAutoincrementIdentifierName($tableIdentifier);
483

484
        $idx = new Index($autoincrementIdentifierName, [$quotedName], true, true);
485

486 487 488
        $sql[] = 'DECLARE
  constraints_Count NUMBER;
BEGIN
489
  SELECT COUNT(CONSTRAINT_NAME) INTO constraints_Count FROM USER_CONSTRAINTS WHERE TABLE_NAME = \'' . $unquotedTableName . '\' AND CONSTRAINT_TYPE = \'P\';
490
  IF constraints_Count = 0 OR constraints_Count = \'\' THEN
491
    EXECUTE IMMEDIATE \'' . $this->getCreateConstraintSQL($idx, $quotedTableName) . '\';
492
  END IF;
493
END;';
494

495 496 497 498
        $sequenceName = $this->getIdentitySequenceName(
            $tableIdentifier->isQuoted() ? $quotedTableName : $unquotedTableName,
            $nameIdentifier->isQuoted() ? $quotedName : $unquotedName
        );
499 500
        $sequence     = new Sequence($sequenceName, $start);
        $sql[]        = $this->getCreateSequenceSQL($sequence);
501

502
        $sql[] = 'CREATE TRIGGER ' . $autoincrementIdentifierName . '
503
   BEFORE INSERT
504
   ON ' . $quotedTableName . '
505 506 507 508 509
   FOR EACH ROW
DECLARE
   last_Sequence NUMBER;
   last_InsertID NUMBER;
BEGIN
510
   SELECT ' . $sequenceName . '.NEXTVAL INTO :NEW.' . $quotedName . ' FROM DUAL;
511
   IF (:NEW.' . $quotedName . ' IS NULL OR :NEW.' . $quotedName . ' = 0) THEN
512
      SELECT ' . $sequenceName . '.NEXTVAL INTO :NEW.' . $quotedName . ' FROM DUAL;
513 514 515
   ELSE
      SELECT NVL(Last_Number, 0) INTO last_Sequence
        FROM User_Sequences
516
       WHERE Sequence_Name = \'' . $sequence->getName() . '\';
517
      SELECT :NEW.' . $quotedName . ' INTO last_InsertID FROM DUAL;
518
      WHILE (last_InsertID > last_Sequence) LOOP
519
         SELECT ' . $sequenceName . '.NEXTVAL INTO last_Sequence FROM DUAL;
520 521 522
      END LOOP;
   END IF;
END;';
523

524 525 526
        return $sql;
    }

Benjamin Morel's avatar
Benjamin Morel committed
527
    /**
528 529 530
     * 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
531
     *
532
     * @return string[]
Benjamin Morel's avatar
Benjamin Morel committed
533
     */
534 535
    public function getDropAutoincrementSql($table)
    {
536
        $table                       = $this->normalizeIdentifier($table);
537
        $autoincrementIdentifierName = $this->getAutoincrementIdentifierName($table);
538
        $identitySequenceName        = $this->getIdentitySequenceName(
539 540 541
            $table->isQuoted() ? $table->getQuotedName($this) : $table->getName(),
            ''
        );
542

543
        return [
544
            'DROP TRIGGER ' . $autoincrementIdentifierName,
545 546
            $this->getDropSequenceSQL($identitySequenceName),
            $this->getDropConstraintSQL($autoincrementIdentifierName, $table->getQuotedName($this)),
547
        ];
548
    }
549

550 551 552 553 554 555 556 557 558 559 560 561 562
    /**
     * 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);
563

564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
        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;
584 585
    }

Benjamin Morel's avatar
Benjamin Morel committed
586 587 588
    /**
     * {@inheritDoc}
     */
589
    public function getListTableForeignKeysSQL($table)
590
    {
591 592
        $table = $this->normalizeIdentifier($table);
        $table = $this->quoteStringLiteral($table->getName());
593

594 595 596 597
        return "SELECT alc.constraint_name,
          alc.DELETE_RULE,
          cols.column_name \"local_column\",
          cols.position,
598 599 600 601 602 603 604 605 606 607 608 609
          (
              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\"
610
     FROM user_cons_columns cols
611
     JOIN user_constraints alc
612 613
       ON alc.constraint_name = cols.constraint_name
      AND alc.constraint_type = 'R'
614 615
      AND alc.table_name = " . $table . '
    ORDER BY cols.constraint_name ASC, cols.position ASC';
616 617
    }

Benjamin Morel's avatar
Benjamin Morel committed
618 619 620
    /**
     * {@inheritDoc}
     */
621
    public function getListTableConstraintsSQL($table)
622
    {
623
        $table = $this->normalizeIdentifier($table);
624
        $table = $this->quoteStringLiteral($table->getName());
625

626
        return 'SELECT * FROM user_constraints WHERE table_name = ' . $table;
627 628
    }

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

637 638 639
        $tabColumnsTableName       = 'user_tab_columns';
        $colCommentsTableName      = 'user_col_comments';
        $tabColumnsOwnerCondition  = '';
640
        $colCommentsOwnerCondition = '';
641

642 643 644 645 646
        if ($database !== null && $database !== '/') {
            $database                  = $this->normalizeIdentifier($database);
            $database                  = $this->quoteStringLiteral($database->getName());
            $tabColumnsTableName       = 'all_tab_columns';
            $colCommentsTableName      = 'all_col_comments';
647 648
            $tabColumnsOwnerCondition  = ' AND c.owner = ' . $database;
            $colCommentsOwnerCondition = ' AND d.OWNER = c.OWNER';
649
        }
650

651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
        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
        );
671 672
    }

673
    /**
674
     * {@inheritDoc}
675
     */
676
    public function getDropSequenceSQL($sequence)
677
    {
678
        if ($sequence instanceof Sequence) {
679
            $sequence = $sequence->getQuotedName($this);
680 681 682
        }

        return 'DROP SEQUENCE ' . $sequence;
683 684
    }

685
    /**
686
     * {@inheritDoc}
687
     */
688
    public function getDropForeignKeySQL($foreignKey, $table)
689
    {
690 691
        if (! $foreignKey instanceof ForeignKeyConstraint) {
            $foreignKey = new Identifier($foreignKey);
692 693
        }

694 695
        if (! $table instanceof Table) {
            $table = new Identifier($table);
696 697
        }

698
        $foreignKey = $foreignKey->getQuotedName($this);
699
        $table      = $table->getQuotedName($this);
700

701 702 703
        return 'ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $foreignKey;
    }

704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
    /**
     * {@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.
738
                throw new InvalidArgumentException('Invalid foreign key action: ' . $action);
739 740 741
        }
    }

742 743 744
    /**
     * {@inheritDoc}
     */
745
    public function getDropDatabaseSQL($database)
746 747 748 749
    {
        return 'DROP USER ' . $database . ' CASCADE';
    }

750
    /**
751
     * {@inheritDoc}
752
     */
753
    public function getAlterTableSQL(TableDiff $diff)
754
    {
755
        $sql         = [];
756
        $commentsSQL = [];
757
        $columnSql   = [];
758

759
        $fields = [];
760

761
        foreach ($diff->addedColumns as $column) {
762 763
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
764 765
            }

766
            $fields[] = $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
767 768 769
            $comment  = $this->getColumnComment($column);

            if (! $comment) {
770
                continue;
771
            }
772 773 774 775 776 777

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

780
        if (count($fields)) {
781
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ADD (' . implode(', ', $fields) . ')';
782 783
        }

784
        $fields = [];
785
        foreach ($diff->changedColumns as $columnDiff) {
786 787
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
788 789
            }

790
            /** @var ColumnDiff $columnDiff */
791
            $column = $columnDiff->column;
Steve Müller's avatar
Steve Müller committed
792 793 794 795 796 797 798 799 800 801 802

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

803 804 805 806 807
            $columnHasChangedComment = $columnDiff->hasChanged('comment');

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

811
                if (! $columnDiff->hasChanged('notnull')) {
812
                    unset($columnInfo['notnull']);
813 814
                }

815
                $fields[] = $column->getQuotedName($this) . $this->getColumnDeclarationSQL('', $columnInfo);
816 817
            }

818 819
            if (! $columnHasChangedComment) {
                continue;
820
            }
821 822 823 824 825 826

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

829
        if (count($fields)) {
830
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' MODIFY (' . implode(', ', $fields) . ')';
831 832
        }

833
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
834 835
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
836 837
            }

838 839
            $oldColumnName = new Identifier($oldColumnName);

840
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) .
841
                ' RENAME COLUMN ' . $oldColumnName->getQuotedName($this) . ' TO ' . $column->getQuotedName($this);
842 843
        }

844
        $fields = [];
845
        foreach ($diff->removedColumns as $column) {
846 847
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
848 849
            }

850
            $fields[] = $column->getQuotedName($this);
851
        }
852

853
        if (count($fields)) {
854
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' DROP (' . implode(', ', $fields) . ')';
855 856
        }

857
        $tableSql = [];
858

859
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
860 861
            $sql = array_merge($sql, $commentsSQL);

862
            if ($diff->newName !== false) {
863
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' RENAME TO ' . $diff->getNewName()->getQuotedName($this);
864 865
            }

866 867 868 869 870
            $sql = array_merge(
                $this->getPreAlterTableIndexForeignKeySQL($diff),
                $sql,
                $this->getPostAlterTableIndexForeignKeySQL($diff)
            );
871 872
        }

873
        return array_merge($sql, $tableSql, $columnSql);
874 875
    }

876 877 878 879 880 881 882 883 884 885
    /**
     * {@inheritdoc}
     */
    public function getColumnDeclarationSQL($name, array $field)
    {
        if (isset($field['columnDefinition'])) {
            $columnDef = $this->getCustomTypeDeclarationSQL($field);
        } else {
            $default = $this->getDefaultValueDeclarationSQL($field);

886 887 888 889 890
            $notnull = '';

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

892
            $unique = isset($field['unique']) && $field['unique'] ?
893 894
                ' ' . $this->getUniqueFieldDeclarationSQL() : '';

895
            $check = isset($field['check']) && $field['check'] ?
896 897
                ' ' . $field['check'] : '';

898
            $typeDecl  = $field['type']->getSQLDeclaration($field, $this);
899 900 901 902 903 904
            $columnDef = $typeDecl . $default . $notnull . $unique . $check;
        }

        return $name . ' ' . $columnDef;
    }

905 906 907 908 909
    /**
     * {@inheritdoc}
     */
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
    {
910
        if (strpos($tableName, '.') !== false) {
911
            [$schema]     = explode('.', $tableName);
912 913 914
            $oldIndexName = $schema . '.' . $oldIndexName;
        }

915
        return ['ALTER INDEX ' . $oldIndexName . ' RENAME TO ' . $index->getQuotedName($this)];
916 917
    }

918
    /**
919
     * {@inheritDoc}
920 921 922 923 924
     */
    public function prefersSequences()
    {
        return true;
    }
925

926 927 928 929 930 931 932 933 934 935 936 937 938
    /**
     * {@inheritdoc}
     */
    public function usesSequenceEmulatedIdentityColumns()
    {
        return true;
    }

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

941 942 943 944
        // No usage of column name to preserve BC compatibility with <2.5
        $identitySequenceName = $table->getName() . '_SEQ';

        if ($table->isQuoted()) {
945 946 947 948 949 950
            $identitySequenceName = '"' . $identitySequenceName . '"';
        }

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

        return $identitySequenceIdentifier->getQuotedName($this);
951 952
    }

953 954 955
    /**
     * {@inheritDoc}
     */
956 957 958 959 960
    public function supportsCommentOnStatement()
    {
        return true;
    }

961
    /**
962
     * {@inheritDoc}
963 964 965 966 967
     */
    public function getName()
    {
        return 'oracle';
    }
968 969

    /**
970
     * {@inheritDoc}
971
     */
972
    protected function doModifyLimitQuery(string $query, ?int $limit, int $offset) : string
973
    {
974
        if ($limit === null && $offset <= 0) {
975 976
            return $query;
        }
977

978
        if (preg_match('/^\s*SELECT/i', $query)) {
979 980
            if (! preg_match('/\sFROM\s/i', $query)) {
                $query .= ' FROM dual';
981
            }
982

983
            $columns = ['a.*'];
984 985 986 987 988 989 990 991 992 993 994 995 996

            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);
997 998
            }
        }
999

1000 1001
        return $query;
    }
1002

1003
    /**
1004
     * {@inheritDoc}
1005
     *
1006 1007
     * Oracle returns all column names in SQL result sets in uppercase.
     */
1008
    public function getSQLResultCasing($column)
1009 1010 1011
    {
        return strtoupper($column);
    }
1012

Benjamin Morel's avatar
Benjamin Morel committed
1013 1014 1015
    /**
     * {@inheritDoc}
     */
1016
    public function getCreateTemporaryTableSnippetSQL()
1017
    {
1018
        return 'CREATE GLOBAL TEMPORARY TABLE';
1019
    }
1020

1021 1022 1023
    /**
     * {@inheritDoc}
     */
1024
    public function getDateTimeTzFormatString()
1025 1026 1027
    {
        return 'Y-m-d H:i:sP';
    }
1028

1029 1030 1031
    /**
     * {@inheritDoc}
     */
1032 1033 1034 1035 1036
    public function getDateFormatString()
    {
        return 'Y-m-d 00:00:00';
    }

1037 1038 1039
    /**
     * {@inheritDoc}
     */
1040 1041 1042 1043
    public function getTimeFormatString()
    {
        return '1900-01-01 H:i:s';
    }
1044

1045 1046 1047
    /**
     * {@inheritDoc}
     */
1048 1049 1050 1051 1052 1053
    public function fixSchemaElementName($schemaElementName)
    {
        if (strlen($schemaElementName) > 30) {
            // Trim it
            return substr($schemaElementName, 0, 30);
        }
1054

1055 1056
        return $schemaElementName;
    }
1057

1058
    /**
1059
     * {@inheritDoc}
1060 1061 1062 1063 1064 1065
     */
    public function getMaxIdentifierLength()
    {
        return 30;
    }

1066
    /**
1067
     * {@inheritDoc}
1068 1069 1070 1071 1072
     */
    public function supportsSequences()
    {
        return true;
    }
1073

1074 1075 1076
    /**
     * {@inheritDoc}
     */
1077 1078 1079 1080
    public function supportsForeignKeyOnUpdate()
    {
        return false;
    }
1081

1082
    /**
1083
     * {@inheritDoc}
1084 1085 1086 1087 1088 1089
     */
    public function supportsReleaseSavepoints()
    {
        return false;
    }

1090
    /**
1091
     * {@inheritDoc}
1092
     */
1093
    public function getTruncateTableSQL($tableName, $cascade = false)
1094
    {
1095 1096 1097
        $tableIdentifier = new Identifier($tableName);

        return 'TRUNCATE TABLE ' . $tableIdentifier->getQuotedName($this);
1098
    }
1099 1100

    /**
1101
     * {@inheritDoc}
1102
     */
1103
    public function getDummySelectSQL(string $expression = '1') : string
1104
    {
1105
        return sprintf('SELECT %s FROM DUAL', $expression);
1106
    }
1107

1108 1109 1110
    /**
     * {@inheritDoc}
     */
1111 1112
    protected function initializeDoctrineTypeMappings()
    {
1113
        $this->doctrineTypeMapping = [
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
            'binary_double'  => 'float',
            'binary_float'   => 'float',
            'binary_integer' => 'boolean',
            'blob'           => 'blob',
            'char'           => 'string',
            'clob'           => 'text',
            'date'           => 'date',
            'float'          => 'float',
            'integer'        => 'integer',
            'long'           => 'string',
            'long raw'       => 'blob',
            'nchar'          => 'string',
            'nclob'          => 'text',
            'number'         => 'integer',
            'nvarchar2'      => 'string',
            'pls_integer'    => 'boolean',
            'raw'            => 'binary',
            'rowid'          => 'string',
            'timestamp'      => 'datetime',
            'timestamptz'    => 'datetimetz',
            'urowid'         => 'string',
            'varchar'        => 'string',
            'varchar2'       => 'string',
1137
        ];
1138
    }
1139 1140

    /**
1141
     * {@inheritDoc}
1142 1143 1144 1145 1146
     */
    public function releaseSavePoint($savepoint)
    {
        return '';
    }
1147

1148 1149 1150
    /**
     * {@inheritDoc}
     */
1151 1152
    protected function getReservedKeywordsClass()
    {
1153
        return Keywords\OracleKeywords::class;
1154
    }
1155 1156

    /**
1157
     * {@inheritDoc}
1158 1159 1160 1161 1162
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'BLOB';
    }
1163
}