Failed Conditions
Push — master ( ff1501...ac0e13 )
by Sergei
22s queued 17s
created

OracleSchemaManager   C

Complexity

Total Complexity 53

Size/Duplication

Total Lines 349
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 167
c 0
b 0
f 0
dl 0
loc 349
rs 6.96
wmc 53

15 Methods

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