Failed Conditions
Pull Request — master (#3546)
by Sergei
14:16
created

_getPortableFunctionDefinition()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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