Completed
Pull Request — develop (#3565)
by Jonathan
61:10
created

OracleSchemaManager::createDatabase()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 15
rs 9.9666
c 0
b 0
f 0
ccs 5
cts 6
cp 0.8333
cc 2
nc 2
nop 1
crap 2.0185
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\DBAL\Schema;
6
7
use Doctrine\DBAL\DBALException;
8
use Doctrine\DBAL\Driver\DriverException;
9
use Doctrine\DBAL\Platforms\OraclePlatform;
10
use Doctrine\DBAL\Types\Type;
11
use Throwable;
12
use const CASE_LOWER;
13
use function array_change_key_case;
14
use function array_values;
15
use function assert;
16
use function preg_match;
17
use function sprintf;
18
use function str_replace;
19
use function strpos;
20
use function strtolower;
21
use function strtoupper;
22
use function trim;
23
24
/**
25
 * Oracle Schema Manager.
26
 */
27
class OracleSchemaManager extends AbstractSchemaManager
28
{
29
    /**
30
     * {@inheritdoc}
31 4
     */
32
    public function dropDatabase(string $database) : void
33
    {
34 4
        try {
35 4
            parent::dropDatabase($database);
36 4
        } catch (DBALException $exception) {
37 4
            $exception = $exception->getPrevious();
38
            assert($exception instanceof Throwable);
39 4
40
            if (! $exception instanceof DriverException) {
41
                throw $exception;
42
            }
43
44
            // If we have a error code 1940 (ORA-01940), the drop database operation failed
45
            // because of active connections on the database.
46
            // To force dropping the database, we first have to close all active connections
47 4
            // on that database and issue the drop database operation again.
48 4
            if ($exception->getCode() !== 1940) {
49
                throw $exception;
50
            }
51 2
52
            $this->killUserSessions($database);
53 2
54
            parent::dropDatabase($database);
55 2
        }
56
    }
57
58
    /**
59
     * {@inheritdoc}
60 2
     */
61
    protected function _getPortableViewDefinition(array $view) : ?View
62 2
    {
63
        $view = array_change_key_case($view, CASE_LOWER);
64 2
65
        return new View($this->getQuotedIdentifierName($view['view_name']), $view['text']);
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71
    protected function _getPortableUserDefinition(array $user) : array
72
    {
73
        $user = array_change_key_case($user, CASE_LOWER);
74
75
        return [
76
            'user' => $user['username'],
77
        ];
78
    }
79
80
    /**
81
     * {@inheritdoc}
82 126
     */
83
    protected function _getPortableTableDefinition(array $table) : string
84 126
    {
85
        $table = array_change_key_case($table, CASE_LOWER);
86 126
87
        return $this->getQuotedIdentifierName($table['table_name']);
88
    }
89
90
    /**
91
     * {@inheritdoc}
92
     *
93
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
94 56
     */
95
    protected function _getPortableTableIndexesList(array $tableIndexRows, string $tableName) : array
96 56
    {
97 56
        $indexBuffer = [];
98 30
        foreach ($tableIndexRows as $tableIndex) {
99
            $tableIndex = array_change_key_case($tableIndex, CASE_LOWER);
100 30
101 30
            $keyName = strtolower($tableIndex['name']);
102
            $buffer  = [];
103 30
104 26
            if ($tableIndex['is_primary'] === 'P') {
105 26
                $keyName              = 'primary';
106 26
                $buffer['primary']    = true;
107
                $buffer['non_unique'] = false;
108 24
            } else {
109 24
                $buffer['primary']    = false;
110
                $buffer['non_unique'] = ! $tableIndex['is_unique'];
111 30
            }
112 30
            $buffer['key_name']    = $keyName;
113 30
            $buffer['column_name'] = $this->getQuotedIdentifierName($tableIndex['column_name']);
114
            $indexBuffer[]         = $buffer;
115
        }
116 56
117
        return parent::_getPortableTableIndexesList($indexBuffer, $tableName);
118
    }
119
120
    /**
121
     * {@inheritdoc}
122 70
     */
123
    protected function _getPortableTableColumnDefinition(array $tableColumn) : Column
124 70
    {
125
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
126 70
127 70
        $dbType = strtolower($tableColumn['data_type']);
128 14
        if (strpos($dbType, 'timestamp(') === 0) {
129 6
            if (strpos($dbType, 'with time zone')) {
130
                $dbType = 'timestamptz';
131 14
            } else {
132
                $dbType = 'timestamp';
133
            }
134
        }
135 70
136 70
        $length = $precision = null;
137 70
        $scale  = 0;
138
        $fixed  = false;
139 70
140
        if (! isset($tableColumn['column_name'])) {
141
            $tableColumn['column_name'] = '';
142
        }
143
144 70
        // Default values returned from database sometimes have trailing spaces.
145 22
        if ($tableColumn['data_default'] !== null) {
146
            $tableColumn['data_default'] = trim($tableColumn['data_default']);
147
        }
148 70
149 16
        if ($tableColumn['data_default'] === '' || $tableColumn['data_default'] === 'NULL') {
150
            $tableColumn['data_default'] = null;
151
        }
152 70
153
        if ($tableColumn['data_default'] !== null) {
154 20
            // Default values returned from database are represented as literal expressions
155
            if (preg_match('/^\'(.*)\'$/s', $tableColumn['data_default'], $matches)) {
156
                $tableColumn['data_default'] = str_replace("''", "'", $matches[1]);
157 70
            }
158 62
        }
159
160
        if ($tableColumn['data_precision'] !== null) {
161 70
            $precision = (int) $tableColumn['data_precision'];
162 64
        }
163
164
        if ($tableColumn['data_scale'] !== null) {
165 70
            $scale = (int) $tableColumn['data_scale'];
166 70
        }
167
168 70
        $type = $this->extractDoctrineTypeFromComment($tableColumn['comments'])
169 70
            ?? $this->_platform->getDoctrineTypeMapping($dbType);
170 62
171
        switch ($dbType) {
172 62
            case 'number':
173
                if ($precision === 20 && $scale === 0) {
174 62
                    $type = 'bigint';
175 8
                } elseif ($precision === 5 && $scale === 0) {
176 60
                    $type = 'smallint';
177 10
                } elseif ($precision === 1 && $scale === 0) {
178
                    $type = 'boolean';
179
                } elseif ($scale > 0) {
180 62
                    $type = 'decimal';
181 38
                }
182 38
183 28
                break;
184 22
            case 'varchar':
185 22
            case 'varchar2':
186 28
            case 'nvarchar2':
187 24
                $length = (int) $tableColumn['char_length'];
188 10
                break;
189 10
            case 'char':
190 10
            case 'nchar':
191
                $length = (int) $tableColumn['char_length'];
192
                $fixed  = true;
193
                break;
194 70
        }
195 70
196 70
        $options = [
197 70
            'notnull'    => $tableColumn['nullable'] === 'N',
198 70
            'fixed'      => $fixed,
199 70
            'default'    => $tableColumn['data_default'],
200 70
            'length'     => $length,
201 34
            'precision'  => $precision,
202
            'scale'      => $scale,
203
            'comment'    => isset($tableColumn['comments']) && $tableColumn['comments'] !== ''
204
                ? $tableColumn['comments']
205 70
                : null,
206
        ];
207
208
        return new Column($this->getQuotedIdentifierName($tableColumn['column_name']), Type::getType($type), $options);
209
    }
210
211 50
    /**
212
     * {@inheritdoc}
213 50
     */
214 50
    protected function _getPortableTableForeignKeysList(array $tableForeignKeys) : array
215 18
    {
216 18
        $list = [];
217 18
        foreach ($tableForeignKeys as $value) {
218 16
            $value = array_change_key_case($value, CASE_LOWER);
219
            if (! isset($list[$value['constraint_name']])) {
220
                if ($value['delete_rule'] === 'NO ACTION') {
221 18
                    $value['delete_rule'] = null;
222 18
                }
223
224
                $list[$value['constraint_name']] = [
225 18
                    'name' => $this->getQuotedIdentifierName($value['constraint_name']),
226 18
                    'local' => [],
227
                    'foreign' => [],
228
                    'foreignTable' => $value['references_table'],
229
                    'onDelete' => $value['delete_rule'],
230 18
                ];
231 18
            }
232
233 18
            $localColumn   = $this->getQuotedIdentifierName($value['local_column']);
234 18
            $foreignColumn = $this->getQuotedIdentifierName($value['foreign_column']);
235
236
            $list[$value['constraint_name']]['local'][$value['position']]   = $localColumn;
237 50
            $list[$value['constraint_name']]['foreign'][$value['position']] = $foreignColumn;
238 50
        }
239 18
240 18
        $result = [];
241 18
        foreach ($list as $constraint) {
242 18
            $result[] = new ForeignKeyConstraint(
243 18
                array_values($constraint['local']),
244 18
                $this->getQuotedIdentifierName($constraint['foreignTable']),
245
                array_values($constraint['foreign']),
246
                $this->getQuotedIdentifierName($constraint['name']),
247
                ['onDelete' => $constraint['onDelete']]
248 50
            );
249
        }
250
251
        return $result;
252
    }
253
254 10
    /**
255
     * {@inheritdoc}
256 10
     */
257
    protected function _getPortableSequenceDefinition(array $sequence) : Sequence
258 10
    {
259 10
        $sequence = array_change_key_case($sequence, CASE_LOWER);
260 10
261 10
        return new Sequence(
262
            $this->getQuotedIdentifierName($sequence['sequence_name']),
263
            (int) $sequence['increment_by'],
264
            (int) $sequence['min_value']
265
        );
266
    }
267
268
    /**
269
     * {@inheritdoc}
270
     */
271
    protected function _getPortableDatabaseDefinition(array $database) : string
272
    {
273
        $database = array_change_key_case($database, CASE_LOWER);
274
275
        return $database['username'];
276
    }
277
278 4
    /**
279
     * {@inheritdoc}
280 4
     */
281
    public function createDatabase(?string $database = null) : void
282 4
    {
283
        if ($database === null) {
284
            $database = $this->_conn->getDatabase();
285
        }
286
287
        $params   = $this->_conn->getParams();
288 4
        $username = $database;
289
        $password = $params['password'];
290 4
291
        $query = 'CREATE USER ' . $username . ' IDENTIFIED BY ' . $password;
292
        $this->_conn->executeUpdate($query);
293
294 4
        $query = 'GRANT DBA TO ' . $username;
295 4
        $this->_conn->executeUpdate($query);
296 4
    }
297
298 4
    public function dropAutoincrement(string $table) : bool
299 4
    {
300
        assert($this->_platform instanceof OraclePlatform);
301 4
302 4
        $sql = $this->_platform->getDropAutoincrementSql($table);
303 4
        foreach ($sql as $query) {
304
            $this->_conn->executeUpdate($query);
305
        }
306
307
        return true;
308
    }
309
310 230
    /**
311
     * {@inheritdoc}
312 230
     */
313
    public function dropTable(string $name) : void
314 230
    {
315 230
        $this->tryMethod('dropAutoincrement', $name);
316 230
317
        parent::dropTable($name);
318
    }
319
320
    /**
321
     * Returns the quoted representation of the given identifier name.
322
     *
323
     * Quotes non-uppercase identifiers explicitly to preserve case
324
     * and thus make references to the particular identifier work.
325 230
     */
326
    private function getQuotedIdentifierName(string $identifier) : string
327 230
    {
328
        if (preg_match('/[a-z]/', $identifier)) {
329 230
            return $this->_platform->quoteIdentifier($identifier);
330 134
        }
331
332
        return $identifier;
333
    }
334
335
    /**
336
     * Kills sessions connected with the given user.
337
     *
338
     * This is useful to force DROP USER operations which could fail because of active user sessions.
339
     *
340
     * @param string $user The name of the user to kill sessions for.
341
     */
342 132
    private function killUserSessions(string $user) : void
343
    {
344 132
        $sql = <<<SQL
345 104
SELECT
346
    s.sid,
347
    s.serial#
348 132
FROM
349
    gv\$session s,
350
    gv\$process p
351
WHERE
352
    s.username = ?
353
    AND p.addr(+) = s.paddr
354
SQL;
355
356
        $activeUserSessions = $this->_conn->fetchAll($sql, [strtoupper($user)]);
357
358
        foreach ($activeUserSessions as $activeUserSession) {
359
            $activeUserSession = array_change_key_case($activeUserSession, CASE_LOWER);
360 2
361
            $this->_execSql(
362
                sprintf(
363 2
                    "ALTER SYSTEM KILL SESSION '%s, %s' IMMEDIATE",
364
                    $activeUserSession['sid'],
365
                    $activeUserSession['serial#']
366
                )
367
            );
368
        }
369
    }
370
}
371