OracleSchemaManager.php 12.2 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
use function array_change_key_case;
use function array_values;
12
use function assert;
13 14
use function preg_match;
use function sprintf;
15
use function str_replace;
16 17 18 19
use function strpos;
use function strtolower;
use function strtoupper;
use function trim;
Grégoire Paris's avatar
Grégoire Paris committed
20
use const CASE_LOWER;
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
            }
Grégoire Paris's avatar
Grégoire Paris committed
110

111
            $buffer['key_name']    = $keyName;
112
            $buffer['column_name'] = $this->getQuotedIdentifierName($tableIndex['column_name']);
113
            $indexBuffer[]         = $buffer;
114
        }
Benjamin Morel's avatar
Benjamin Morel committed
115

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

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

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

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

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

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

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

148
        if ($tableColumn['data_default'] !== null) {
149 150 151 152
            // 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]);
            }
153 154
        }

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

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

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

167
        switch ($dbType) {
168
            case 'number':
169 170 171 172 173 174 175 176
                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';
177
                }
178

179
                break;
Sergei Morozov's avatar
Sergei Morozov committed
180

181 182 183
            case 'varchar':
            case 'varchar2':
            case 'nvarchar2':
184
                $length = $tableColumn['char_length'];
185
                $fixed  = false;
186
                break;
Sergei Morozov's avatar
Sergei Morozov committed
187

188 189
            case 'char':
            case 'nchar':
190
                $length = $tableColumn['char_length'];
191
                $fixed  = true;
192 193
                break;
        }
romanb's avatar
romanb committed
194

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

208
        return new Column($this->getQuotedIdentifierName($tableColumn['column_name']), Type::getType($type), $options);
209 210
    }

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

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

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

236
            $list[$value['constraint_name']]['local'][$value['position']]   = $localColumn;
237
            $list[$value['constraint_name']]['foreign'][$value['position']] = $foreignColumn;
238 239
        }

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

        return $result;
    }

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

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

Benjamin Morel's avatar
Benjamin Morel committed
268 269
    /**
     * {@inheritdoc}
270 271
     *
     * @deprecated
Benjamin Morel's avatar
Benjamin Morel committed
272
     */
273 274
    protected function _getPortableFunctionDefinition($function)
    {
275
        $function = array_change_key_case($function, CASE_LOWER);
Benjamin Morel's avatar
Benjamin Morel committed
276

277 278
        return $function['name'];
    }
romanb's avatar
romanb committed
279

Benjamin Morel's avatar
Benjamin Morel committed
280 281 282
    /**
     * {@inheritdoc}
     */
283 284
    protected function _getPortableDatabaseDefinition($database)
    {
285
        $database = array_change_key_case($database, CASE_LOWER);
Benjamin Morel's avatar
Benjamin Morel committed
286

287 288
        return $database['username'];
    }
romanb's avatar
romanb committed
289

Benjamin Morel's avatar
Benjamin Morel committed
290 291
    /**
     * {@inheritdoc}
292
     *
293 294
     * @param string|null $database
     *
295
     * Calling this method without an argument or by passing NULL is deprecated.
Benjamin Morel's avatar
Benjamin Morel committed
296
     */
297 298
    public function createDatabase($database = null)
    {
299
        if ($database === null) {
300 301
            $database = $this->_conn->getDatabase();
        }
romanb's avatar
romanb committed
302

303 304 305
        $params   = $this->_conn->getParams();
        $username = $database;
        $password = $params['password'];
romanb's avatar
romanb committed
306

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

310
        $query = 'GRANT DBA TO ' . $username;
Benjamin Morel's avatar
Benjamin Morel committed
311
        $this->_conn->executeUpdate($query);
romanb's avatar
romanb committed
312
    }
313

Benjamin Morel's avatar
Benjamin Morel committed
314 315 316
    /**
     * @param string $table
     *
317
     * @return bool
Benjamin Morel's avatar
Benjamin Morel committed
318
     */
319
    public function dropAutoincrement($table)
romanb's avatar
romanb committed
320
    {
321 322
        assert($this->_platform instanceof OraclePlatform);

323 324
        $sql = $this->_platform->getDropAutoincrementSql($table);
        foreach ($sql as $query) {
325
            $this->_conn->executeUpdate($query);
326 327 328
        }

        return true;
romanb's avatar
romanb committed
329 330
    }

Benjamin Morel's avatar
Benjamin Morel committed
331 332 333
    /**
     * {@inheritdoc}
     */
romanb's avatar
romanb committed
334 335
    public function dropTable($name)
    {
336
        $this->tryMethod('dropAutoincrement', $name);
romanb's avatar
romanb committed
337

Benjamin Morel's avatar
Benjamin Morel committed
338
        parent::dropTable($name);
romanb's avatar
romanb committed
339
    }
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358

    /**
     * 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;
    }
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382

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

383
        $activeUserSessions = $this->_conn->fetchAll($sql, [strtoupper($user)]);
384 385

        foreach ($activeUserSessions as $activeUserSession) {
386
            $activeUserSession = array_change_key_case($activeUserSession, CASE_LOWER);
387 388 389 390 391 392 393 394 395 396

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

Grégoire Paris's avatar
Grégoire Paris committed
398 399 400
    /**
     * {@inheritdoc}
     */
401 402 403 404 405
    public function listTableDetails($tableName) : Table
    {
        $table = parent::listTableDetails($tableName);

        $platform = $this->_platform;
Grégoire Paris's avatar
Grégoire Paris committed
406 407
        assert($platform instanceof OraclePlatform);
        $sql = $platform->getListTableCommentsSQL($tableName);
408 409

        $tableOptions = $this->_conn->fetchAssoc($sql);
410 411 412 413

        if ($tableOptions !== false) {
            $table->addOption('comment', $tableOptions['COMMENTS']);
        }
414 415 416

        return $table;
    }
417
}