OracleSchemaManager.php 13.4 KB
Newer Older
romanb's avatar
romanb committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?php
/*
 * 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
Benjamin Morel's avatar
Benjamin Morel committed
17
 * <http://www.doctrine-project.org>.
romanb's avatar
romanb committed
18 19
 */

20
namespace Doctrine\DBAL\Schema;
romanb's avatar
romanb committed
21

22 23
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Driver\DriverException;
24
use Doctrine\DBAL\Types\Type;
25 26 27 28 29 30 31 32 33 34
use const CASE_LOWER;
use function array_change_key_case;
use function array_values;
use function is_null;
use function preg_match;
use function sprintf;
use function strpos;
use function strtolower;
use function strtoupper;
use function trim;
35

romanb's avatar
romanb committed
36
/**
Benjamin Morel's avatar
Benjamin Morel committed
37
 * Oracle Schema Manager.
romanb's avatar
romanb committed
38
 *
Benjamin Morel's avatar
Benjamin Morel committed
39 40 41 42
 * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
 * @author Benjamin Eberlei <kontakt@beberlei.de>
 * @since  2.0
romanb's avatar
romanb committed
43
 */
44
class OracleSchemaManager extends AbstractSchemaManager
45
{
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    /**
     * {@inheritdoc}
     */
    public function dropDatabase($database)
    {
        try {
            parent::dropDatabase($database);
        } catch (DBALException $exception) {
            $exception = $exception->getPrevious();

            if (! $exception instanceof DriverException) {
                throw $exception;
            }

            // If we have a error code 1940 (ORA-01940), the drop database operation failed
            // because of active connections on the database.
            // To force dropping the database, we first have to close all active connections
            // on that database and issue the drop database operation again.
            if ($exception->getErrorCode() !== 1940) {
                throw $exception;
            }

            $this->killUserSessions($database);

            parent::dropDatabase($database);
        }
    }

Benjamin Morel's avatar
Benjamin Morel committed
74 75 76
    /**
     * {@inheritdoc}
     */
77
    protected function _getPortableViewDefinition($view)
romanb's avatar
romanb committed
78
    {
79 80
        $view = \array_change_key_case($view, CASE_LOWER);

81
        return new View($this->getQuotedIdentifierName($view['view_name']), $view['text']);
romanb's avatar
romanb committed
82 83
    }

Benjamin Morel's avatar
Benjamin Morel committed
84 85 86
    /**
     * {@inheritdoc}
     */
87
    protected function _getPortableUserDefinition($user)
romanb's avatar
romanb committed
88
    {
89 90
        $user = \array_change_key_case($user, CASE_LOWER);

91
        return [
92
            'user' => $user['username'],
93
        ];
94
    }
romanb's avatar
romanb committed
95

Benjamin Morel's avatar
Benjamin Morel committed
96 97 98
    /**
     * {@inheritdoc}
     */
99 100
    protected function _getPortableTableDefinition($table)
    {
101 102
        $table = \array_change_key_case($table, CASE_LOWER);

103
        return $this->getQuotedIdentifierName($table['table_name']);
romanb's avatar
romanb committed
104 105
    }

106
    /**
Benjamin Morel's avatar
Benjamin Morel committed
107 108
     * {@inheritdoc}
     *
109 110 111 112
     * @license New BSD License
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
     */
    protected function _getPortableTableIndexesList($tableIndexes, $tableName=null)
romanb's avatar
romanb committed
113
    {
114
        $indexBuffer = [];
Steve Müller's avatar
Steve Müller committed
115
        foreach ($tableIndexes as $tableIndex) {
116 117 118
            $tableIndex = \array_change_key_case($tableIndex, CASE_LOWER);

            $keyName = strtolower($tableIndex['name']);
119

Steve Müller's avatar
Steve Müller committed
120
            if (strtolower($tableIndex['is_primary']) == "p") {
121 122 123 124 125
                $keyName = 'primary';
                $buffer['primary'] = true;
                $buffer['non_unique'] = false;
            } else {
                $buffer['primary'] = false;
Steve Müller's avatar
Steve Müller committed
126
                $buffer['non_unique'] = ($tableIndex['is_unique'] == 0) ? true : false;
127 128
            }
            $buffer['key_name'] = $keyName;
129
            $buffer['column_name'] = $this->getQuotedIdentifierName($tableIndex['column_name']);
130 131
            $indexBuffer[] = $buffer;
        }
Benjamin Morel's avatar
Benjamin Morel committed
132

133
        return parent::_getPortableTableIndexesList($indexBuffer, $tableName);
134
    }
romanb's avatar
romanb committed
135

Benjamin Morel's avatar
Benjamin Morel committed
136 137 138
    /**
     * {@inheritdoc}
     */
139 140
    protected function _getPortableTableColumnDefinition($tableColumn)
    {
141
        $tableColumn = \array_change_key_case($tableColumn, CASE_LOWER);
142

143
        $dbType = strtolower($tableColumn['data_type']);
Steve Müller's avatar
Steve Müller committed
144
        if (strpos($dbType, "timestamp(") === 0) {
145
            if (strpos($dbType, "with time zone")) {
146 147 148 149
                $dbType = "timestamptz";
            } else {
                $dbType = "timestamp";
            }
150 151
        }

Benjamin Morel's avatar
Benjamin Morel committed
152
        $unsigned = $fixed = null;
romanb's avatar
romanb committed
153

154 155 156
        if ( ! isset($tableColumn['column_name'])) {
            $tableColumn['column_name'] = '';
        }
romanb's avatar
romanb committed
157

158 159 160 161
        // Default values returned from database sometimes have trailing spaces.
        $tableColumn['data_default'] = trim($tableColumn['data_default']);

        if ($tableColumn['data_default'] === '' || $tableColumn['data_default'] === 'NULL') {
162
            $tableColumn['data_default'] = null;
romanb's avatar
romanb committed
163 164
        }

165 166
        if (null !== $tableColumn['data_default']) {
            // Default values returned from database are enclosed in single quotes.
167
            $tableColumn['data_default'] = trim($tableColumn['data_default'], "'");
168 169
        }

170 171
        $precision = null;
        $scale = null;
172 173

        $type = $this->_platform->getDoctrineTypeMapping($dbType);
174 175 176
        $type = $this->extractDoctrineTypeFromComment($tableColumn['comments'], $type);
        $tableColumn['comments'] = $this->removeDoctrineTypeFromComment($tableColumn['comments'], $type);

177
        switch ($dbType) {
178
            case 'number':
179 180 181 182 183 184 185 186 187 188 189 190 191
                if ($tableColumn['data_precision'] == 20 && $tableColumn['data_scale'] == 0) {
                    $precision = 20;
                    $scale = 0;
                    $type = 'bigint';
                } elseif ($tableColumn['data_precision'] == 5 && $tableColumn['data_scale'] == 0) {
                    $type = 'smallint';
                    $precision = 5;
                    $scale = 0;
                } elseif ($tableColumn['data_precision'] == 1 && $tableColumn['data_scale'] == 0) {
                    $precision = 1;
                    $scale = 0;
                    $type = 'boolean';
                } elseif ($tableColumn['data_scale'] > 0) {
192 193
                    $precision = $tableColumn['data_precision'];
                    $scale = $tableColumn['data_scale'];
194
                    $type = 'decimal';
195
                }
196 197
                $length = null;
                break;
198 199
            case 'pls_integer':
            case 'binary_integer':
200
                $length = null;
201 202 203 204
                break;
            case 'varchar':
            case 'varchar2':
            case 'nvarchar2':
205
                $length = $tableColumn['char_length'];
206
                $fixed = false;
207
                break;
208 209
            case 'char':
            case 'nchar':
210
                $length = $tableColumn['char_length'];
211
                $fixed = true;
212 213 214 215 216 217
                break;
            case 'date':
            case 'timestamp':
                $length = null;
                break;
            case 'float':
218 219
            case 'binary_float':
            case 'binary_double':
220 221
                $precision = $tableColumn['data_precision'];
                $scale = $tableColumn['data_scale'];
222
                $length = null;
223 224 225
                break;
            case 'clob':
            case 'nclob':
226
                $length = null;
227 228 229 230 231 232
                break;
            case 'blob':
            case 'raw':
            case 'long raw':
            case 'bfile':
                $length = null;
233
                break;
234 235 236 237 238
            case 'rowid':
            case 'urowid':
            default:
                $length = null;
        }
romanb's avatar
romanb committed
239

240
        $options = [
241 242 243 244 245 246 247
            'notnull'    => (bool) ($tableColumn['nullable'] === 'N'),
            'fixed'      => (bool) $fixed,
            'unsigned'   => (bool) $unsigned,
            'default'    => $tableColumn['data_default'],
            'length'     => $length,
            'precision'  => $precision,
            'scale'      => $scale,
248 249 250
            'comment'    => isset($tableColumn['comments']) && '' !== $tableColumn['comments']
                ? $tableColumn['comments']
                : null,
251
        ];
252

253
        return new Column($this->getQuotedIdentifierName($tableColumn['column_name']), Type::getType($type), $options);
254 255
    }

Benjamin Morel's avatar
Benjamin Morel committed
256 257 258
    /**
     * {@inheritdoc}
     */
259 260
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
    {
261
        $list = [];
262
        foreach ($tableForeignKeys as $value) {
263 264
            $value = \array_change_key_case($value, CASE_LOWER);
            if (!isset($list[$value['constraint_name']])) {
265 266 267 268
                if ($value['delete_rule'] == "NO ACTION") {
                    $value['delete_rule'] = null;
                }

269
                $list[$value['constraint_name']] = [
270
                    'name' => $this->getQuotedIdentifierName($value['constraint_name']),
271 272
                    'local' => [],
                    'foreign' => [],
273
                    'foreignTable' => $value['references_table'],
274
                    'onDelete' => $value['delete_rule'],
275
                ];
276
            }
277 278 279 280 281 282

            $localColumn = $this->getQuotedIdentifierName($value['local_column']);
            $foreignColumn = $this->getQuotedIdentifierName($value['foreign_column']);

            $list[$value['constraint_name']]['local'][$value['position']] = $localColumn;
            $list[$value['constraint_name']]['foreign'][$value['position']] = $foreignColumn;
283 284
        }

285
        $result = [];
Steve Müller's avatar
Steve Müller committed
286
        foreach ($list as $constraint) {
287
            $result[] = new ForeignKeyConstraint(
288 289
                array_values($constraint['local']), $this->getQuotedIdentifierName($constraint['foreignTable']),
                array_values($constraint['foreign']), $this->getQuotedIdentifierName($constraint['name']),
290
                ['onDelete' => $constraint['onDelete']]
291 292 293 294 295 296
            );
        }

        return $result;
    }

Benjamin Morel's avatar
Benjamin Morel committed
297 298 299
    /**
     * {@inheritdoc}
     */
300 301 302
    protected function _getPortableSequenceDefinition($sequence)
    {
        $sequence = \array_change_key_case($sequence, CASE_LOWER);
Benjamin Morel's avatar
Benjamin Morel committed
303

304 305
        return new Sequence(
            $this->getQuotedIdentifierName($sequence['sequence_name']),
306 307
            (int) $sequence['increment_by'],
            (int) $sequence['min_value']
308
        );
romanb's avatar
romanb committed
309 310
    }

Benjamin Morel's avatar
Benjamin Morel committed
311 312 313
    /**
     * {@inheritdoc}
     */
314 315
    protected function _getPortableFunctionDefinition($function)
    {
316
        $function = \array_change_key_case($function, CASE_LOWER);
Benjamin Morel's avatar
Benjamin Morel committed
317

318 319
        return $function['name'];
    }
romanb's avatar
romanb committed
320

Benjamin Morel's avatar
Benjamin Morel committed
321 322 323
    /**
     * {@inheritdoc}
     */
324 325
    protected function _getPortableDatabaseDefinition($database)
    {
326
        $database = \array_change_key_case($database, CASE_LOWER);
Benjamin Morel's avatar
Benjamin Morel committed
327

328 329
        return $database['username'];
    }
romanb's avatar
romanb committed
330

Benjamin Morel's avatar
Benjamin Morel committed
331 332 333
    /**
     * {@inheritdoc}
     */
334 335 336 337 338
    public function createDatabase($database = null)
    {
        if (is_null($database)) {
            $database = $this->_conn->getDatabase();
        }
romanb's avatar
romanb committed
339

340 341 342
        $params = $this->_conn->getParams();
        $username   = $database;
        $password   = $params['password'];
romanb's avatar
romanb committed
343

344
        $query  = 'CREATE USER ' . $username . ' IDENTIFIED BY ' . $password;
Benjamin Morel's avatar
Benjamin Morel committed
345
        $this->_conn->executeUpdate($query);
346

347
        $query = 'GRANT DBA TO ' . $username;
Benjamin Morel's avatar
Benjamin Morel committed
348
        $this->_conn->executeUpdate($query);
349 350

        return true;
romanb's avatar
romanb committed
351
    }
352

Benjamin Morel's avatar
Benjamin Morel committed
353 354 355
    /**
     * @param string $table
     *
356
     * @return bool
Benjamin Morel's avatar
Benjamin Morel committed
357
     */
358
    public function dropAutoincrement($table)
romanb's avatar
romanb committed
359
    {
360 361
        $sql = $this->_platform->getDropAutoincrementSql($table);
        foreach ($sql as $query) {
362
            $this->_conn->executeUpdate($query);
363 364 365
        }

        return true;
romanb's avatar
romanb committed
366 367
    }

Benjamin Morel's avatar
Benjamin Morel committed
368 369 370
    /**
     * {@inheritdoc}
     */
romanb's avatar
romanb committed
371 372
    public function dropTable($name)
    {
373
        $this->tryMethod('dropAutoincrement', $name);
romanb's avatar
romanb committed
374

Benjamin Morel's avatar
Benjamin Morel committed
375
        parent::dropTable($name);
romanb's avatar
romanb committed
376
    }
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395

    /**
     * Returns the quoted representation of the given identifier name.
     *
     * Quotes non-uppercase identifiers explicitly to preserve case
     * and thus make references to the particular identifier work.
     *
     * @param string $identifier The identifier to quote.
     *
     * @return string The quoted identifier.
     */
    private function getQuotedIdentifierName($identifier)
    {
        if (preg_match('/[a-z]/', $identifier)) {
            return $this->_platform->quoteIdentifier($identifier);
        }

        return $identifier;
    }
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419

    /**
     * Kills sessions connected with the given user.
     *
     * This is useful to force DROP USER operations which could fail because of active user sessions.
     *
     * @param string $user The name of the user to kill sessions for.
     *
     * @return void
     */
    private function killUserSessions($user)
    {
        $sql = <<<SQL
SELECT
    s.sid,
    s.serial#
FROM
    gv\$session s,
    gv\$process p
WHERE
    s.username = ?
    AND p.addr(+) = s.paddr
SQL;

420
        $activeUserSessions = $this->_conn->fetchAll($sql, [strtoupper($user)]);
421 422 423 424 425 426 427 428 429 430 431 432 433

        foreach ($activeUserSessions as $activeUserSession) {
            $activeUserSession = array_change_key_case($activeUserSession, \CASE_LOWER);

            $this->_execSql(
                sprintf(
                    "ALTER SYSTEM KILL SESSION '%s, %s' IMMEDIATE",
                    $activeUserSession['sid'],
                    $activeUserSession['serial#']
                )
            );
        }
    }
434
}