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

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

5
use Doctrine\DBAL\DBALException;
6
use Doctrine\DBAL\Driver\Exception;
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 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

Grégoire Paris's avatar
Grégoire Paris committed
22
use const CASE_LOWER;
23

romanb's avatar
romanb committed
24
/**
Benjamin Morel's avatar
Benjamin Morel committed
25
 * Oracle Schema Manager.
romanb's avatar
romanb committed
26
 */
27
class OracleSchemaManager extends AbstractSchemaManager
28
{
29 30 31 32 33 34 35 36 37
    /**
     * {@inheritdoc}
     */
    public function dropDatabase($database)
    {
        try {
            parent::dropDatabase($database);
        } catch (DBALException $exception) {
            $exception = $exception->getPrevious();
Sergei Morozov's avatar
Sergei Morozov committed
38
            assert($exception instanceof Throwable);
39

40
            if (! $exception instanceof Exception) {
41 42 43 44 45 46 47
                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.
48
            if ($exception->getCode() !== 1940) {
49 50 51 52 53 54 55 56 57
                throw $exception;
            }

            $this->killUserSessions($database);

            parent::dropDatabase($database);
        }
    }

Benjamin Morel's avatar
Benjamin Morel committed
58 59 60
    /**
     * {@inheritdoc}
     */
61
    protected function _getPortableViewDefinition($view)
romanb's avatar
romanb committed
62
    {
63
        $view = array_change_key_case($view, CASE_LOWER);
64

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

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

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

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

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

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

            $keyName = strtolower($tableIndex['name']);
102
            $buffer  = [];
103

104 105 106
            if (strtolower($tableIndex['is_primary']) === 'p') {
                $keyName              = 'primary';
                $buffer['primary']    = true;
107 108
                $buffer['non_unique'] = false;
            } else {
109
                $buffer['primary']    = false;
110
                $buffer['non_unique'] = ! $tableIndex['is_unique'];
111
            }
Grégoire Paris's avatar
Grégoire Paris committed
112

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

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

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

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

137
        $unsigned = $fixed = $precision = $scale = $length = null;
romanb's avatar
romanb committed
138

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

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

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

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

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

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

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

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

181
                break;
Sergei Morozov's avatar
Sergei Morozov committed
182

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

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

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

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

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

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

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

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

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

        return $result;
    }

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

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

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

277 278
        return $database['username'];
    }
romanb's avatar
romanb committed
279

Benjamin Morel's avatar
Benjamin Morel committed
280 281 282
    /**
     * {@inheritdoc}
     */
283
    public function createDatabase($database)
284
    {
285 286 287
        $params   = $this->_conn->getParams();
        $username = $database;
        $password = $params['password'];
romanb's avatar
romanb committed
288

289
        $query = 'CREATE USER ' . $username . ' IDENTIFIED BY ' . $password;
290
        $this->_conn->executeStatement($query);
291

292
        $query = 'GRANT DBA TO ' . $username;
293
        $this->_conn->executeStatement($query);
romanb's avatar
romanb committed
294
    }
295

Benjamin Morel's avatar
Benjamin Morel committed
296 297 298
    /**
     * @param string $table
     *
299
     * @return bool
300 301
     *
     * @throws DBALException
Benjamin Morel's avatar
Benjamin Morel committed
302
     */
303
    public function dropAutoincrement($table)
romanb's avatar
romanb committed
304
    {
305 306
        assert($this->_platform instanceof OraclePlatform);

307 308
        $sql = $this->_platform->getDropAutoincrementSql($table);
        foreach ($sql as $query) {
309
            $this->_conn->executeStatement($query);
310 311 312
        }

        return true;
romanb's avatar
romanb committed
313 314
    }

Benjamin Morel's avatar
Benjamin Morel committed
315 316 317
    /**
     * {@inheritdoc}
     */
romanb's avatar
romanb committed
318 319
    public function dropTable($name)
    {
320
        $this->tryMethod('dropAutoincrement', $name);
romanb's avatar
romanb committed
321

Benjamin Morel's avatar
Benjamin Morel committed
322
        parent::dropTable($name);
romanb's avatar
romanb committed
323
    }
324 325 326 327 328 329 330 331 332 333 334 335 336

    /**
     * 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)
    {
337
        if (preg_match('/[a-z]/', $identifier) === 1) {
338 339 340 341 342
            return $this->_platform->quoteIdentifier($identifier);
        }

        return $identifier;
    }
343 344 345 346 347 348 349 350 351

    /**
     * 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
352 353
     *
     * @throws DBALException
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
     */
    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;

369
        $activeUserSessions = $this->_conn->fetchAllAssociative($sql, [strtoupper($user)]);
370 371

        foreach ($activeUserSessions as $activeUserSession) {
372
            $activeUserSession = array_change_key_case($activeUserSession, CASE_LOWER);
373 374 375 376 377 378 379 380 381 382

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

Grégoire Paris's avatar
Grégoire Paris committed
384 385 386
    /**
     * {@inheritdoc}
     */
387
    public function listTableDetails($name): Table
388
    {
389
        $table = parent::listTableDetails($name);
390 391

        $platform = $this->_platform;
Grégoire Paris's avatar
Grégoire Paris committed
392
        assert($platform instanceof OraclePlatform);
393
        $sql = $platform->getListTableCommentsSQL($name);
394

395
        $tableOptions = $this->_conn->fetchAssociative($sql);
396 397 398 399

        if ($tableOptions !== false) {
            $table->addOption('comment', $tableOptions['COMMENTS']);
        }
400 401 402

        return $table;
    }
403
}