OracleSchemaManager.php 13.2 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 25
use Doctrine\DBAL\Types\Type;

romanb's avatar
romanb committed
26
/**
Benjamin Morel's avatar
Benjamin Morel committed
27
 * Oracle Schema Manager.
romanb's avatar
romanb committed
28
 *
Benjamin Morel's avatar
Benjamin Morel committed
29 30 31 32
 * @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
33
 */
34
class OracleSchemaManager extends AbstractSchemaManager
35
{
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
    /**
     * {@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
64 65 66
    /**
     * {@inheritdoc}
     */
67
    protected function _getPortableViewDefinition($view)
romanb's avatar
romanb committed
68
    {
69 70
        $view = \array_change_key_case($view, CASE_LOWER);

71
        return new View($this->getQuotedIdentifierName($view['view_name']), $view['text']);
romanb's avatar
romanb committed
72 73
    }

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

81
        return [
82
            'user' => $user['username'],
83
        ];
84
    }
romanb's avatar
romanb committed
85

Benjamin Morel's avatar
Benjamin Morel committed
86 87 88
    /**
     * {@inheritdoc}
     */
89 90
    protected function _getPortableTableDefinition($table)
    {
91 92
        $table = \array_change_key_case($table, CASE_LOWER);

93
        return $this->getQuotedIdentifierName($table['table_name']);
romanb's avatar
romanb committed
94 95
    }

96
    /**
Benjamin Morel's avatar
Benjamin Morel committed
97 98
     * {@inheritdoc}
     *
99 100 101 102
     * @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
103
    {
104
        $indexBuffer = [];
Steve Müller's avatar
Steve Müller committed
105
        foreach ($tableIndexes as $tableIndex) {
106 107 108
            $tableIndex = \array_change_key_case($tableIndex, CASE_LOWER);

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

Steve Müller's avatar
Steve Müller committed
110
            if (strtolower($tableIndex['is_primary']) == "p") {
111 112 113 114 115
                $keyName = 'primary';
                $buffer['primary'] = true;
                $buffer['non_unique'] = false;
            } else {
                $buffer['primary'] = false;
Steve Müller's avatar
Steve Müller committed
116
                $buffer['non_unique'] = ($tableIndex['is_unique'] == 0) ? true : false;
117 118
            }
            $buffer['key_name'] = $keyName;
119
            $buffer['column_name'] = $this->getQuotedIdentifierName($tableIndex['column_name']);
120 121
            $indexBuffer[] = $buffer;
        }
Benjamin Morel's avatar
Benjamin Morel committed
122

123
        return parent::_getPortableTableIndexesList($indexBuffer, $tableName);
124
    }
romanb's avatar
romanb committed
125

Benjamin Morel's avatar
Benjamin Morel committed
126 127 128
    /**
     * {@inheritdoc}
     */
129 130
    protected function _getPortableTableColumnDefinition($tableColumn)
    {
131
        $tableColumn = \array_change_key_case($tableColumn, CASE_LOWER);
132

133
        $dbType = strtolower($tableColumn['data_type']);
Steve Müller's avatar
Steve Müller committed
134
        if (strpos($dbType, "timestamp(") === 0) {
135
            if (strpos($dbType, "with time zone")) {
136 137 138 139
                $dbType = "timestamptz";
            } else {
                $dbType = "timestamp";
            }
140 141
        }

Benjamin Morel's avatar
Benjamin Morel committed
142
        $unsigned = $fixed = null;
romanb's avatar
romanb committed
143

144 145 146
        if ( ! isset($tableColumn['column_name'])) {
            $tableColumn['column_name'] = '';
        }
romanb's avatar
romanb committed
147

148 149 150 151
        // Default values returned from database sometimes have trailing spaces.
        $tableColumn['data_default'] = trim($tableColumn['data_default']);

        if ($tableColumn['data_default'] === '' || $tableColumn['data_default'] === 'NULL') {
152
            $tableColumn['data_default'] = null;
romanb's avatar
romanb committed
153 154
        }

155 156
        if (null !== $tableColumn['data_default']) {
            // Default values returned from database are enclosed in single quotes.
157
            $tableColumn['data_default'] = trim($tableColumn['data_default'], "'");
158 159
        }

160 161
        $precision = null;
        $scale = null;
162 163

        $type = $this->_platform->getDoctrineTypeMapping($dbType);
164 165 166
        $type = $this->extractDoctrineTypeFromComment($tableColumn['comments'], $type);
        $tableColumn['comments'] = $this->removeDoctrineTypeFromComment($tableColumn['comments'], $type);

167
        switch ($dbType) {
168
            case 'number':
169 170 171 172 173 174 175 176 177 178 179 180 181
                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) {
182 183
                    $precision = $tableColumn['data_precision'];
                    $scale = $tableColumn['data_scale'];
184
                    $type = 'decimal';
185
                }
186 187
                $length = null;
                break;
188 189
            case 'pls_integer':
            case 'binary_integer':
190
                $length = null;
191 192 193 194
                break;
            case 'varchar':
            case 'varchar2':
            case 'nvarchar2':
195
                $length = $tableColumn['char_length'];
196
                $fixed = false;
197
                break;
198 199
            case 'char':
            case 'nchar':
200
                $length = $tableColumn['char_length'];
201
                $fixed = true;
202 203 204 205 206 207
                break;
            case 'date':
            case 'timestamp':
                $length = null;
                break;
            case 'float':
208 209
            case 'binary_float':
            case 'binary_double':
210 211
                $precision = $tableColumn['data_precision'];
                $scale = $tableColumn['data_scale'];
212
                $length = null;
213 214 215
                break;
            case 'clob':
            case 'nclob':
216
                $length = null;
217 218 219 220 221 222
                break;
            case 'blob':
            case 'raw':
            case 'long raw':
            case 'bfile':
                $length = null;
223
                break;
224 225 226 227 228
            case 'rowid':
            case 'urowid':
            default:
                $length = null;
        }
romanb's avatar
romanb committed
229

230
        $options = [
231 232 233 234 235 236 237
            'notnull'    => (bool) ($tableColumn['nullable'] === 'N'),
            'fixed'      => (bool) $fixed,
            'unsigned'   => (bool) $unsigned,
            'default'    => $tableColumn['data_default'],
            'length'     => $length,
            'precision'  => $precision,
            'scale'      => $scale,
238 239 240
            'comment'    => isset($tableColumn['comments']) && '' !== $tableColumn['comments']
                ? $tableColumn['comments']
                : null,
241
        ];
242

243
        return new Column($this->getQuotedIdentifierName($tableColumn['column_name']), Type::getType($type), $options);
244 245
    }

Benjamin Morel's avatar
Benjamin Morel committed
246 247 248
    /**
     * {@inheritdoc}
     */
249 250
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
    {
251
        $list = [];
252
        foreach ($tableForeignKeys as $value) {
253 254
            $value = \array_change_key_case($value, CASE_LOWER);
            if (!isset($list[$value['constraint_name']])) {
255 256 257 258
                if ($value['delete_rule'] == "NO ACTION") {
                    $value['delete_rule'] = null;
                }

259
                $list[$value['constraint_name']] = [
260
                    'name' => $this->getQuotedIdentifierName($value['constraint_name']),
261 262
                    'local' => [],
                    'foreign' => [],
263
                    'foreignTable' => $value['references_table'],
264
                    'onDelete' => $value['delete_rule'],
265
                ];
266
            }
267 268 269 270 271 272

            $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;
273 274
        }

275
        $result = [];
Steve Müller's avatar
Steve Müller committed
276
        foreach ($list as $constraint) {
277
            $result[] = new ForeignKeyConstraint(
278 279
                array_values($constraint['local']), $this->getQuotedIdentifierName($constraint['foreignTable']),
                array_values($constraint['foreign']), $this->getQuotedIdentifierName($constraint['name']),
280
                ['onDelete' => $constraint['onDelete']]
281 282 283 284 285 286
            );
        }

        return $result;
    }

Benjamin Morel's avatar
Benjamin Morel committed
287 288 289
    /**
     * {@inheritdoc}
     */
290 291 292
    protected function _getPortableSequenceDefinition($sequence)
    {
        $sequence = \array_change_key_case($sequence, CASE_LOWER);
Benjamin Morel's avatar
Benjamin Morel committed
293

294 295 296 297 298
        return new Sequence(
            $this->getQuotedIdentifierName($sequence['sequence_name']),
            $sequence['increment_by'],
            $sequence['min_value']
        );
romanb's avatar
romanb committed
299 300
    }

Benjamin Morel's avatar
Benjamin Morel committed
301 302 303
    /**
     * {@inheritdoc}
     */
304 305
    protected function _getPortableFunctionDefinition($function)
    {
306
        $function = \array_change_key_case($function, CASE_LOWER);
Benjamin Morel's avatar
Benjamin Morel committed
307

308 309
        return $function['name'];
    }
romanb's avatar
romanb committed
310

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

318 319
        return $database['username'];
    }
romanb's avatar
romanb committed
320

Benjamin Morel's avatar
Benjamin Morel committed
321 322 323
    /**
     * {@inheritdoc}
     */
324 325 326 327 328
    public function createDatabase($database = null)
    {
        if (is_null($database)) {
            $database = $this->_conn->getDatabase();
        }
romanb's avatar
romanb committed
329

330 331 332
        $params = $this->_conn->getParams();
        $username   = $database;
        $password   = $params['password'];
romanb's avatar
romanb committed
333

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

337
        $query = 'GRANT DBA TO ' . $username;
Benjamin Morel's avatar
Benjamin Morel committed
338
        $this->_conn->executeUpdate($query);
339 340

        return true;
romanb's avatar
romanb committed
341
    }
342

Benjamin Morel's avatar
Benjamin Morel committed
343 344 345
    /**
     * @param string $table
     *
346
     * @return bool
Benjamin Morel's avatar
Benjamin Morel committed
347
     */
348
    public function dropAutoincrement($table)
romanb's avatar
romanb committed
349
    {
350 351
        $sql = $this->_platform->getDropAutoincrementSql($table);
        foreach ($sql as $query) {
352
            $this->_conn->executeUpdate($query);
353 354 355
        }

        return true;
romanb's avatar
romanb committed
356 357
    }

Benjamin Morel's avatar
Benjamin Morel committed
358 359 360
    /**
     * {@inheritdoc}
     */
romanb's avatar
romanb committed
361 362
    public function dropTable($name)
    {
363
        $this->tryMethod('dropAutoincrement', $name);
romanb's avatar
romanb committed
364

Benjamin Morel's avatar
Benjamin Morel committed
365
        parent::dropTable($name);
romanb's avatar
romanb committed
366
    }
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385

    /**
     * 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;
    }
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409

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

410
        $activeUserSessions = $this->_conn->fetchAll($sql, [strtoupper($user)]);
411 412 413 414 415 416 417 418 419 420 421 422 423

        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#']
                )
            );
        }
    }
424
}