OraclePlatform.php 33.2 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
     * @return void
     *
42 43
     * @throws DBALException
     */
44
    public static function assertValidIdentifier($identifier)
45
    {
46 47
        if (! preg_match('(^(([a-zA-Z]{1}[a-zA-Z0-9_$#]{0,})|("[^"]+"))$)', $identifier)) {
            throw new DBALException('Invalid Oracle identifier');
48 49 50
        }
    }

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

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

    /**
64
     * @param string $type
65 66
     *
     * @return string
67 68 69 70 71 72 73 74 75 76 77 78
     */
    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\')';
        }
    }

79
    /**
80
     * {@inheritDoc}
81 82 83
     */
    public function getLocateExpression($str, $substr, $startPos = false)
    {
84 85
        if ($startPos === false) {
            return 'INSTR(' . $str . ', ' . $substr . ')';
86
        }
87

88
        return 'INSTR(' . $str . ', ' . $substr . ', ' . $startPos . ')';
89 90
    }

91
    /**
92
     * {@inheritDoc}
93 94
     *
     * @deprecated Use application-generated UUIDs instead
95 96 97 98 99
     */
    public function getGuidExpression()
    {
        return 'SYS_GUID()';
    }
100

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

115
                    case DateIntervalUnit::YEAR:
116 117 118 119 120
                        $interval *= 12;
                        break;
                }

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

122 123
            default:
                $calculationClause = '';
124

125
                switch ($unit) {
126
                    case DateIntervalUnit::SECOND:
127 128
                        $calculationClause = '/24/60/60';
                        break;
129

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

134
                    case DateIntervalUnit::HOUR:
135 136
                        $calculationClause = '/24';
                        break;
137

138
                    case DateIntervalUnit::WEEK:
139 140 141 142 143 144
                        $calculationClause = '*7';
                        break;
                }

                return '(' . $date . $operator . $interval . $calculationClause . ')';
        }
145 146
    }

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

155
    /**
156
     * {@inheritDoc}
157 158 159
     */
    public function getBitAndComparisonExpression($value1, $value2)
    {
160
        return 'BITAND(' . $value1 . ', ' . $value2 . ')';
161 162 163
    }

    /**
164
     * {@inheritDoc}
165 166 167
     */
    public function getBitOrComparisonExpression($value1, $value2)
    {
168 169
        return '(' . $value1 . '-' .
                $this->getBitAndComparisonExpression($value1, $value2)
170 171
                . '+' . $value2 . ')';
    }
172

173
    /**
174
     * {@inheritDoc}
175
     *
176 177 178
     * 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()}
179
     */
180
    public function getCreateSequenceSQL(Sequence $sequence)
181
    {
182
        return 'CREATE SEQUENCE ' . $sequence->getQuotedName($this) .
183
               ' START WITH ' . $sequence->getInitialValue() .
184
               ' MINVALUE ' . $sequence->getInitialValue() .
185 186
               ' INCREMENT BY ' . $sequence->getAllocationSize() .
               $this->getSequenceCacheSQL($sequence);
187
    }
188

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

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

        if ($sequence->getCache() === 1) {
211
            return ' NOCACHE';
212 213 214
        }

        if ($sequence->getCache() > 1) {
215 216 217 218
            return ' CACHE ' . $sequence->getCache();
        }

        return '';
219
    }
220

romanb's avatar
romanb committed
221
    /**
222
     * {@inheritDoc}
romanb's avatar
romanb committed
223
     */
224
    public function getSequenceNextValSQL($sequenceName)
romanb's avatar
romanb committed
225
    {
226
        return 'SELECT ' . $sequenceName . '.nextval FROM DUAL';
romanb's avatar
romanb committed
227
    }
228

romanb's avatar
romanb committed
229
    /**
230
     * {@inheritDoc}
romanb's avatar
romanb committed
231
     */
232
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
233
    {
234
        return 'SET TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
235
    }
236

237 238 239
    /**
     * {@inheritDoc}
     */
240
    protected function _getTransactionIsolationLevelSQL($level)
romanb's avatar
romanb committed
241 242
    {
        switch ($level) {
243
            case TransactionIsolationLevel::READ_UNCOMMITTED:
244
                return 'READ UNCOMMITTED';
245
            case TransactionIsolationLevel::READ_COMMITTED:
246
                return 'READ COMMITTED';
247 248
            case TransactionIsolationLevel::REPEATABLE_READ:
            case TransactionIsolationLevel::SERIALIZABLE:
romanb's avatar
romanb committed
249 250
                return 'SERIALIZABLE';
            default:
251
                return parent::_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
252 253
        }
    }
254

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

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

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

    /**
280
     * {@inheritDoc}
281
     */
282
    public function getSmallIntTypeDeclarationSQL(array $field)
283 284 285 286
    {
        return 'NUMBER(5)';
    }

287
    /**
288
     * {@inheritDoc}
289
     */
290
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
291 292 293 294 295
    {
        return 'TIMESTAMP(0)';
    }

    /**
296
     * {@inheritDoc}
297 298
     */
    public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration)
299
    {
300
        return 'TIMESTAMP(0) WITH TIME ZONE';
301 302
    }

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

    /**
312
     * {@inheritDoc}
313
     */
314
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
315 316 317 318
    {
        return 'DATE';
    }

319
    /**
320
     * {@inheritDoc}
321
     */
322
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
323 324 325 326 327
    {
        return '';
    }

    /**
328
     * {@inheritDoc}
329
     */
330 331
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
    {
332 333 334
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(2000)')
                : ($length ? 'VARCHAR2(' . $length . ')' : 'VARCHAR2(4000)');
    }
335

Steve Müller's avatar
Steve Müller committed
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
        return 'RAW(' . ($length ?: $this->getBinaryMaxLength()) . ')';
    }

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

352 353 354
    /**
     * {@inheritDoc}
     */
355
    public function getClobTypeDeclarationSQL(array $field)
356 357 358
    {
        return 'CLOB';
    }
359

Benjamin Morel's avatar
Benjamin Morel committed
360 361 362
    /**
     * {@inheritDoc}
     */
363
    public function getListDatabasesSQL()
364
    {
365
        return 'SELECT username FROM all_users';
366 367
    }

Benjamin Morel's avatar
Benjamin Morel committed
368 369 370
    /**
     * {@inheritDoc}
     */
371
    public function getListSequencesSQL($database)
jwage's avatar
jwage committed
372
    {
373
        $database = $this->normalizeIdentifier($database);
374
        $database = $this->quoteStringLiteral($database->getName());
375

376 377
        return 'SELECT sequence_name, min_value, increment_by FROM sys.all_sequences ' .
               'WHERE SEQUENCE_OWNER = ' . $database;
jwage's avatar
jwage committed
378 379
    }

380
    /**
381
     * {@inheritDoc}
382
     */
383
    protected function _getCreateTableSQL($table, array $columns, array $options = [])
384
    {
Gabriel Caruso's avatar
Gabriel Caruso committed
385
        $indexes            = $options['indexes'] ?? [];
386
        $options['indexes'] = [];
Gabriel Caruso's avatar
Gabriel Caruso committed
387
        $sql                = parent::_getCreateTableSQL($table, $columns, $options);
388 389 390

        foreach ($columns as $name => $column) {
            if (isset($column['sequence'])) {
391
                $sql[] = $this->getCreateSequenceSQL($column['sequence']);
392 393
            }

394 395 396
            if (! isset($column['autoincrement']) || ! $column['autoincrement'] &&
               (! isset($column['autoinc']) || ! $column['autoinc'])) {
                continue;
397
            }
398 399

            $sql = array_merge($sql, $this->getCreateAutoincrementSql($name, $table));
400
        }
401

402
        if (isset($indexes) && ! empty($indexes)) {
403
            foreach ($indexes as $index) {
404
                $sql[] = $this->getCreateIndexSQL($index, $table);
405 406 407 408 409 410
            }
        }

        return $sql;
    }

411
    /**
412 413
     * {@inheritDoc}
     *
414 415
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaOracleReader.html
     */
416
    public function getListTableIndexesSQL($table, $currentDatabase = null)
417
    {
418
        $table = $this->normalizeIdentifier($table);
419
        $table = $this->quoteStringLiteral($table->getName());
420

421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
        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
443
                           WHERE  ucon.index_name = uind_col.index_name
444 445
                       ) AS is_primary
             FROM      user_ind_columns uind_col
446 447
             WHERE     uind_col.table_name = " . $table . '
             ORDER BY  uind_col.column_position ASC';
448 449
    }

Benjamin Morel's avatar
Benjamin Morel committed
450 451 452
    /**
     * {@inheritDoc}
     */
453
    public function getListTablesSQL()
454 455 456 457
    {
        return 'SELECT * FROM sys.user_tables';
    }

458 459 460
    /**
     * {@inheritDoc}
     */
461
    public function getListViewsSQL($database)
462
    {
463
        return 'SELECT view_name, text FROM sys.user_views';
464 465
    }

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

Benjamin Morel's avatar
Benjamin Morel committed
474 475 476
    /**
     * {@inheritDoc}
     */
477
    public function getDropViewSQL($name)
478
    {
479
        return 'DROP VIEW ' . $name;
480 481
    }

Benjamin Morel's avatar
Benjamin Morel committed
482
    /**
483 484 485
     * @param string $name
     * @param string $table
     * @param int    $start
Benjamin Morel's avatar
Benjamin Morel committed
486
     *
487
     * @return string[]
Benjamin Morel's avatar
Benjamin Morel committed
488
     */
489 490
    public function getCreateAutoincrementSql($name, $table, $start = 1)
    {
491 492
        $tableIdentifier   = $this->normalizeIdentifier($table);
        $quotedTableName   = $tableIdentifier->getQuotedName($this);
493 494 495
        $unquotedTableName = $tableIdentifier->getName();

        $nameIdentifier = $this->normalizeIdentifier($name);
496 497
        $quotedName     = $nameIdentifier->getQuotedName($this);
        $unquotedName   = $nameIdentifier->getName();
498

499
        $sql = [];
500

501
        $autoincrementIdentifierName = $this->getAutoincrementIdentifierName($tableIdentifier);
502

503
        $idx = new Index($autoincrementIdentifierName, [$quotedName], true, true);
504

505 506 507
        $sql[] = 'DECLARE
  constraints_Count NUMBER;
BEGIN
508
  SELECT COUNT(CONSTRAINT_NAME) INTO constraints_Count FROM USER_CONSTRAINTS WHERE TABLE_NAME = \'' . $unquotedTableName . '\' AND CONSTRAINT_TYPE = \'P\';
509
  IF constraints_Count = 0 OR constraints_Count = \'\' THEN
510
    EXECUTE IMMEDIATE \'' . $this->getCreateConstraintSQL($idx, $quotedTableName) . '\';
511
  END IF;
512
END;';
513

514 515 516 517
        $sequenceName = $this->getIdentitySequenceName(
            $tableIdentifier->isQuoted() ? $quotedTableName : $unquotedTableName,
            $nameIdentifier->isQuoted() ? $quotedName : $unquotedName
        );
518 519
        $sequence     = new Sequence($sequenceName, $start);
        $sql[]        = $this->getCreateSequenceSQL($sequence);
520

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

543 544 545
        return $sql;
    }

Benjamin Morel's avatar
Benjamin Morel committed
546
    /**
547 548 549
     * 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
550
     *
551
     * @return string[]
Benjamin Morel's avatar
Benjamin Morel committed
552
     */
553 554
    public function getDropAutoincrementSql($table)
    {
555
        $table                       = $this->normalizeIdentifier($table);
556
        $autoincrementIdentifierName = $this->getAutoincrementIdentifierName($table);
557
        $identitySequenceName        = $this->getIdentitySequenceName(
558 559 560
            $table->isQuoted() ? $table->getQuotedName($this) : $table->getName(),
            ''
        );
561

562
        return [
563
            'DROP TRIGGER ' . $autoincrementIdentifierName,
564 565
            $this->getDropSequenceSQL($identitySequenceName),
            $this->getDropConstraintSQL($autoincrementIdentifierName, $table->getQuotedName($this)),
566
        ];
567
    }
568

569 570 571 572 573 574 575 576 577 578 579 580 581
    /**
     * 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);
582

583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
        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;
603 604
    }

Benjamin Morel's avatar
Benjamin Morel committed
605 606 607
    /**
     * {@inheritDoc}
     */
608
    public function getListTableForeignKeysSQL($table)
609
    {
610 611
        $table = $this->normalizeIdentifier($table);
        $table = $this->quoteStringLiteral($table->getName());
612

613 614 615 616
        return "SELECT alc.constraint_name,
          alc.DELETE_RULE,
          cols.column_name \"local_column\",
          cols.position,
617 618 619 620 621 622 623 624 625 626 627 628
          (
              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\"
629
     FROM user_cons_columns cols
630
     JOIN user_constraints alc
631 632
       ON alc.constraint_name = cols.constraint_name
      AND alc.constraint_type = 'R'
633 634
      AND alc.table_name = " . $table . '
    ORDER BY cols.constraint_name ASC, cols.position ASC';
635 636
    }

Benjamin Morel's avatar
Benjamin Morel committed
637 638 639
    /**
     * {@inheritDoc}
     */
640
    public function getListTableConstraintsSQL($table)
641
    {
642
        $table = $this->normalizeIdentifier($table);
643
        $table = $this->quoteStringLiteral($table->getName());
644

645
        return 'SELECT * FROM user_constraints WHERE table_name = ' . $table;
646 647
    }

Benjamin Morel's avatar
Benjamin Morel committed
648 649 650
    /**
     * {@inheritDoc}
     */
651
    public function getListTableColumnsSQL($table, $database = null)
652
    {
653
        $table = $this->normalizeIdentifier($table);
654
        $table = $this->quoteStringLiteral($table->getName());
655

656 657 658
        $tabColumnsTableName       = 'user_tab_columns';
        $colCommentsTableName      = 'user_col_comments';
        $tabColumnsOwnerCondition  = '';
659
        $colCommentsOwnerCondition = '';
660

661 662 663 664 665
        if ($database !== null && $database !== '/') {
            $database                  = $this->normalizeIdentifier($database);
            $database                  = $this->quoteStringLiteral($database->getName());
            $tabColumnsTableName       = 'all_tab_columns';
            $colCommentsTableName      = 'all_col_comments';
666 667
            $tabColumnsOwnerCondition  = ' AND c.owner = ' . $database;
            $colCommentsOwnerCondition = ' AND d.OWNER = c.OWNER';
668
        }
669

670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
        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
        );
690 691
    }

692
    /**
693
     * {@inheritDoc}
694
     */
695
    public function getDropSequenceSQL($sequence)
696
    {
697
        if ($sequence instanceof Sequence) {
698
            $sequence = $sequence->getQuotedName($this);
699 700 701
        }

        return 'DROP SEQUENCE ' . $sequence;
702 703
    }

704
    /**
705
     * {@inheritDoc}
706
     */
707
    public function getDropForeignKeySQL($foreignKey, $table)
708
    {
709 710
        if (! $foreignKey instanceof ForeignKeyConstraint) {
            $foreignKey = new Identifier($foreignKey);
711 712
        }

713 714
        if (! $table instanceof Table) {
            $table = new Identifier($table);
715 716
        }

717
        $foreignKey = $foreignKey->getQuotedName($this);
718
        $table      = $table->getQuotedName($this);
719

720 721 722
        return 'ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $foreignKey;
    }

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 749
    /**
     * {@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 '';
750

751 752 753
            case 'CASCADE':
            case 'SET NULL':
                return $action;
754

755 756
            default:
                // SET DEFAULT is not supported, throw exception instead.
757
                throw new InvalidArgumentException('Invalid foreign key action: ' . $action);
758 759 760
        }
    }

761 762 763
    /**
     * {@inheritDoc}
     */
764
    public function getDropDatabaseSQL($database)
765 766 767 768
    {
        return 'DROP USER ' . $database . ' CASCADE';
    }

769
    /**
770
     * {@inheritDoc}
771
     */
772
    public function getAlterTableSQL(TableDiff $diff)
773
    {
774
        $sql         = [];
775
        $commentsSQL = [];
776
        $columnSql   = [];
777

778
        $fields = [];
779

780
        foreach ($diff->addedColumns as $column) {
781 782
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
783 784
            }

785
            $fields[] = $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
786 787 788
            $comment  = $this->getColumnComment($column);

            if (! $comment) {
789
                continue;
790
            }
791 792 793 794 795 796

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

799
        if (count($fields)) {
800
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ADD (' . implode(', ', $fields) . ')';
801 802
        }

803
        $fields = [];
804
        foreach ($diff->changedColumns as $columnDiff) {
805 806
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
807 808
            }

809
            $column = $columnDiff->column;
Steve Müller's avatar
Steve Müller committed
810 811 812 813 814 815 816 817 818 819 820

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

821 822 823 824 825
            $columnHasChangedComment = $columnDiff->hasChanged('comment');

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

829
                if (! $columnDiff->hasChanged('notnull')) {
830
                    unset($columnInfo['notnull']);
831 832
                }

833
                $fields[] = $column->getQuotedName($this) . $this->getColumnDeclarationSQL('', $columnInfo);
834 835
            }

836 837
            if (! $columnHasChangedComment) {
                continue;
838
            }
839 840 841 842 843 844

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

847
        if (count($fields)) {
848
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' MODIFY (' . implode(', ', $fields) . ')';
849 850
        }

851
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
852 853
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
854 855
            }

856 857
            $oldColumnName = new Identifier($oldColumnName);

858
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) .
859
                ' RENAME COLUMN ' . $oldColumnName->getQuotedName($this) . ' TO ' . $column->getQuotedName($this);
860 861
        }

862
        $fields = [];
863
        foreach ($diff->removedColumns as $column) {
864 865
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
866 867
            }

868
            $fields[] = $column->getQuotedName($this);
869
        }
870

871
        if (count($fields)) {
872
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' DROP (' . implode(', ', $fields) . ')';
873 874
        }

875
        $tableSql = [];
876

877
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
878 879
            $sql = array_merge($sql, $commentsSQL);

Sergei Morozov's avatar
Sergei Morozov committed
880 881 882 883 884 885 886 887
            $newName = $diff->getNewName();

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

890 891 892 893 894
            $sql = array_merge(
                $this->getPreAlterTableIndexForeignKeySQL($diff),
                $sql,
                $this->getPostAlterTableIndexForeignKeySQL($diff)
            );
895 896
        }

897
        return array_merge($sql, $tableSql, $columnSql);
898 899
    }

900 901 902 903 904 905 906 907 908 909
    /**
     * {@inheritdoc}
     */
    public function getColumnDeclarationSQL($name, array $field)
    {
        if (isset($field['columnDefinition'])) {
            $columnDef = $this->getCustomTypeDeclarationSQL($field);
        } else {
            $default = $this->getDefaultValueDeclarationSQL($field);

910 911 912 913 914
            $notnull = '';

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

916
            $unique = isset($field['unique']) && $field['unique'] ?
917 918
                ' ' . $this->getUniqueFieldDeclarationSQL() : '';

919
            $check = isset($field['check']) && $field['check'] ?
920 921
                ' ' . $field['check'] : '';

922
            $typeDecl  = $field['type']->getSQLDeclaration($field, $this);
923 924 925 926 927 928
            $columnDef = $typeDecl . $default . $notnull . $unique . $check;
        }

        return $name . ' ' . $columnDef;
    }

929 930 931 932 933
    /**
     * {@inheritdoc}
     */
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
    {
934
        if (strpos($tableName, '.') !== false) {
935
            [$schema]     = explode('.', $tableName);
936 937 938
            $oldIndexName = $schema . '.' . $oldIndexName;
        }

939
        return ['ALTER INDEX ' . $oldIndexName . ' RENAME TO ' . $index->getQuotedName($this)];
940 941
    }

942
    /**
943
     * {@inheritDoc}
944 945 946 947 948
     */
    public function prefersSequences()
    {
        return true;
    }
949

950 951 952 953 954 955 956 957 958 959 960 961 962
    /**
     * {@inheritdoc}
     */
    public function usesSequenceEmulatedIdentityColumns()
    {
        return true;
    }

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

965 966 967 968
        // No usage of column name to preserve BC compatibility with <2.5
        $identitySequenceName = $table->getName() . '_SEQ';

        if ($table->isQuoted()) {
969 970 971 972 973 974
            $identitySequenceName = '"' . $identitySequenceName . '"';
        }

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

        return $identitySequenceIdentifier->getQuotedName($this);
975 976
    }

977 978 979
    /**
     * {@inheritDoc}
     */
980 981 982 983 984
    public function supportsCommentOnStatement()
    {
        return true;
    }

985
    /**
986
     * {@inheritDoc}
987 988 989 990 991
     */
    public function getName()
    {
        return 'oracle';
    }
992 993

    /**
994
     * {@inheritDoc}
995
     */
996
    protected function doModifyLimitQuery($query, $limit, $offset = null)
997
    {
998
        if ($limit === null && $offset <= 0) {
999 1000
            return $query;
        }
1001

1002
        if (preg_match('/^\s*SELECT/i', $query)) {
1003 1004
            if (! preg_match('/\sFROM\s/i', $query)) {
                $query .= ' FROM dual';
1005
            }
1006

1007
            $columns = ['a.*'];
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020

            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);
1021 1022
            }
        }
1023

1024 1025
        return $query;
    }
1026

1027
    /**
1028
     * {@inheritDoc}
1029
     *
1030 1031
     * Oracle returns all column names in SQL result sets in uppercase.
     */
1032
    public function getSQLResultCasing($column)
1033 1034 1035
    {
        return strtoupper($column);
    }
1036

Benjamin Morel's avatar
Benjamin Morel committed
1037 1038 1039
    /**
     * {@inheritDoc}
     */
1040
    public function getCreateTemporaryTableSnippetSQL()
1041
    {
1042
        return 'CREATE GLOBAL TEMPORARY TABLE';
1043
    }
1044

1045 1046 1047
    /**
     * {@inheritDoc}
     */
1048
    public function getDateTimeTzFormatString()
1049 1050 1051
    {
        return 'Y-m-d H:i:sP';
    }
1052

1053 1054 1055
    /**
     * {@inheritDoc}
     */
1056 1057 1058 1059 1060
    public function getDateFormatString()
    {
        return 'Y-m-d 00:00:00';
    }

1061 1062 1063
    /**
     * {@inheritDoc}
     */
1064 1065 1066 1067
    public function getTimeFormatString()
    {
        return '1900-01-01 H:i:s';
    }
1068

1069 1070 1071
    /**
     * {@inheritDoc}
     */
1072 1073 1074 1075 1076 1077
    public function fixSchemaElementName($schemaElementName)
    {
        if (strlen($schemaElementName) > 30) {
            // Trim it
            return substr($schemaElementName, 0, 30);
        }
1078

1079 1080
        return $schemaElementName;
    }
1081

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

1090
    /**
1091
     * {@inheritDoc}
1092 1093 1094 1095 1096
     */
    public function supportsSequences()
    {
        return true;
    }
1097

1098 1099 1100
    /**
     * {@inheritDoc}
     */
1101 1102 1103 1104
    public function supportsForeignKeyOnUpdate()
    {
        return false;
    }
1105

1106
    /**
1107
     * {@inheritDoc}
1108 1109 1110 1111 1112 1113
     */
    public function supportsReleaseSavepoints()
    {
        return false;
    }

1114
    /**
1115
     * {@inheritDoc}
1116
     */
1117
    public function getTruncateTableSQL($tableName, $cascade = false)
1118
    {
1119 1120 1121
        $tableIdentifier = new Identifier($tableName);

        return 'TRUNCATE TABLE ' . $tableIdentifier->getQuotedName($this);
1122
    }
1123 1124

    /**
1125
     * {@inheritDoc}
1126 1127 1128
     */
    public function getDummySelectSQL()
    {
1129 1130 1131
        $expression = func_num_args() > 0 ? func_get_arg(0) : '1';

        return sprintf('SELECT %s FROM DUAL', $expression);
1132
    }
1133

1134 1135 1136
    /**
     * {@inheritDoc}
     */
1137 1138
    protected function initializeDoctrineTypeMappings()
    {
1139
        $this->doctrineTypeMapping = [
1140 1141 1142 1143 1144 1145 1146 1147 1148
            'integer'           => 'integer',
            'number'            => 'integer',
            'pls_integer'       => 'boolean',
            'binary_integer'    => 'boolean',
            'varchar'           => 'string',
            'varchar2'          => 'string',
            'nvarchar2'         => 'string',
            'char'              => 'string',
            'nchar'             => 'string',
1149
            'date'              => 'date',
1150 1151
            'timestamp'         => 'datetime',
            'timestamptz'       => 'datetimetz',
1152
            'float'             => 'float',
1153 1154
            'binary_float'      => 'float',
            'binary_double'     => 'float',
1155 1156 1157
            'long'              => 'string',
            'clob'              => 'text',
            'nclob'             => 'text',
Steve Müller's avatar
Steve Müller committed
1158 1159
            'raw'               => 'binary',
            'long raw'          => 'blob',
1160
            'rowid'             => 'string',
1161
            'urowid'            => 'string',
1162
            'blob'              => 'blob',
1163
        ];
1164
    }
1165 1166

    /**
1167
     * {@inheritDoc}
1168 1169 1170 1171 1172
     */
    public function releaseSavePoint($savepoint)
    {
        return '';
    }
1173

1174 1175 1176
    /**
     * {@inheritDoc}
     */
1177 1178
    protected function getReservedKeywordsClass()
    {
1179
        return Keywords\OracleKeywords::class;
1180
    }
1181 1182

    /**
1183
     * {@inheritDoc}
1184 1185 1186 1187 1188
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'BLOB';
    }
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209

    public function getListTableCommentsSQL(string $table, ?string $database = null) : string
    {
        $tableCommentsName = 'user_tab_comments';
        $ownerCondition    = '';

        if ($database !== null && $database !== '/') {
            $tableCommentsName = 'all_tab_comments';
            $ownerCondition    = ' AND owner = ' . $this->quoteStringLiteral($this->normalizeIdentifier($database)->getName());
        }

        return sprintf(
            <<<'SQL'
SELECT comments FROM %s WHERE table_name = %s%s
SQL
            ,
            $tableCommentsName,
            $this->quoteStringLiteral($this->normalizeIdentifier($table)->getName()),
            $ownerCondition
        );
    }
1210
}