Failed Conditions
Push — 2.10.x ( db5afa...61a6b9 )
by Grégoire
27s queued 15s
created

_getPortableDatabaseDefinition()   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 function array_change_key_case;
11
use function array_values;
12
use function assert;
13
use function preg_match;
14
use function sprintf;
15
use function str_replace;
16
use function strpos;
17
use function strtolower;
18
use function strtoupper;
19
use function trim;
20
use const CASE_LOWER;
21
22
/**
23
 * Oracle Schema Manager.
24
 */
25
class OracleSchemaManager extends AbstractSchemaManager
26
{
27
    /**
28
     * {@inheritdoc}
29
     */
30
    public function dropDatabase($database)
31
    {
32
        try {
33
            parent::dropDatabase($database);
34
        } catch (DBALException $exception) {
35
            $exception = $exception->getPrevious();
36
            assert($exception instanceof Throwable);
37
38
            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
            if ($exception->getErrorCode() !== 1940) {
47
                throw $exception;
48
            }
49
50
            $this->killUserSessions($database);
51
52
            parent::dropDatabase($database);
53
        }
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    protected function _getPortableViewDefinition($view)
60
    {
61
        $view = array_change_key_case($view, CASE_LOWER);
62
63
        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
    protected function _getPortableTableDefinition($table)
82
    {
83
        $table = array_change_key_case($table, CASE_LOWER);
84
85
        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
    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
94
    {
95
        $indexBuffer = [];
96
        foreach ($tableIndexes as $tableIndex) {
97
            $tableIndex = array_change_key_case($tableIndex, CASE_LOWER);
98
99
            $keyName = strtolower($tableIndex['name']);
100
            $buffer  = [];
101
102
            if (strtolower($tableIndex['is_primary']) === 'p') {
103
                $keyName              = 'primary';
104
                $buffer['primary']    = true;
105
                $buffer['non_unique'] = false;
106
            } else {
107
                $buffer['primary']    = false;
108
                $buffer['non_unique'] = ! $tableIndex['is_unique'];
109
            }
110
111
            $buffer['key_name']    = $keyName;
112
            $buffer['column_name'] = $this->getQuotedIdentifierName($tableIndex['column_name']);
113
            $indexBuffer[]         = $buffer;
114
        }
115
116
        return parent::_getPortableTableIndexesList($indexBuffer, $tableName);
117
    }
118
119
    /**
120
     * {@inheritdoc}
121
     */
122
    protected function _getPortableTableColumnDefinition($tableColumn)
123
    {
124
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
125
126
        $dbType = strtolower($tableColumn['data_type']);
127
        if (strpos($dbType, 'timestamp(') === 0) {
128
            if (strpos($dbType, 'with time zone')) {
129
                $dbType = 'timestamptz';
130
            } else {
131
                $dbType = 'timestamp';
132
            }
133
        }
134
135
        $unsigned = $fixed = $precision = $scale = $length = null;
136
137
        if (! isset($tableColumn['column_name'])) {
138
            $tableColumn['column_name'] = '';
139
        }
140
141
        // Default values returned from database sometimes have trailing spaces.
142
        $tableColumn['data_default'] = trim($tableColumn['data_default']);
143
144
        if ($tableColumn['data_default'] === '' || $tableColumn['data_default'] === 'NULL') {
145
            $tableColumn['data_default'] = null;
146
        }
147
148
        if ($tableColumn['data_default'] !== null) {
149
            // Default values returned from database are represented as literal expressions
150
            if (preg_match('/^\'(.*)\'$/s', $tableColumn['data_default'], $matches)) {
151
                $tableColumn['data_default'] = str_replace("''", "'", $matches[1]);
152
            }
153
        }
154
155
        if ($tableColumn['data_precision'] !== null) {
156
            $precision = (int) $tableColumn['data_precision'];
157
        }
158
159
        if ($tableColumn['data_scale'] !== null) {
160
            $scale = (int) $tableColumn['data_scale'];
161
        }
162
163
        $type                    = $this->_platform->getDoctrineTypeMapping($dbType);
164
        $type                    = $this->extractDoctrineTypeFromComment($tableColumn['comments'], $type);
165
        $tableColumn['comments'] = $this->removeDoctrineTypeFromComment($tableColumn['comments'], $type);
166
167
        switch ($dbType) {
168
            case 'number':
169
                if ($precision === 20 && $scale === 0) {
170
                    $type = 'bigint';
171
                } elseif ($precision === 5 && $scale === 0) {
172
                    $type = 'smallint';
173
                } elseif ($precision === 1 && $scale === 0) {
174
                    $type = 'boolean';
175
                } elseif ($scale > 0) {
176
                    $type = 'decimal';
177
                }
178
179
                break;
180
181
            case 'varchar':
182
            case 'varchar2':
183
            case 'nvarchar2':
184
                $length = $tableColumn['char_length'];
185
                $fixed  = false;
186
                break;
187
188
            case 'char':
189
            case 'nchar':
190
                $length = $tableColumn['char_length'];
191
                $fixed  = true;
192
                break;
193
        }
194
195
        $options = [
196
            'notnull'    => (bool) ($tableColumn['nullable'] === 'N'),
197
            'fixed'      => (bool) $fixed,
198
            'unsigned'   => (bool) $unsigned,
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($tableForeignKeys)
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($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
     * @deprecated
272
     */
273
    protected function _getPortableFunctionDefinition($function)
274
    {
275
        $function = array_change_key_case($function, CASE_LOWER);
276
277
        return $function['name'];
278
    }
279
280
    /**
281
     * {@inheritdoc}
282
     */
283
    protected function _getPortableDatabaseDefinition($database)
284
    {
285
        $database = array_change_key_case($database, CASE_LOWER);
286
287
        return $database['username'];
288
    }
289
290
    /**
291
     * {@inheritdoc}
292
     *
293
     * @param string|null $database
294
     *
295
     * Calling this method without an argument or by passing NULL is deprecated.
296
     */
297
    public function createDatabase($database = null)
298
    {
299
        if ($database === null) {
300
            $database = $this->_conn->getDatabase();
301
        }
302
303
        $params   = $this->_conn->getParams();
304
        $username = $database;
305
        $password = $params['password'];
306
307
        $query = 'CREATE USER ' . $username . ' IDENTIFIED BY ' . $password;
308
        $this->_conn->executeUpdate($query);
309
310
        $query = 'GRANT DBA TO ' . $username;
311
        $this->_conn->executeUpdate($query);
312
    }
313
314
    /**
315
     * @param string $table
316
     *
317
     * @return bool
318
     */
319
    public function dropAutoincrement($table)
320
    {
321
        assert($this->_platform instanceof OraclePlatform);
322
323
        $sql = $this->_platform->getDropAutoincrementSql($table);
324
        foreach ($sql as $query) {
325
            $this->_conn->executeUpdate($query);
326
        }
327
328
        return true;
329
    }
330
331
    /**
332
     * {@inheritdoc}
333
     */
334
    public function dropTable($name)
335
    {
336
        $this->tryMethod('dropAutoincrement', $name);
337
338
        parent::dropTable($name);
339
    }
340
341
    /**
342
     * Returns the quoted representation of the given identifier name.
343
     *
344
     * Quotes non-uppercase identifiers explicitly to preserve case
345
     * and thus make references to the particular identifier work.
346
     *
347
     * @param string $identifier The identifier to quote.
348
     *
349
     * @return string The quoted identifier.
350
     */
351
    private function getQuotedIdentifierName($identifier)
352
    {
353
        if (preg_match('/[a-z]/', $identifier)) {
354
            return $this->_platform->quoteIdentifier($identifier);
355
        }
356
357
        return $identifier;
358
    }
359
360
    /**
361
     * Kills sessions connected with the given user.
362
     *
363
     * This is useful to force DROP USER operations which could fail because of active user sessions.
364
     *
365
     * @param string $user The name of the user to kill sessions for.
366
     *
367
     * @return void
368
     */
369
    private function killUserSessions($user)
370
    {
371
        $sql = <<<SQL
372
SELECT
373
    s.sid,
374
    s.serial#
375
FROM
376
    gv\$session s,
377
    gv\$process p
378
WHERE
379
    s.username = ?
380
    AND p.addr(+) = s.paddr
381
SQL;
382
383
        $activeUserSessions = $this->_conn->fetchAll($sql, [strtoupper($user)]);
384
385
        foreach ($activeUserSessions as $activeUserSession) {
386
            $activeUserSession = array_change_key_case($activeUserSession, CASE_LOWER);
387
388
            $this->_execSql(
389
                sprintf(
390
                    "ALTER SYSTEM KILL SESSION '%s, %s' IMMEDIATE",
391
                    $activeUserSession['sid'],
392
                    $activeUserSession['serial#']
393
                )
394
            );
395
        }
396
    }
397
398
    /**
399
     * {@inheritdoc}
400
     */
401
    public function listTableDetails($tableName) : Table
402
    {
403
        $table = parent::listTableDetails($tableName);
404
405
        $platform = $this->_platform;
406
        assert($platform instanceof OraclePlatform);
407
        $sql = $platform->getListTableCommentsSQL($tableName);
408
409
        $tableOptions = $this->_conn->fetchAssoc($sql);
410
411
        if ($tableOptions !== false) {
412
            $table->addOption('comment', $tableOptions['COMMENTS']);
413
        }
414
415
        return $table;
416
    }
417
}
418