OracleSchemaManager.php 12 KB
Newer Older
romanb's avatar
romanb committed
1 2
<?php

3
namespace Doctrine\DBAL\Schema;
romanb's avatar
romanb committed
4

5 6
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Driver\DriverException;
7
use Doctrine\DBAL\Platforms\OraclePlatform;
8
use Doctrine\DBAL\Types\Type;
Sergei Morozov's avatar
Sergei Morozov committed
9
use Throwable;
10 11 12
use const CASE_LOWER;
use function array_change_key_case;
use function array_values;
13
use function assert;
14 15
use function preg_match;
use function sprintf;
16
use function str_replace;
17 18 19 20
use function strpos;
use function strtolower;
use function strtoupper;
use function trim;
21

romanb's avatar
romanb committed
22
/**
Benjamin Morel's avatar
Benjamin Morel committed
23
 * Oracle Schema Manager.
romanb's avatar
romanb committed
24
 */
25
class OracleSchemaManager extends AbstractSchemaManager
26
{
27 28 29 30 31 32 33 34 35
    /**
     * {@inheritdoc}
     */
    public function dropDatabase($database)
    {
        try {
            parent::dropDatabase($database);
        } catch (DBALException $exception) {
            $exception = $exception->getPrevious();
Sergei Morozov's avatar
Sergei Morozov committed
36
            assert($exception instanceof Throwable);
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

            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
56 57 58
    /**
     * {@inheritdoc}
     */
59
    protected function _getPortableViewDefinition($view)
romanb's avatar
romanb committed
60
    {
61
        $view = array_change_key_case($view, CASE_LOWER);
62

63
        return new View($this->getQuotedIdentifierName($view['view_name']), $view['text']);
romanb's avatar
romanb committed
64 65
    }

Benjamin Morel's avatar
Benjamin Morel committed
66 67 68
    /**
     * {@inheritdoc}
     */
69
    protected function _getPortableUserDefinition($user)
romanb's avatar
romanb committed
70
    {
71
        $user = array_change_key_case($user, CASE_LOWER);
72

73
        return [
74
            'user' => $user['username'],
75
        ];
76
    }
romanb's avatar
romanb committed
77

Benjamin Morel's avatar
Benjamin Morel committed
78 79 80
    /**
     * {@inheritdoc}
     */
81 82
    protected function _getPortableTableDefinition($table)
    {
83
        $table = array_change_key_case($table, CASE_LOWER);
84

85
        return $this->getQuotedIdentifierName($table['table_name']);
romanb's avatar
romanb committed
86 87
    }

88
    /**
Benjamin Morel's avatar
Benjamin Morel committed
89 90
     * {@inheritdoc}
     *
91 92
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
     */
93
    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
romanb's avatar
romanb committed
94
    {
95
        $indexBuffer = [];
Steve Müller's avatar
Steve Müller committed
96
        foreach ($tableIndexes as $tableIndex) {
97
            $tableIndex = array_change_key_case($tableIndex, CASE_LOWER);
98 99

            $keyName = strtolower($tableIndex['name']);
100
            $buffer  = [];
101

102 103 104
            if (strtolower($tableIndex['is_primary']) === 'p') {
                $keyName              = 'primary';
                $buffer['primary']    = true;
105 106
                $buffer['non_unique'] = false;
            } else {
107
                $buffer['primary']    = false;
108
                $buffer['non_unique'] = ! $tableIndex['is_unique'];
109
            }
110
            $buffer['key_name']    = $keyName;
111
            $buffer['column_name'] = $this->getQuotedIdentifierName($tableIndex['column_name']);
112
            $indexBuffer[]         = $buffer;
113
        }
Benjamin Morel's avatar
Benjamin Morel committed
114

115
        return parent::_getPortableTableIndexesList($indexBuffer, $tableName);
116
    }
romanb's avatar
romanb committed
117

Benjamin Morel's avatar
Benjamin Morel committed
118 119 120
    /**
     * {@inheritdoc}
     */
121 122
    protected function _getPortableTableColumnDefinition($tableColumn)
    {
123
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
124

125
        $dbType = strtolower($tableColumn['data_type']);
126 127 128
        if (strpos($dbType, 'timestamp(') === 0) {
            if (strpos($dbType, 'with time zone')) {
                $dbType = 'timestamptz';
129
            } else {
130
                $dbType = 'timestamp';
131
            }
132 133
        }

134
        $unsigned = $fixed = $precision = $scale = $length = null;
romanb's avatar
romanb committed
135

136
        if (! isset($tableColumn['column_name'])) {
137 138
            $tableColumn['column_name'] = '';
        }
romanb's avatar
romanb committed
139

140 141 142 143
        // Default values returned from database sometimes have trailing spaces.
        $tableColumn['data_default'] = trim($tableColumn['data_default']);

        if ($tableColumn['data_default'] === '' || $tableColumn['data_default'] === 'NULL') {
144
            $tableColumn['data_default'] = null;
romanb's avatar
romanb committed
145 146
        }

147
        if ($tableColumn['data_default'] !== null) {
148 149 150 151
            // Default values returned from database are represented as literal expressions
            if (preg_match('/^\'(.*)\'$/s', $tableColumn['data_default'], $matches)) {
                $tableColumn['data_default'] = str_replace("''", "'", $matches[1]);
            }
152 153
        }

154 155 156 157 158 159 160
        if ($tableColumn['data_precision'] !== null) {
            $precision = (int) $tableColumn['data_precision'];
        }

        if ($tableColumn['data_scale'] !== null) {
            $scale = (int) $tableColumn['data_scale'];
        }
161

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

166
        switch ($dbType) {
167
            case 'number':
168 169 170 171 172 173 174 175
                if ($precision === 20 && $scale === 0) {
                    $type = 'bigint';
                } elseif ($precision === 5 && $scale === 0) {
                    $type = 'smallint';
                } elseif ($precision === 1 && $scale === 0) {
                    $type = 'boolean';
                } elseif ($scale > 0) {
                    $type = 'decimal';
176
                }
177

178 179 180 181
                break;
            case 'varchar':
            case 'varchar2':
            case 'nvarchar2':
182
                $length = $tableColumn['char_length'];
183
                $fixed  = false;
184
                break;
185 186
            case 'char':
            case 'nchar':
187
                $length = $tableColumn['char_length'];
188
                $fixed  = true;
189 190
                break;
        }
romanb's avatar
romanb committed
191

192
        $options = [
193 194 195 196 197 198 199
            'notnull'    => (bool) ($tableColumn['nullable'] === 'N'),
            'fixed'      => (bool) $fixed,
            'unsigned'   => (bool) $unsigned,
            'default'    => $tableColumn['data_default'],
            'length'     => $length,
            'precision'  => $precision,
            'scale'      => $scale,
200
            'comment'    => isset($tableColumn['comments']) && $tableColumn['comments'] !== ''
201 202
                ? $tableColumn['comments']
                : null,
203
        ];
204

205
        return new Column($this->getQuotedIdentifierName($tableColumn['column_name']), Type::getType($type), $options);
206 207
    }

Benjamin Morel's avatar
Benjamin Morel committed
208 209 210
    /**
     * {@inheritdoc}
     */
211 212
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
    {
213
        $list = [];
214
        foreach ($tableForeignKeys as $value) {
215 216 217
            $value = array_change_key_case($value, CASE_LOWER);
            if (! isset($list[$value['constraint_name']])) {
                if ($value['delete_rule'] === 'NO ACTION') {
218 219 220
                    $value['delete_rule'] = null;
                }

221
                $list[$value['constraint_name']] = [
222
                    'name' => $this->getQuotedIdentifierName($value['constraint_name']),
223 224
                    'local' => [],
                    'foreign' => [],
225
                    'foreignTable' => $value['references_table'],
226
                    'onDelete' => $value['delete_rule'],
227
                ];
228
            }
229

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

233
            $list[$value['constraint_name']]['local'][$value['position']]   = $localColumn;
234
            $list[$value['constraint_name']]['foreign'][$value['position']] = $foreignColumn;
235 236
        }

237
        $result = [];
Steve Müller's avatar
Steve Müller committed
238
        foreach ($list as $constraint) {
239
            $result[] = new ForeignKeyConstraint(
240 241 242 243
                array_values($constraint['local']),
                $this->getQuotedIdentifierName($constraint['foreignTable']),
                array_values($constraint['foreign']),
                $this->getQuotedIdentifierName($constraint['name']),
244
                ['onDelete' => $constraint['onDelete']]
245 246 247 248 249 250
            );
        }

        return $result;
    }

Benjamin Morel's avatar
Benjamin Morel committed
251 252 253
    /**
     * {@inheritdoc}
     */
254 255
    protected function _getPortableSequenceDefinition($sequence)
    {
256
        $sequence = array_change_key_case($sequence, CASE_LOWER);
Benjamin Morel's avatar
Benjamin Morel committed
257

258 259
        return new Sequence(
            $this->getQuotedIdentifierName($sequence['sequence_name']),
260 261
            (int) $sequence['increment_by'],
            (int) $sequence['min_value']
262
        );
romanb's avatar
romanb committed
263 264
    }

Benjamin Morel's avatar
Benjamin Morel committed
265 266 267
    /**
     * {@inheritdoc}
     */
268 269
    protected function _getPortableFunctionDefinition($function)
    {
270
        $function = array_change_key_case($function, CASE_LOWER);
Benjamin Morel's avatar
Benjamin Morel committed
271

272 273
        return $function['name'];
    }
romanb's avatar
romanb committed
274

Benjamin Morel's avatar
Benjamin Morel committed
275 276 277
    /**
     * {@inheritdoc}
     */
278 279
    protected function _getPortableDatabaseDefinition($database)
    {
280
        $database = array_change_key_case($database, CASE_LOWER);
Benjamin Morel's avatar
Benjamin Morel committed
281

282 283
        return $database['username'];
    }
romanb's avatar
romanb committed
284

Benjamin Morel's avatar
Benjamin Morel committed
285 286 287
    /**
     * {@inheritdoc}
     */
288 289
    public function createDatabase($database = null)
    {
290
        if ($database === null) {
291 292
            $database = $this->_conn->getDatabase();
        }
romanb's avatar
romanb committed
293

294 295 296
        $params   = $this->_conn->getParams();
        $username = $database;
        $password = $params['password'];
romanb's avatar
romanb committed
297

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

301
        $query = 'GRANT DBA TO ' . $username;
Benjamin Morel's avatar
Benjamin Morel committed
302
        $this->_conn->executeUpdate($query);
romanb's avatar
romanb committed
303
    }
304

Benjamin Morel's avatar
Benjamin Morel committed
305 306 307
    /**
     * @param string $table
     *
308
     * @return bool
Benjamin Morel's avatar
Benjamin Morel committed
309
     */
310
    public function dropAutoincrement($table)
romanb's avatar
romanb committed
311
    {
312 313
        assert($this->_platform instanceof OraclePlatform);

314 315
        $sql = $this->_platform->getDropAutoincrementSql($table);
        foreach ($sql as $query) {
316
            $this->_conn->executeUpdate($query);
317 318 319
        }

        return true;
romanb's avatar
romanb committed
320 321
    }

Benjamin Morel's avatar
Benjamin Morel committed
322 323 324
    /**
     * {@inheritdoc}
     */
romanb's avatar
romanb committed
325 326
    public function dropTable($name)
    {
327
        $this->tryMethod('dropAutoincrement', $name);
romanb's avatar
romanb committed
328

Benjamin Morel's avatar
Benjamin Morel committed
329
        parent::dropTable($name);
romanb's avatar
romanb committed
330
    }
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349

    /**
     * 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;
    }
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373

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

374
        $activeUserSessions = $this->_conn->fetchAll($sql, [strtoupper($user)]);
375 376

        foreach ($activeUserSessions as $activeUserSession) {
377
            $activeUserSession = array_change_key_case($activeUserSession, CASE_LOWER);
378 379 380 381 382 383 384 385 386 387

            $this->_execSql(
                sprintf(
                    "ALTER SYSTEM KILL SESSION '%s, %s' IMMEDIATE",
                    $activeUserSession['sid'],
                    $activeUserSession['serial#']
                )
            );
        }
    }
388 389 390 391 392 393 394 395 396 397 398 399 400 401

    public function listTableDetails($tableName) : Table
    {
        $table = parent::listTableDetails($tableName);

        /** @var OraclePlatform $platform */
        $platform = $this->_platform;
        $sql      = $platform->getListTableCommentsSQL($tableName);

        $tableOptions = $this->_conn->fetchAssoc($sql);
        $table->addOption('comment', $tableOptions['COMMENTS']);

        return $table;
    }
402
}