Passed
Pull Request — master (#3817)
by Sergei
12:25
created

OracleSchemaManager::dropAutoincrement()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 10
ccs 5
cts 6
cp 0.8333
rs 10
c 0
b 0
f 0
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
     */
32 4
    public function dropDatabase(string $database) : void
33
    {
34
        try {
35 4
            parent::dropDatabase($database);
36 4
        } catch (DBALException $exception) {
37 4
            $exception = $exception->getPrevious();
38 4
            assert($exception instanceof Throwable);
39
40 4
            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 4
            if ($exception->getCode() !== 1940) {
49 4
                throw $exception;
50
            }
51
52 2
            $this->killUserSessions($database);
53
54 2
            parent::dropDatabase($database);
55
        }
56 2
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61 2
    protected function _getPortableViewDefinition(array $view) : View
62
    {
63 2
        $view = array_change_key_case($view, CASE_LOWER);
64
65 2
        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 26
    protected function _getPortableTableDefinition(array $table) : string
84
    {
85 26
        $table = array_change_key_case($table, CASE_LOWER);
86
87 26
        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 88
    protected function _getPortableTableIndexesList(array $tableIndexRows, string $tableName) : array
96
    {
97 88
        $indexBuffer = [];
98 88
        foreach ($tableIndexRows as $tableIndex) {
99 30
            $tableIndex = array_change_key_case($tableIndex, CASE_LOWER);
100
101 30
            $keyName = strtolower($tableIndex['name']);
102 30
            $buffer  = [];
103
104 30
            if ($tableIndex['is_primary'] === 'P') {
105 26
                $keyName              = 'primary';
106 26
                $buffer['primary']    = true;
107 26
                $buffer['non_unique'] = false;
108
            } else {
109 24
                $buffer['primary']    = false;
110 24
                $buffer['non_unique'] = ! $tableIndex['is_unique'];
111
            }
112 30
            $buffer['key_name']    = $keyName;
113 30
            $buffer['column_name'] = $this->getQuotedIdentifierName($tableIndex['column_name']);
114 30
            $indexBuffer[]         = $buffer;
115
        }
116
117 88
        return parent::_getPortableTableIndexesList($indexBuffer, $tableName);
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123 102
    protected function _getPortableTableColumnDefinition(array $tableColumn) : Column
124
    {
125 102
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
126
127 102
        $dbType = strtolower($tableColumn['data_type']);
128 102
        if (strpos($dbType, 'timestamp(') === 0) {
129 14
            if (strpos($dbType, 'with time zone')) {
130 6
                $dbType = 'timestamptz';
131
            } else {
132 14
                $dbType = 'timestamp';
133
            }
134
        }
135
136 102
        $length = $precision = null;
137 102
        $scale  = 0;
138 102
        $fixed  = false;
139
140 102
        if (! isset($tableColumn['column_name'])) {
141
            $tableColumn['column_name'] = '';
142
        }
143
144
        // Default values returned from database sometimes have trailing spaces.
145 102
        if ($tableColumn['data_default'] !== null) {
146 56
            $tableColumn['data_default'] = trim($tableColumn['data_default']);
147
        }
148
149 102
        if ($tableColumn['data_default'] === '' || $tableColumn['data_default'] === 'NULL') {
150 50
            $tableColumn['data_default'] = null;
151
        }
152
153 102
        if ($tableColumn['data_default'] !== null) {
154
            // Default values returned from database are represented as literal expressions
155 54
            if (preg_match('/^\'(.*)\'$/s', $tableColumn['data_default'], $matches)) {
156 52
                $tableColumn['data_default'] = str_replace("''", "'", $matches[1]);
157
            }
158
        }
159
160 102
        if ($tableColumn['data_precision'] !== null) {
161 98
            $precision = (int) $tableColumn['data_precision'];
162
        }
163
164 102
        if ($tableColumn['data_scale'] !== null) {
165 100
            $scale = (int) $tableColumn['data_scale'];
166
        }
167
168 102
        $type = $this->extractDoctrineTypeFromComment($tableColumn['comments'])
169 102
            ?? $this->_platform->getDoctrineTypeMapping($dbType);
170
171 102
        switch ($dbType) {
172 102
            case 'number':
173 98
                if ($precision === 20 && $scale === 0) {
174
                    $type = 'bigint';
175 98
                } elseif ($precision === 5 && $scale === 0) {
176
                    $type = 'smallint';
177 98
                } elseif ($precision === 1 && $scale === 0) {
178 2
                    $type = 'boolean';
179 96
                } elseif ($scale > 0) {
180 10
                    $type = 'decimal';
181
                }
182
183 98
                break;
184 68
            case 'varchar':
185 68
            case 'varchar2':
186 24
            case 'nvarchar2':
187 56
                $length = (int) $tableColumn['char_length'];
188 56
                break;
189 24
            case 'char':
190 20
            case 'nchar':
191 10
                $length = (int) $tableColumn['char_length'];
192 10
                $fixed  = true;
193 10
                break;
194
        }
195
196
        $options = [
197 102
            'notnull'    => $tableColumn['nullable'] === 'N',
198 102
            'fixed'      => $fixed,
199 102
            'default'    => $tableColumn['data_default'],
200 102
            'length'     => $length,
201 102
            'precision'  => $precision,
202 102
            'scale'      => $scale,
203 102
            'comment'    => isset($tableColumn['comments']) && $tableColumn['comments'] !== ''
204 34
                ? $tableColumn['comments']
205
                : null,
206
        ];
207
208 102
        return new Column($this->getQuotedIdentifierName($tableColumn['column_name']), Type::getType($type), $options);
209
    }
210
211
    /**
212
     * {@inheritdoc}
213
     */
214 82
    protected function _getPortableTableForeignKeysList(array $tableForeignKeys) : array
215
    {
216 82
        $list = [];
217 82
        foreach ($tableForeignKeys as $value) {
218 18
            $value = array_change_key_case($value, CASE_LOWER);
219 18
            if (! isset($list[$value['constraint_name']])) {
220 18
                if ($value['delete_rule'] === 'NO ACTION') {
221 16
                    $value['delete_rule'] = null;
222
                }
223
224 18
                $list[$value['constraint_name']] = [
225 18
                    'name' => $this->getQuotedIdentifierName($value['constraint_name']),
226
                    'local' => [],
227
                    'foreign' => [],
228 18
                    'foreignTable' => $value['references_table'],
229 18
                    'onDelete' => $value['delete_rule'],
230
                ];
231
            }
232
233 18
            $localColumn   = $this->getQuotedIdentifierName($value['local_column']);
234 18
            $foreignColumn = $this->getQuotedIdentifierName($value['foreign_column']);
235
236 18
            $list[$value['constraint_name']]['local'][$value['position']]   = $localColumn;
237 18
            $list[$value['constraint_name']]['foreign'][$value['position']] = $foreignColumn;
238
        }
239
240 82
        $result = [];
241 82
        foreach ($list as $constraint) {
242 18
            $result[] = new ForeignKeyConstraint(
243 18
                array_values($constraint['local']),
244 18
                $this->getQuotedIdentifierName($constraint['foreignTable']),
245 18
                array_values($constraint['foreign']),
246 18
                $this->getQuotedIdentifierName($constraint['name']),
247 18
                ['onDelete' => $constraint['onDelete']]
248
            );
249
        }
250
251 82
        return $result;
252
    }
253
254
    /**
255
     * {@inheritdoc}
256
     */
257 9
    protected function _getPortableSequenceDefinition(array $sequence) : Sequence
258
    {
259 9
        $sequence = array_change_key_case($sequence, CASE_LOWER);
260
261 9
        return new Sequence(
262 9
            $this->getQuotedIdentifierName($sequence['sequence_name']),
263 9
            (int) $sequence['increment_by'],
264 9
            (int) $sequence['min_value']
265
        );
266
    }
267
268
    /**
269
     * {@inheritdoc}
270
     */
271 4
    protected function _getPortableDatabaseDefinition(array $database) : string
272
    {
273 4
        $database = array_change_key_case($database, CASE_LOWER);
274
275 4
        return $database['username'];
276
    }
277
278
    /**
279
     * {@inheritdoc}
280
     */
281 4
    public function createDatabase(string $database) : void
282
    {
283 4
        $params   = $this->_conn->getParams();
284 4
        $username = $database;
285 4
        $password = $params['password'];
286
287 4
        $query = 'CREATE USER ' . $username . ' IDENTIFIED BY ' . $password;
288 4
        $this->_conn->executeUpdate($query);
289
290 4
        $query = 'GRANT DBA TO ' . $username;
291 4
        $this->_conn->executeUpdate($query);
292 4
    }
293
294 263
    public function dropAutoincrement(string $table) : bool
295
    {
296 263
        assert($this->_platform instanceof OraclePlatform);
297
298 263
        $sql = $this->_platform->getDropAutoincrementSql($table);
299 263
        foreach ($sql as $query) {
300 263
            $this->_conn->executeUpdate($query);
301
        }
302
303
        return true;
304
    }
305
306
    /**
307
     * {@inheritdoc}
308
     */
309 263
    public function dropTable(string $name) : void
310
    {
311 263
        $this->tryMethod('dropAutoincrement', $name);
312
313 263
        parent::dropTable($name);
314 162
    }
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 145
    private function getQuotedIdentifierName(string $identifier) : string
323
    {
324 145
        if (preg_match('/[a-z]/', $identifier)) {
325 17
            return $this->_platform->quoteIdentifier($identifier);
326
        }
327
328 145
        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 2
    private function killUserSessions(string $user) : void
339
    {
340
        $sql = <<<SQL
341 2
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 2
        $activeUserSessions = $this->_conn->fetchAll($sql, [strtoupper($user)]);
353
354 2
        foreach ($activeUserSessions as $activeUserSession) {
355 2
            $activeUserSession = array_change_key_case($activeUserSession, CASE_LOWER);
356
357 2
            $this->_execSql(
358 2
                sprintf(
359 2
                    "ALTER SYSTEM KILL SESSION '%s, %s' IMMEDIATE",
360 2
                    $activeUserSession['sid'],
361 2
                    $activeUserSession['serial#']
362
                )
363
            );
364
        }
365 2
    }
366
367 78
    public function listTableDetails(string $tableName) : Table
368
    {
369 78
        $table = parent::listTableDetails($tableName);
370
371
        /** @var OraclePlatform $platform */
372 78
        $platform = $this->_platform;
373 78
        $sql      = $platform->getListTableCommentsSQL($tableName);
374
375 78
        $tableOptions = $this->_conn->fetchAssoc($sql);
376 78
        $table->addOption('comment', $tableOptions['COMMENTS']);
377
378 78
        return $table;
379
    }
380
}
381