OraclePlatform.php 15.9 KB
Newer Older
1
<?php
romanb's avatar
romanb committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 *  $Id$
 *
 * 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
 * and is licensed under the LGPL. For more information, see
19
 * <http://www.doctrine-project.org>.
romanb's avatar
romanb committed
20
 */
21

22
namespace Doctrine\DBAL\Platforms;
23

romanb's avatar
romanb committed
24
/**
25
 * OraclePlatform.
romanb's avatar
romanb committed
26 27 28 29 30
 *
 * @since 2.0
 * @author Roman Borschel <roman@code-factory.org>
 * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
 */
31
class OraclePlatform extends AbstractPlatform
32 33 34 35 36 37 38 39
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        parent::__construct();
    }
40

41 42 43 44 45 46 47 48 49 50 51 52 53
    /**
     * return string to call a function to get a substring inside an SQL statement
     *
     * Note: Not SQL92, but common functionality.
     *
     * @param string $value         an sql string literal or column name/alias
     * @param integer $position     where to start the substring portion
     * @param integer $length       the substring portion length
     * @return string               SQL substring function with given parameters
     * @override
     */
    public function getSubstringExpression($value, $position, $length = null)
    {
54
        if ($length !== null) {
55
            return "SUBSTR($value, $position, $length)";
56
        }
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102

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

    /**
     * Return string to call a variable with the current timestamp inside an SQL statement
     * There are three special variables for current date and time:
     * - CURRENT_TIMESTAMP (date and time, TIMESTAMP type)
     * - CURRENT_DATE (date, DATE type)
     * - CURRENT_TIME (time, TIME type)
     *
     * @return string to call a variable with the current timestamp
     * @override
     */
    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\')';
        }
    }

    /**
     * random
     *
     * @return string           an oracle SQL string that generates a float between 0 and 1
     * @override
     */
    public function getRandomExpression()
    {
        return 'dbms_random.value';
    }

    /**
     * Returns global unique identifier
     *
     * @return string to get global unique identifier
     * @override
     */
    public function getGuidExpression()
    {
        return 'SYS_GUID()';
    }
103 104 105 106 107 108 109 110 111 112
    
    /**
     * Gets the SQL used to create a sequence that starts with a given value
     * and increments by the given allocation size.
     *
     * @param string $sequenceName
     * @param integer $start
     * @param integer $allocationSize
     * @return string The SQL.
     */
113 114
    public function getCreateSequenceSql($sequenceName, $start = 1, $allocationSize = 1)
    {
115
        return 'CREATE SEQUENCE ' . $sequenceName 
116
                . ' START WITH ' . $start . ' INCREMENT BY ' . $allocationSize; 
117
    }
118

romanb's avatar
romanb committed
119
    /**
120
     * {@inheritdoc}
romanb's avatar
romanb committed
121
     *
122
     * @param string $sequenceName
romanb's avatar
romanb committed
123 124 125 126
     * @override
     */
    public function getSequenceNextValSql($sequenceName)
    {
127
        return 'SELECT ' . $sequenceName . '.nextval FROM DUAL';
romanb's avatar
romanb committed
128
    }
romanb's avatar
romanb committed
129 130
    
    /**
131
     * {@inheritdoc}
romanb's avatar
romanb committed
132
     *
133
     * @param integer $level
romanb's avatar
romanb committed
134 135 136 137
     * @override
     */
    public function getSetTransactionIsolationSql($level)
    {
138
        return 'SET TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSql($level);
romanb's avatar
romanb committed
139
    }
140

romanb's avatar
romanb committed
141 142 143
    protected function _getTransactionIsolationLevelSql($level)
    {
        switch ($level) {
144 145 146
            case \Doctrine\DBAL\Connection::TRANSACTION_READ_UNCOMMITTED:
                return 'READ UNCOMMITTED';
            case \Doctrine\DBAL\Connection::TRANSACTION_READ_COMMITTED:
147
                return 'READ COMMITTED';
148 149
            case \Doctrine\DBAL\Connection::TRANSACTION_REPEATABLE_READ:
            case \Doctrine\DBAL\Connection::TRANSACTION_SERIALIZABLE:
romanb's avatar
romanb committed
150 151 152 153 154
                return 'SERIALIZABLE';
            default:
                return parent::_getTransactionIsolationLevelSql($level);
        }
    }
155

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    /**
     * @override
     */
    public function getIntegerTypeDeclarationSql(array $field)
    {
        return 'NUMBER(10)';
    }

    /**
     * @override
     */
    public function getBigIntTypeDeclarationSql(array $field)
    {
        return 'NUMBER(20)';
    }

    /**
     * @override
     */
    public function getSmallIntTypeDeclarationSql(array $field)
    {
        return 'NUMBER(5)';
    }

180 181 182 183 184
    /**
     * @override
     */
    public function getDateTimeTypeDeclarationSql(array $fieldDeclaration)
    {
185
        return 'TIMESTAMP(0) WITH TIME ZONE';
186 187
    }

188 189 190 191 192 193 194 195
    /**
     * @override
     */
    public function getBooleanTypeDeclarationSql(array $field)
    {
        return 'NUMBER(1)';
    }

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
    /**
     * @override
     */
    protected function _getCommonIntegerTypeDeclarationSql(array $columnDef)
    {
        return '';
    }

    /**
     * Gets the SQL snippet used to declare a VARCHAR column on the Oracle platform.
     *
     * @params array $field
     * @override
     */
    public function getVarcharTypeDeclarationSql(array $field)
    {
        if ( ! isset($field['length'])) {
            if (array_key_exists('default', $field)) {
                $field['length'] = $this->getVarcharMaxLength();
            } else {
                $field['length'] = false;
            }
        }

        $length = ($field['length'] <= $this->getVarcharMaxLength()) ? $field['length'] : false;
        $fixed = (isset($field['fixed'])) ? $field['fixed'] : false;

        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(2000)')
                : ($length ? 'VARCHAR2(' . $length . ')' : 'VARCHAR2(4000)');
    }

227 228 229 230 231 232 233 234 235 236
    public function getListDatabasesSql()
    {
        return 'SELECT username FROM sys.dba_users';
    }

    public function getListFunctionsSql()
    {
        return "SELECT name FROM sys.user_source WHERE line = 1 AND type = 'FUNCTION'";
    }

jwage's avatar
jwage committed
237 238 239 240 241
    public function getListSequencesSql($database)
    {
        return 'SELECT sequence_name FROM sys.user_sequences';
    }

242 243
    public function getCreateTableSql($table, array $columns, array $options = array())
    {
244
        $indexes = isset($options['indexes']) ? $options['indexes'] : array();
245 246 247 248 249
        $options['indexes'] = array();
        $sql = parent::getCreateTableSql($table, $columns, $options);

        foreach ($columns as $name => $column) {
            if (isset($column['sequence'])) {
250
                $sql[] = $this->getCreateSequenceSql($column['sequence'], 1);
251 252 253 254 255 256 257 258 259 260
            }

            if (isset($column['autoincrement']) && $column['autoincrement'] ||
               (isset($column['autoinc']) && $column['autoinc'])) {           
                $sql = array_merge($sql, $this->getCreateAutoincrementSql($name, $table));
            }
        }
        
        if (isset($indexes) && ! empty($indexes)) {
            foreach ($indexes as $indexName => $definition) {
261
                // create nonunique indexes, as they are a part of CREATE TABLE DDL
262
                if ( ! isset($definition['type']) || 
263
                        (isset($definition['type']) && strtolower($definition['type']) != 'unique')) {
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
                    $sql[] = $this->getCreateIndexSql($table, $indexName, $definition);
                }
            }
        }

        return $sql;
    }

    public function getListTableIndexesSql($table)
    {
        return "SELECT * FROM user_indexes"
               . " WHERE table_name = '" . strtoupper($table) . "'";
    }

    public function getListTablesSql()
    {
        return 'SELECT * FROM sys.user_tables';
    }

    public function getListUsersSql()
    {
        return 'SELECT * FROM sys.dba_users';
    }

    public function getListViewsSql()
    {
        return 'SELECT view_name FROM sys.user_views';
    }

    public function getCreateViewSql($name, $sql)
    {
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
    }

    public function getDropViewSql($name)
    {
        return 'DROP VIEW '. $name;
    }

    public function getCreateAutoincrementSql($name, $table, $start = 1)
    {
        $table = strtoupper($table);
        $sql   = array();

        $indexName  = $table . '_AI_PK';
        $definition = array(
            'primary' => true,
            'fields' => array($name => true),
        );

        $sql[] = 'DECLARE
  constraints_Count NUMBER;
BEGIN
  SELECT COUNT(CONSTRAINT_NAME) INTO constraints_Count FROM USER_CONSTRAINTS WHERE TABLE_NAME = \''.$table.'\' AND CONSTRAINT_TYPE = \'P\';
  IF constraints_Count = 0 OR constraints_Count = \'\' THEN
    EXECUTE IMMEDIATE \''.$this->getCreateConstraintSql($table, $indexName, $definition).'\';
  END IF;
END;';   

        $sequenceName = $table . '_SEQ';
        $sql[] = $this->getCreateSequenceSql($sequenceName, $start);

326
        $triggerName  = $table . '_AI_PK';
327 328 329 330 331 332 333 334
        $sql[] = 'CREATE TRIGGER ' . $triggerName . '
   BEFORE INSERT
   ON ' . $table . '
   FOR EACH ROW
DECLARE
   last_Sequence NUMBER;
   last_InsertID NUMBER;
BEGIN
335
   SELECT ' . $sequenceName . '.NEXTVAL INTO :NEW.' . $name . ' FROM DUAL;
336
   IF (:NEW.' . $name . ' IS NULL OR :NEW.'.$name.' = 0) THEN
337
      SELECT ' . $sequenceName . '.NEXTVAL INTO :NEW.' . $name . ' FROM DUAL;
338 339 340 341 342 343
   ELSE
      SELECT NVL(Last_Number, 0) INTO last_Sequence
        FROM User_Sequences
       WHERE Sequence_Name = \'' . $sequenceName . '\';
      SELECT :NEW.' . $name . ' INTO last_InsertID FROM DUAL;
      WHILE (last_InsertID > last_Sequence) LOOP
344
         SELECT ' . $sequenceName . '.NEXTVAL INTO last_Sequence FROM DUAL;
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
      END LOOP;
   END IF;
END;';
        return $sql;
    }

    public function getDropAutoincrementSql($table)
    {
        $table = strtoupper($table);
        $trigger = $table . '_AI_PK';

        if ($trigger) {
            $sql[] = 'DROP TRIGGER ' . $trigger;
            $sql[] = $this->getDropSequenceSql($table.'_SEQ');

            $indexName = $table . '_AI_PK';
            $sql[] = $this->getDropConstraintSql($table, $indexName);
        }

        return $sql;
    }

    public function getListTableConstraintsSql($table)
    {
        $table = strtoupper($table);
        return 'SELECT * FROM user_constraints WHERE table_name = \'' . $table . '\'';
    }

    public function getListTableColumnsSql($table)
    {
        $table = strtoupper($table);
        return "SELECT * FROM all_tab_columns WHERE table_name = '" . $table . "' ORDER BY column_name";
    }

    public function getDropSequenceSql($sequenceName)
    {
381
        return 'DROP SEQUENCE ' . $sequenceName;
382 383 384 385 386 387 388 389 390 391
    }

    public function getDropDatabaseSql($database)
    {
        return 'DROP USER ' . $database . ' CASCADE';
    }

    public function getAlterTableSql($name, array $changes, $check = false)
    {
        if ( ! $name) {
392
            throw DoctrineException::missingTableName();
393 394 395 396 397 398 399 400 401 402
        }
        foreach ($changes as $changeName => $change) {
            switch ($changeName) {
                case 'add':
                case 'remove':
                case 'change':
                case 'name':
                case 'rename':
                    break;
                default:
403
                    throw \Doctrine\Common\DoctrineException::alterTableChangeNotSupported($changeName);
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
            }
        }

        if ($check) {
            return false;
        }

        if ( ! empty($changes['add']) && is_array($changes['add'])) {
            $fields = array();
            foreach ($changes['add'] as $fieldName => $field) {
                $fields[] = $this->getColumnDeclarationSql($fieldName, $field);
            }
            $sql[] = 'ALTER TABLE ' . $name . ' ADD (' . implode(', ', $fields) . ')';
        }

        if ( ! empty($changes['change']) && is_array($changes['change'])) {
            $fields = array();
            foreach ($changes['change'] as $fieldName => $field) {
                $fields[] = $fieldName. ' ' . $this->getColumnDeclarationSql('', $field['definition']);
            }
            $sql[] = 'ALTER TABLE ' . $name . ' MODIFY (' . implode(', ', $fields) . ')';
        }

        if ( ! empty($changes['rename']) && is_array($changes['rename'])) {
            foreach ($changes['rename'] as $fieldName => $field) {
429 430
                $sql[] = 'ALTER TABLE ' . $name . ' RENAME COLUMN ' . $fieldName
                       . ' TO ' . $field['name'];
431 432 433 434 435 436
            }
        }

        if ( ! empty($changes['remove']) && is_array($changes['remove'])) {
            $fields = array();
            foreach ($changes['remove'] as $fieldName => $field) {
437
                $fields[] = $fieldName;
438 439 440 441 442
            }
            $sql[] = 'ALTER TABLE ' . $name . ' DROP COLUMN ' . implode(', ', $fields);
        }

        if ( ! empty($changes['name'])) {
443
            $changeName = $changes['name'];
444 445 446 447 448 449
            $sql[] = 'ALTER TABLE ' . $name . ' RENAME TO ' . $changeName;
        }

        return $sql;
    }

450 451 452 453 454 455 456 457 458
    /**
     * Whether the platform prefers sequences for ID generation.
     *
     * @return boolean
     */
    public function prefersSequences()
    {
        return true;
    }
459 460 461 462 463 464 465 466 467 468

    /**
     * Get the platform name for this instance
     *
     * @return string
     */
    public function getName()
    {
        return 'oracle';
    }
469 470 471 472 473 474 475 476 477

    /**
     * Adds an driver-specific LIMIT clause to the query
     *
     * @param string $query         query to modify
     * @param integer $limit        limit the number of rows
     * @param integer $offset       start reading from given offset
     * @return string               the modified query
     */
478
    public function modifyLimitQuery($query, $limit, $offset = null)
479 480 481 482 483 484 485 486 487
    {
        $limit = (int) $limit;
        $offset = (int) $offset;
        if (preg_match('/^\s*SELECT/i', $query)) {
            if ( ! preg_match('/\sFROM\s/i', $query)) {
                $query .= " FROM dual";
            }
            if ($limit > 0) {
                $max = $offset + $limit;
488
                $column = '*';
489 490 491 492 493 494 495 496 497 498 499 500 501 502
                if ($offset > 0) {
                    $min = $offset + 1;
                    $query = 'SELECT b.'.$column.' FROM ('.
                                 'SELECT a.*, ROWNUM AS doctrine_rownum FROM ('
                                   . $query . ') a '.
                              ') b '.
                              'WHERE doctrine_rownum BETWEEN ' . $min .  ' AND ' . $max;
                } else {
                    $query = 'SELECT a.'.$column.' FROM (' . $query .') a WHERE ROWNUM <= ' . $max;
                }
            }
        }
        return $query;
    }
503
    
504 505 506 507 508 509 510 511
    /**
     * Gets the character casing of a column in an SQL result set of this platform.
     * 
     * Oracle returns all column names in SQL result sets in uppercase.
     * 
     * @param string $column The column name for which to get the correct character casing.
     * @return string The column name in the character casing used in SQL result sets.
     */
512 513 514 515
    public function getSqlResultCasing($column)
    {
        return strtoupper($column);
    }
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    
    public function getCreateTemporaryTableSnippetSql()
    {
        return "CREATE GLOBAL TEMPORARY TABLE";
    }
    
    public function getDateTimeFormatString()
    {
        return 'Y-m-d H:i:sP';
    }
    
    public function fixSchemaElementName($schemaElementName)
    {
        if (strlen($schemaElementName) > 30) {
            // Trim it
            return substr($schemaElementName, 0, 30);
        }
        return $schemaElementName;
    }
535
}