OraclePlatform.php 33.3 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
        if (preg_match('(^(([a-zA-Z]{1}[a-zA-Z0-9_$#]{0,})|("[^"]+"))$)', $identifier) === 0) {
47
            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
        return $fixed ? ($length > 0 ? 'CHAR(' . $length . ')' : 'CHAR(2000)')
                : ($length > 0 ? 'VARCHAR2(' . $length . ')' : 'VARCHAR2(4000)');
334
    }
335

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

    /**
     * {@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
    /**
     * {@inheritdoc}
     */
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
    {
728
        $referentialAction = '';
729 730 731 732 733

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

734 735 736 737 738
        if ($referentialAction !== '') {
            return ' ON DELETE ' . $referentialAction;
        }

        return '';
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
    }

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

755 756 757
            case 'CASCADE':
            case 'SET NULL':
                return $action;
758

759 760
            default:
                // SET DEFAULT is not supported, throw exception instead.
761
                throw new InvalidArgumentException('Invalid foreign key action: ' . $action);
762 763 764
        }
    }

765 766 767
    /**
     * {@inheritDoc}
     */
768
    public function getDropDatabaseSQL($database)
769 770 771 772
    {
        return 'DROP USER ' . $database . ' CASCADE';
    }

773
    /**
774
     * {@inheritDoc}
775
     */
776
    public function getAlterTableSQL(TableDiff $diff)
777
    {
778
        $sql         = [];
779
        $commentsSQL = [];
780
        $columnSql   = [];
781

782
        $fields = [];
783

784
        foreach ($diff->addedColumns as $column) {
785 786
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
787 788
            }

789
            $fields[] = $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
790 791
            $comment  = $this->getColumnComment($column);

792
            if ($comment === null || $comment === '') {
793
                continue;
794
            }
795 796 797 798 799 800

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

803
        if (count($fields) > 0) {
804
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ADD (' . implode(', ', $fields) . ')';
805 806
        }

807
        $fields = [];
808
        foreach ($diff->changedColumns as $columnDiff) {
809 810
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
811 812
            }

813
            $column = $columnDiff->column;
Steve Müller's avatar
Steve Müller committed
814 815 816 817 818 819 820 821 822 823 824

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

825 826 827 828 829
            $columnHasChangedComment = $columnDiff->hasChanged('comment');

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

833
                if (! $columnDiff->hasChanged('notnull')) {
834
                    unset($columnInfo['notnull']);
835 836
                }

837
                $fields[] = $column->getQuotedName($this) . $this->getColumnDeclarationSQL('', $columnInfo);
838 839
            }

840 841
            if (! $columnHasChangedComment) {
                continue;
842
            }
843 844 845 846 847 848

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

851
        if (count($fields) > 0) {
852
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' MODIFY (' . implode(', ', $fields) . ')';
853 854
        }

855
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
856 857
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
858 859
            }

860 861
            $oldColumnName = new Identifier($oldColumnName);

862
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) .
863
                ' RENAME COLUMN ' . $oldColumnName->getQuotedName($this) . ' TO ' . $column->getQuotedName($this);
864 865
        }

866
        $fields = [];
867
        foreach ($diff->removedColumns as $column) {
868 869
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
870 871
            }

872
            $fields[] = $column->getQuotedName($this);
873
        }
874

875
        if (count($fields) > 0) {
876
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' DROP (' . implode(', ', $fields) . ')';
877 878
        }

879
        $tableSql = [];
880

881
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
882 883
            $sql = array_merge($sql, $commentsSQL);

Sergei Morozov's avatar
Sergei Morozov committed
884 885 886 887 888 889 890 891
            $newName = $diff->getNewName();

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

894 895 896 897 898
            $sql = array_merge(
                $this->getPreAlterTableIndexForeignKeySQL($diff),
                $sql,
                $this->getPostAlterTableIndexForeignKeySQL($diff)
            );
899 900
        }

901
        return array_merge($sql, $tableSql, $columnSql);
902 903
    }

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

914 915 916 917 918
            $notnull = '';

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

920
            $unique = ! empty($field['unique']) ?
921 922
                ' ' . $this->getUniqueFieldDeclarationSQL() : '';

923
            $check = ! empty($field['check']) ?
924 925
                ' ' . $field['check'] : '';

926
            $typeDecl  = $field['type']->getSQLDeclaration($field, $this);
927 928 929 930 931 932
            $columnDef = $typeDecl . $default . $notnull . $unique . $check;
        }

        return $name . ' ' . $columnDef;
    }

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

943
        return ['ALTER INDEX ' . $oldIndexName . ' RENAME TO ' . $index->getQuotedName($this)];
944 945
    }

946
    /**
947
     * {@inheritDoc}
948 949 950 951 952
     */
    public function prefersSequences()
    {
        return true;
    }
953

954 955 956 957 958 959 960 961 962 963 964 965 966
    /**
     * {@inheritdoc}
     */
    public function usesSequenceEmulatedIdentityColumns()
    {
        return true;
    }

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

969 970 971 972
        // No usage of column name to preserve BC compatibility with <2.5
        $identitySequenceName = $table->getName() . '_SEQ';

        if ($table->isQuoted()) {
973 974 975 976 977 978
            $identitySequenceName = '"' . $identitySequenceName . '"';
        }

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

        return $identitySequenceIdentifier->getQuotedName($this);
979 980
    }

981 982 983
    /**
     * {@inheritDoc}
     */
984 985 986 987 988
    public function supportsCommentOnStatement()
    {
        return true;
    }

989
    /**
990
     * {@inheritDoc}
991 992 993 994 995
     */
    public function getName()
    {
        return 'oracle';
    }
996 997

    /**
998
     * {@inheritDoc}
999
     */
1000
    protected function doModifyLimitQuery($query, $limit, $offset = null)
1001
    {
1002
        if ($limit === null && $offset <= 0) {
1003 1004
            return $query;
        }
1005

1006 1007
        if (preg_match('/^\s*SELECT/i', $query) === 1) {
            if (preg_match('/\sFROM\s/i', $query) === 0) {
1008
                $query .= ' FROM dual';
1009
            }
1010

1011
            $columns = ['a.*'];
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024

            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);
1025 1026
            }
        }
1027

1028 1029
        return $query;
    }
1030

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

Benjamin Morel's avatar
Benjamin Morel committed
1041 1042 1043
    /**
     * {@inheritDoc}
     */
1044
    public function getCreateTemporaryTableSnippetSQL()
1045
    {
1046
        return 'CREATE GLOBAL TEMPORARY TABLE';
1047
    }
1048

1049 1050 1051
    /**
     * {@inheritDoc}
     */
1052
    public function getDateTimeTzFormatString()
1053 1054 1055
    {
        return 'Y-m-d H:i:sP';
    }
1056

1057 1058 1059
    /**
     * {@inheritDoc}
     */
1060 1061 1062 1063 1064
    public function getDateFormatString()
    {
        return 'Y-m-d 00:00:00';
    }

1065 1066 1067
    /**
     * {@inheritDoc}
     */
1068 1069 1070 1071
    public function getTimeFormatString()
    {
        return '1900-01-01 H:i:s';
    }
1072

1073 1074 1075
    /**
     * {@inheritDoc}
     */
1076 1077 1078 1079 1080 1081
    public function fixSchemaElementName($schemaElementName)
    {
        if (strlen($schemaElementName) > 30) {
            // Trim it
            return substr($schemaElementName, 0, 30);
        }
1082

1083 1084
        return $schemaElementName;
    }
1085

1086
    /**
1087
     * {@inheritDoc}
1088 1089 1090 1091 1092 1093
     */
    public function getMaxIdentifierLength()
    {
        return 30;
    }

1094
    /**
1095
     * {@inheritDoc}
1096 1097 1098 1099 1100
     */
    public function supportsSequences()
    {
        return true;
    }
1101

1102 1103 1104
    /**
     * {@inheritDoc}
     */
1105 1106 1107 1108
    public function supportsForeignKeyOnUpdate()
    {
        return false;
    }
1109

1110
    /**
1111
     * {@inheritDoc}
1112 1113 1114 1115 1116 1117
     */
    public function supportsReleaseSavepoints()
    {
        return false;
    }

1118
    /**
1119
     * {@inheritDoc}
1120
     */
1121
    public function getTruncateTableSQL($tableName, $cascade = false)
1122
    {
1123 1124 1125
        $tableIdentifier = new Identifier($tableName);

        return 'TRUNCATE TABLE ' . $tableIdentifier->getQuotedName($this);
1126
    }
1127 1128

    /**
1129
     * {@inheritDoc}
1130 1131 1132
     */
    public function getDummySelectSQL()
    {
1133 1134 1135
        $expression = func_num_args() > 0 ? func_get_arg(0) : '1';

        return sprintf('SELECT %s FROM DUAL', $expression);
1136
    }
1137

1138 1139 1140
    /**
     * {@inheritDoc}
     */
1141 1142
    protected function initializeDoctrineTypeMappings()
    {
1143
        $this->doctrineTypeMapping = [
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
            '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',
1167
        ];
1168
    }
1169 1170

    /**
1171
     * {@inheritDoc}
1172 1173 1174 1175 1176
     */
    public function releaseSavePoint($savepoint)
    {
        return '';
    }
1177

1178 1179 1180
    /**
     * {@inheritDoc}
     */
1181 1182
    protected function getReservedKeywordsClass()
    {
1183
        return Keywords\OracleKeywords::class;
1184
    }
1185 1186

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

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