OraclePlatform.php 33.7 KB
Newer Older
1
<?php
romanb's avatar
romanb committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
Benjamin Eberlei's avatar
Benjamin Eberlei committed
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
romanb's avatar
romanb committed
18
 */
19

20
namespace Doctrine\DBAL\Platforms;
21

22
use Doctrine\DBAL\DBALException;
23
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
24
use Doctrine\DBAL\Schema\Identifier;
25 26 27
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\Sequence;
use Doctrine\DBAL\Schema\Table;
28
use Doctrine\DBAL\Schema\TableDiff;
Steve Müller's avatar
Steve Müller committed
29
use Doctrine\DBAL\Types\BinaryType;
30

romanb's avatar
romanb committed
31
/**
32
 * OraclePlatform.
romanb's avatar
romanb committed
33 34 35 36
 *
 * @since 2.0
 * @author Roman Borschel <roman@code-factory.org>
 * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
37
 * @author Benjamin Eberlei <kontakt@beberlei.de>
romanb's avatar
romanb committed
38
 */
39
class OraclePlatform extends AbstractPlatform
40
{
41
    /**
Benjamin Morel's avatar
Benjamin Morel committed
42
     * Assertion for Oracle identifiers.
43 44
     *
     * @link http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements008.htm
45
     *
Benjamin Morel's avatar
Benjamin Morel committed
46
     * @param string $identifier
47
     *
48 49 50 51 52 53 54 55 56
     * @throws DBALException
     */
    static public function assertValidIdentifier($identifier)
    {
        if ( ! preg_match('(^(([a-zA-Z]{1}[a-zA-Z0-9_$#]{0,})|("[^"]+"))$)', $identifier)) {
            throw new DBALException("Invalid Oracle identifier");
        }
    }

57
    /**
58
     * {@inheritDoc}
59 60 61
     */
    public function getSubstringExpression($value, $position, $length = null)
    {
62
        if ($length !== null) {
63
            return "SUBSTR($value, $position, $length)";
64
        }
65 66 67 68 69

        return "SUBSTR($value, $position)";
    }

    /**
70
     * {@inheritDoc}
71 72 73 74 75 76 77 78 79 80 81 82
     */
    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\')';
        }
    }

83
    /**
84
     * {@inheritDoc}
85 86 87 88 89 90
     */
    public function getLocateExpression($str, $substr, $startPos = false)
    {
        if ($startPos == false) {
            return 'INSTR('.$str.', '.$substr.')';
        }
91 92

        return 'INSTR('.$str.', '.$substr.', '.$startPos.')';
93 94
    }

95
    /**
96
     * {@inheritDoc}
97 98 99 100 101
     */
    public function getGuidExpression()
    {
        return 'SYS_GUID()';
    }
102

103
    /**
104
     * {@inheritdoc}
105
     */
106
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
107
    {
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
        switch ($unit) {
            case self::DATE_INTERVAL_UNIT_MONTH:
            case self::DATE_INTERVAL_UNIT_QUARTER:
            case self::DATE_INTERVAL_UNIT_YEAR:
                switch ($unit) {
                    case self::DATE_INTERVAL_UNIT_QUARTER:
                        $interval *= 3;
                        break;

                    case self::DATE_INTERVAL_UNIT_YEAR:
                        $interval *= 12;
                        break;
                }

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

124 125
            default:
                $calculationClause = '';
126

127 128 129 130
                switch ($unit) {
                    case self::DATE_INTERVAL_UNIT_SECOND:
                        $calculationClause = '/24/60/60';
                        break;
131

132 133 134
                    case self::DATE_INTERVAL_UNIT_MINUTE:
                        $calculationClause = '/24/60';
                        break;
135

136 137 138
                    case self::DATE_INTERVAL_UNIT_HOUR:
                        $calculationClause = '/24';
                        break;
139

140 141 142 143 144 145 146
                    case self::DATE_INTERVAL_UNIT_WEEK:
                        $calculationClause = '*7';
                        break;
                }

                return '(' . $date . $operator . $interval . $calculationClause . ')';
        }
147 148
    }

149
    /**
150
     * {@inheritDoc}
151 152 153 154
     *
     * Note: Since Oracle timestamp differences are calculated down to the microsecond we have to truncate
     * them to the difference in days. This is obviously a restriction of the original functionality, but we
     * need to make this a portable function.
155
     */
156
    public function getDateDiffExpression($date1, $date2)
157
    {
158
        return "TRUNC(TO_NUMBER(SUBSTR((" . $date1 . "-" . $date2 . "), 1, INSTR(" . $date1 . "-" . $date2 .", ' '))))";
159
    }
Fabio B. Silva's avatar
Fabio B. Silva committed
160

161
    /**
162
     * {@inheritDoc}
163 164 165 166 167 168 169
     */
    public function getBitAndComparisonExpression($value1, $value2)
    {
        return 'BITAND('.$value1 . ', ' . $value2 . ')';
    }

    /**
170
     * {@inheritDoc}
171 172 173
     */
    public function getBitOrComparisonExpression($value1, $value2)
    {
174 175
        return '(' . $value1 . '-' .
                $this->getBitAndComparisonExpression($value1, $value2)
176 177
                . '+' . $value2 . ')';
    }
178

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

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

    /**
     * Cache definition for sequences
     *
jeroendedauw's avatar
jeroendedauw committed
208 209
     * @param Sequence $sequence
     *
210 211
     * @return string
     */
jeroendedauw's avatar
jeroendedauw committed
212
    private function getSequenceCacheSQL(Sequence $sequence)
213 214 215 216
    {
        if ($sequence->getCache() === 0) {
            return ' NOCACHE';
        } else if ($sequence->getCache() === 1) {
217
            return ' NOCACHE';
218 219 220 221 222
        } else if ($sequence->getCache() > 1) {
            return ' CACHE ' . $sequence->getCache();
        }

        return '';
223
    }
224

romanb's avatar
romanb committed
225
    /**
226
     * {@inheritDoc}
romanb's avatar
romanb committed
227
     */
228
    public function getSequenceNextValSQL($sequenceName)
romanb's avatar
romanb committed
229
    {
230
        return 'SELECT ' . $sequenceName . '.nextval FROM DUAL';
romanb's avatar
romanb committed
231
    }
232

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

241 242 243
    /**
     * {@inheritDoc}
     */
244
    protected function _getTransactionIsolationLevelSQL($level)
romanb's avatar
romanb committed
245 246
    {
        switch ($level) {
247
            case \Doctrine\DBAL\Connection::TRANSACTION_READ_UNCOMMITTED:
248
                return 'READ UNCOMMITTED';
249
            case \Doctrine\DBAL\Connection::TRANSACTION_READ_COMMITTED:
250
                return 'READ COMMITTED';
251 252
            case \Doctrine\DBAL\Connection::TRANSACTION_REPEATABLE_READ:
            case \Doctrine\DBAL\Connection::TRANSACTION_SERIALIZABLE:
romanb's avatar
romanb committed
253 254
                return 'SERIALIZABLE';
            default:
255
                return parent::_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
256 257
        }
    }
258

259
    /**
260
     * {@inheritDoc}
261
     */
262
    public function getBooleanTypeDeclarationSQL(array $field)
263 264 265
    {
        return 'NUMBER(1)';
    }
266

267
    /**
268
     * {@inheritDoc}
269
     */
270
    public function getIntegerTypeDeclarationSQL(array $field)
271 272 273 274 275
    {
        return 'NUMBER(10)';
    }

    /**
276
     * {@inheritDoc}
277
     */
278
    public function getBigIntTypeDeclarationSQL(array $field)
279 280 281 282 283
    {
        return 'NUMBER(20)';
    }

    /**
284
     * {@inheritDoc}
285
     */
286
    public function getSmallIntTypeDeclarationSQL(array $field)
287 288 289 290
    {
        return 'NUMBER(5)';
    }

291
    /**
292
     * {@inheritDoc}
293
     */
294
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
295 296 297 298 299
    {
        return 'TIMESTAMP(0)';
    }

    /**
300
     * {@inheritDoc}
301 302
     */
    public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration)
303
    {
304
        return 'TIMESTAMP(0) WITH TIME ZONE';
305 306
    }

307
    /**
308
     * {@inheritDoc}
309
     */
310
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
311 312 313 314 315
    {
        return 'DATE';
    }

    /**
316
     * {@inheritDoc}
317
     */
318
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
319 320 321 322
    {
        return 'DATE';
    }

323
    /**
324
     * {@inheritDoc}
325
     */
326
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
327 328 329 330 331
    {
        return '';
    }

    /**
332
     * {@inheritDoc}
333
     */
334 335
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
    {
336 337 338
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(2000)')
                : ($length ? 'VARCHAR2(' . $length . ')' : 'VARCHAR2(4000)');
    }
339

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

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

356 357 358
    /**
     * {@inheritDoc}
     */
359
    public function getClobTypeDeclarationSQL(array $field)
360 361 362
    {
        return 'CLOB';
    }
363

Benjamin Morel's avatar
Benjamin Morel committed
364 365 366
    /**
     * {@inheritDoc}
     */
367
    public function getListDatabasesSQL()
368
    {
369
        return 'SELECT username FROM all_users';
370 371
    }

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

380
        return "SELECT sequence_name, min_value, increment_by FROM sys.all_sequences ".
381
               "WHERE SEQUENCE_OWNER = " . $database;
jwage's avatar
jwage committed
382 383
    }

384
    /**
385
     * {@inheritDoc}
386
     */
387
    protected function _getCreateTableSQL($table, array $columns, array $options = array())
388
    {
389
        $indexes = isset($options['indexes']) ? $options['indexes'] : array();
390
        $options['indexes'] = array();
391
        $sql = parent::_getCreateTableSQL($table, $columns, $options);
392 393 394

        foreach ($columns as $name => $column) {
            if (isset($column['sequence'])) {
395
                $sql[] = $this->getCreateSequenceSQL($column['sequence'], 1);
396 397 398
            }

            if (isset($column['autoincrement']) && $column['autoincrement'] ||
399
               (isset($column['autoinc']) && $column['autoinc'])) {
400 401 402
                $sql = array_merge($sql, $this->getCreateAutoincrementSql($name, $table));
            }
        }
403

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

        return $sql;
    }

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

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

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

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

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

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

Benjamin Morel's avatar
Benjamin Morel committed
485 486 487 488 489 490 491
    /**
     * @param string  $name
     * @param string  $table
     * @param integer $start
     *
     * @return array
     */
492 493
    public function getCreateAutoincrementSql($name, $table, $start = 1)
    {
494 495 496 497 498 499 500
        $tableIdentifier = $this->normalizeIdentifier($table);
        $quotedTableName = $tableIdentifier->getQuotedName($this);
        $unquotedTableName = $tableIdentifier->getName();

        $nameIdentifier = $this->normalizeIdentifier($name);
        $quotedName = $nameIdentifier->getQuotedName($this);
        $unquotedName = $nameIdentifier->getName();
501

502
        $sql = array();
503

504
        $autoincrementIdentifierName = $this->getAutoincrementIdentifierName($tableIdentifier);
505

506
        $idx = new Index($autoincrementIdentifierName, array($quotedName), true, true);
507

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

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

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

546 547 548
        return $sql;
    }

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

565 566
        return array(
            'DROP TRIGGER ' . $autoincrementIdentifierName,
567 568
            $this->getDropSequenceSQL($identitySequenceName),
            $this->getDropConstraintSQL($autoincrementIdentifierName, $table->getQuotedName($this)),
569 570
        );
    }
571

572 573 574 575 576 577 578 579 580 581 582 583 584
    /**
     * 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);
585

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

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

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

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

648
        return "SELECT * FROM user_constraints WHERE table_name = " . $table;
649 650
    }

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

659
        $tabColumnsTableName = "user_tab_columns";
660
        $colCommentsTableName = "user_col_comments";
661 662
        $tabColumnsOwnerCondition = '';
        $colCommentsOwnerCondition = '';
663

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

673 674 675 676
        return "SELECT   c.*,
                         (
                             SELECT d.comments
                             FROM   $colCommentsTableName d
677
                             WHERE  d.TABLE_NAME = c.TABLE_NAME " . $colCommentsOwnerCondition . "
678 679 680
                             AND    d.COLUMN_NAME = c.COLUMN_NAME
                         ) AS comments
                FROM     $tabColumnsTableName c
681
                WHERE    c.table_name = " . $table . " $tabColumnsOwnerCondition
682
                ORDER BY c.column_id";
683 684
    }

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

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

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

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

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

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

716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
    /**
     * {@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.
                throw new \InvalidArgumentException('Invalid foreign key action: ' . $action);
        }
    }

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

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

        $fields = array();
772

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

778
            $fields[] = $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
779
            if ($comment = $this->getColumnComment($column)) {
780 781 782 783 784
                $commentsSQL[] = $this->getCommentOnColumnSQL(
                    $diff->getName($this)->getQuotedName($this),
                    $column->getQuotedName($this),
                    $comment
                );
785
            }
786
        }
787

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

792
        $fields = array();
793
        foreach ($diff->changedColumns as $columnDiff) {
794 795
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
796 797
            }

Steve Müller's avatar
Steve Müller committed
798
            /* @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */
799
            $column = $columnDiff->column;
Steve Müller's avatar
Steve Müller committed
800 801 802 803 804 805 806 807 808 809 810

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

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

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

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

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

            if ($columnHasChangedComment) {
                $commentsSQL[] = $this->getCommentOnColumnSQL(
828 829
                    $diff->getName($this)->getQuotedName($this),
                    $column->getQuotedName($this),
830 831
                    $this->getColumnComment($column)
                );
832
            }
833
        }
834

835
        if (count($fields)) {
836
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' MODIFY (' . implode(', ', $fields) . ')';
837 838
        }

839
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
840 841
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
842 843
            }

844 845
            $oldColumnName = new Identifier($oldColumnName);

846
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) .
847
                ' RENAME COLUMN ' . $oldColumnName->getQuotedName($this) .' TO ' . $column->getQuotedName($this);
848 849
        }

850
        $fields = array();
851
        foreach ($diff->removedColumns as $column) {
852 853
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
854 855
            }

856
            $fields[] = $column->getQuotedName($this);
857
        }
858

859
        if (count($fields)) {
860
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' DROP (' . implode(', ', $fields).')';
861 862
        }

863 864
        $tableSql = array();

865
        if ( ! $this->onSchemaAlterTable($diff, $tableSql)) {
866 867
            $sql = array_merge($sql, $commentsSQL);

868
            if ($diff->newName !== false) {
869
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' RENAME TO ' . $diff->getNewName()->getQuotedName($this);
870 871
            }

872 873 874 875 876
            $sql = array_merge(
                $this->getPreAlterTableIndexForeignKeySQL($diff),
                $sql,
                $this->getPostAlterTableIndexForeignKeySQL($diff)
            );
877 878
        }

879
        return array_merge($sql, $tableSql, $columnSql);
880 881
    }

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

892 893 894 895 896
            $notnull = '';

            if (isset($field['notnull'])) {
                $notnull = $field['notnull'] ? ' NOT NULL' : ' NULL';
            }
897 898 899 900 901 902 903

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

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

904
            $typeDecl = $field['type']->getSQLDeclaration($field, $this);
905 906 907 908 909 910
            $columnDef = $typeDecl . $default . $notnull . $unique . $check;
        }

        return $name . ' ' . $columnDef;
    }

911 912 913 914 915
    /**
     * {@inheritdoc}
     */
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
    {
916 917 918 919 920
        if (strpos($tableName, '.') !== false) {
            list($schema) = explode('.', $tableName);
            $oldIndexName = $schema . '.' . $oldIndexName;
        }

921 922 923
        return array('ALTER INDEX ' . $oldIndexName . ' RENAME TO ' . $index->getQuotedName($this));
    }

924
    /**
925
     * {@inheritDoc}
926 927 928 929 930
     */
    public function prefersSequences()
    {
        return true;
    }
931

932 933 934 935 936 937 938 939 940 941 942 943 944
    /**
     * {@inheritdoc}
     */
    public function usesSequenceEmulatedIdentityColumns()
    {
        return true;
    }

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

947 948 949 950
        // No usage of column name to preserve BC compatibility with <2.5
        $identitySequenceName = $table->getName() . '_SEQ';

        if ($table->isQuoted()) {
951 952 953 954 955 956
            $identitySequenceName = '"' . $identitySequenceName . '"';
        }

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

        return $identitySequenceIdentifier->getQuotedName($this);
957 958
    }

959 960 961
    /**
     * {@inheritDoc}
     */
962 963 964 965 966
    public function supportsCommentOnStatement()
    {
        return true;
    }

967
    /**
968
     * {@inheritDoc}
969 970 971 972 973
     */
    public function getName()
    {
        return 'oracle';
    }
974 975

    /**
976
     * {@inheritDoc}
977
     */
978
    protected function doModifyLimitQuery($query, $limit, $offset = null)
979
    {
980 981 982
        if ($limit === null && $offset === null) {
            return $query;
        }
983

984
        if (preg_match('/^\s*SELECT/i', $query)) {
985
            if (!preg_match('/\sFROM\s/i', $query)) {
986 987
                $query .= " FROM dual";
            }
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002

            $columns = array('a.*');

            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);
1003 1004
            }
        }
1005

1006 1007
        return $query;
    }
1008

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

Benjamin Morel's avatar
Benjamin Morel committed
1019 1020 1021
    /**
     * {@inheritDoc}
     */
1022
    public function getCreateTemporaryTableSnippetSQL()
1023 1024 1025
    {
        return "CREATE GLOBAL TEMPORARY TABLE";
    }
1026

1027 1028 1029
    /**
     * {@inheritDoc}
     */
1030
    public function getDateTimeTzFormatString()
1031 1032 1033
    {
        return 'Y-m-d H:i:sP';
    }
1034

1035 1036 1037
    /**
     * {@inheritDoc}
     */
1038 1039 1040 1041 1042
    public function getDateFormatString()
    {
        return 'Y-m-d 00:00:00';
    }

1043 1044 1045
    /**
     * {@inheritDoc}
     */
1046 1047 1048 1049
    public function getTimeFormatString()
    {
        return '1900-01-01 H:i:s';
    }
1050

1051 1052 1053
    /**
     * {@inheritDoc}
     */
1054 1055 1056 1057 1058 1059
    public function fixSchemaElementName($schemaElementName)
    {
        if (strlen($schemaElementName) > 30) {
            // Trim it
            return substr($schemaElementName, 0, 30);
        }
1060

1061 1062
        return $schemaElementName;
    }
1063

1064
    /**
1065
     * {@inheritDoc}
1066 1067 1068 1069 1070 1071
     */
    public function getMaxIdentifierLength()
    {
        return 30;
    }

1072
    /**
1073
     * {@inheritDoc}
1074 1075 1076 1077 1078
     */
    public function supportsSequences()
    {
        return true;
    }
1079

1080 1081 1082
    /**
     * {@inheritDoc}
     */
1083 1084 1085 1086
    public function supportsForeignKeyOnUpdate()
    {
        return false;
    }
1087

1088
    /**
1089
     * {@inheritDoc}
1090 1091 1092 1093 1094 1095
     */
    public function supportsReleaseSavepoints()
    {
        return false;
    }

1096
    /**
1097
     * {@inheritDoc}
1098
     */
1099
    public function getTruncateTableSQL($tableName, $cascade = false)
1100
    {
1101 1102 1103
        $tableIdentifier = new Identifier($tableName);

        return 'TRUNCATE TABLE ' . $tableIdentifier->getQuotedName($this);
1104
    }
1105 1106

    /**
1107
     * {@inheritDoc}
1108 1109 1110 1111 1112
     */
    public function getDummySelectSQL()
    {
        return 'SELECT 1 FROM DUAL';
    }
1113

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

    /**
1147
     * {@inheritDoc}
1148 1149 1150 1151 1152
     */
    public function releaseSavePoint($savepoint)
    {
        return '';
    }
1153

1154 1155 1156
    /**
     * {@inheritDoc}
     */
1157 1158
    protected function getReservedKeywordsClass()
    {
1159
        return Keywords\OracleKeywords::class;
1160
    }
1161 1162

    /**
1163
     * {@inheritDoc}
1164 1165 1166 1167 1168
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'BLOB';
    }
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178

    /**
     * {@inheritdoc}
     */
    public function quoteStringLiteral($str)
    {
        $str = str_replace('\\', '\\\\', $str); // Oracle requires backslashes to be escaped aswell.

        return parent::quoteStringLiteral($str);
    }
1179
}