Failed Conditions
Pull Request — develop (#3581)
by Jonathan
12:44
created

OracleSchemaManager   B

Complexity

Total Complexity 51

Size/Duplication

Total Lines 335
Duplicated Lines 0 %

Test Coverage

Coverage 94.94%

Importance

Changes 0
Metric Value
wmc 51
eloc 159
dl 0
loc 335
ccs 150
cts 158
cp 0.9494
rs 7.92
c 0
b 0
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
A dropDatabase() 0 23 4
A _getPortableTableForeignKeysList() 0 38 5
A _getPortableTableIndexesList() 0 23 3
F _getPortableTableColumnDefinition() 0 86 26
A _getPortableSequenceDefinition() 0 8 1
A _getPortableViewDefinition() 0 5 1
A _getPortableUserDefinition() 0 6 1
A _getPortableTableDefinition() 0 5 1
A _getPortableDatabaseDefinition() 0 5 1
A dropTable() 0 5 1
A createDatabase() 0 11 1
A getQuotedIdentifierName() 0 7 2
A dropAutoincrement() 0 10 2
A killUserSessions() 0 24 2

How to fix   Complexity   

Complex Class

Complex classes like OracleSchemaManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use OracleSchemaManager, and based on these observations, apply Extract Interface, too.

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