Failed Conditions
Push — master ( d6883c...f5ddd0 )
by Sergei
14:06
created

_getPortableTableColumnDefinition()   F

Complexity

Conditions 48
Paths > 20000

Size

Total Lines 151
Code Lines 110

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 101
CRAP Score 48.6269

Importance

Changes 0
Metric Value
eloc 110
dl 0
loc 151
ccs 101
cts 108
cp 0.9352
rs 0
c 0
b 0
f 0
cc 48
nc 344064
nop 1
crap 48.6269

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Doctrine\DBAL\Schema;
4
5
use Doctrine\DBAL\Exception\DriverException;
6
use Doctrine\DBAL\FetchMode;
7
use Doctrine\DBAL\Platforms\PostgreSqlPlatform;
8
use Doctrine\DBAL\Types\Type;
9
use const CASE_LOWER;
10
use function array_change_key_case;
11
use function array_filter;
12
use function array_keys;
13
use function array_map;
14
use function array_shift;
15
use function assert;
16
use function explode;
17
use function implode;
18
use function in_array;
19
use function preg_match;
20
use function preg_replace;
21
use function sprintf;
22
use function str_replace;
23
use function stripos;
24
use function strlen;
25
use function strpos;
26
use function strtolower;
27
use function trim;
28
29
/**
30
 * PostgreSQL Schema Manager.
31
 */
32
class PostgreSqlSchemaManager extends AbstractSchemaManager
33
{
34
    /** @var string[] */
35
    private $existingSchemaPaths;
36
37
    /**
38
     * Gets all the existing schema names.
39
     *
40
     * @return string[]
41
     */
42 617
    public function getSchemaNames()
43
    {
44 617
        $statement = $this->_conn->executeQuery("SELECT nspname FROM pg_namespace WHERE nspname !~ '^pg_.*' AND nspname != 'information_schema'");
45
46 617
        return $statement->fetchAll(FetchMode::COLUMN);
47
    }
48
49
    /**
50
     * Returns an array of schema search paths.
51
     *
52
     * This is a PostgreSQL only function.
53
     *
54
     * @return string[]
55
     */
56 617
    public function getSchemaSearchPaths()
57
    {
58 617
        $params = $this->_conn->getParams();
59 617
        $schema = explode(',', $this->_conn->fetchColumn('SHOW search_path'));
0 ignored issues
show
Bug introduced by
It seems like $this->_conn->fetchColumn('SHOW search_path') can also be of type false; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

59
        $schema = explode(',', /** @scrutinizer ignore-type */ $this->_conn->fetchColumn('SHOW search_path'));
Loading history...
60
61 617
        if (isset($params['user'])) {
62 617
            $schema = str_replace('"$user"', $params['user'], $schema);
63
        }
64
65 617
        return array_map('trim', $schema);
66
    }
67
68
    /**
69
     * Gets names of all existing schemas in the current users search path.
70
     *
71
     * This is a PostgreSQL only function.
72
     *
73
     * @return string[]
74
     */
75 617
    public function getExistingSchemaSearchPaths()
76
    {
77 617
        if ($this->existingSchemaPaths === null) {
78 617
            $this->determineExistingSchemaSearchPaths();
79
        }
80
81 617
        return $this->existingSchemaPaths;
82
    }
83
84
    /**
85
     * Sets or resets the order of the existing schemas in the current search path of the user.
86
     *
87
     * This is a PostgreSQL only function.
88
     *
89
     * @return void
90
     */
91 617
    public function determineExistingSchemaSearchPaths()
92
    {
93 617
        $names = $this->getSchemaNames();
94 617
        $paths = $this->getSchemaSearchPaths();
95
96
        $this->existingSchemaPaths = array_filter($paths, static function ($v) use ($names) {
97 617
            return in_array($v, $names);
98 617
        });
99 617
    }
100
101
    /**
102
     * {@inheritdoc}
103
     */
104 383
    public function dropDatabase($database)
105
    {
106
        try {
107 383
            parent::dropDatabase($database);
108 383
        } catch (DriverException $exception) {
109
            // If we have a SQLSTATE 55006, the drop database operation failed
110
            // because of active connections on the database.
111
            // To force dropping the database, we first have to close all active connections
112
            // on that database and issue the drop database operation again.
113 383
            if ($exception->getSQLState() !== '55006') {
114 383
                throw $exception;
115
            }
116
117 383
            assert($this->_platform instanceof PostgreSqlPlatform);
118
119 383
            $this->_execSql(
120
                [
121 383
                    $this->_platform->getDisallowDatabaseConnectionsSQL($database),
122 383
                    $this->_platform->getCloseActiveDatabaseConnectionsSQL($database),
123
                ]
124
            );
125
126 383
            parent::dropDatabase($database);
127
        }
128 383
    }
129
130
    /**
131
     * {@inheritdoc}
132
     */
133 512
    protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
134
    {
135 512
        $onUpdate       = null;
136 512
        $onDelete       = null;
137 512
        $localColumns   = [];
138 512
        $foreignColumns = [];
139 512
        $foreignTable   = null;
140
141 512
        if (preg_match('(ON UPDATE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
142 505
            $onUpdate = $match[1];
143
        }
144 512
        if (preg_match('(ON DELETE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
145 491
            $onDelete = $match[1];
146
        }
147
148 512
        if (preg_match('/FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)/', $tableForeignKey['condef'], $values)) {
149
            // PostgreSQL returns identifiers that are keywords with quotes, we need them later, don't get
150
            // the idea to trim them here.
151 512
            $localColumns   = array_map('trim', explode(',', $values[1]));
152 512
            $foreignColumns = array_map('trim', explode(',', $values[3]));
153 512
            $foreignTable   = $values[2];
154
        }
155
156 512
        return new ForeignKeyConstraint(
157
            $localColumns,
158
            $foreignTable,
159
            $foreignColumns,
160 512
            $tableForeignKey['conname'],
161 512
            ['onUpdate' => $onUpdate, 'onDelete' => $onDelete]
162
        );
163
    }
164
165
    /**
166
     * {@inheritdoc}
167
     */
168
    protected function _getPortableTriggerDefinition($trigger)
169
    {
170
        return $trigger['trigger_name'];
171
    }
172
173
    /**
174
     * {@inheritdoc}
175
     */
176 264
    protected function _getPortableViewDefinition($view)
177
    {
178 264
        return new View($view['schemaname'] . '.' . $view['viewname'], $view['definition']);
179
    }
180
181
    /**
182
     * {@inheritdoc}
183
     */
184
    protected function _getPortableUserDefinition($user)
185
    {
186
        return [
187
            'user' => $user['usename'],
188
            'password' => $user['passwd'],
189
        ];
190
    }
191
192
    /**
193
     * {@inheritdoc}
194
     */
195 617
    protected function _getPortableTableDefinition($table)
196
    {
197 617
        $schemas     = $this->getExistingSchemaSearchPaths();
198 617
        $firstSchema = array_shift($schemas);
199
200 617
        if ($table['schema_name'] === $firstSchema) {
201 617
            return $table['table_name'];
202
        }
203
204 512
        return $table['schema_name'] . '.' . $table['table_name'];
205
    }
206
207
    /**
208
     * {@inheritdoc}
209
     *
210
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
211
     */
212 568
    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
213
    {
214 568
        $buffer = [];
215 568
        foreach ($tableIndexes as $row) {
216 540
            $colNumbers    = array_map('intval', explode(' ', $row['indkey']));
217 540
            $columnNameSql = sprintf(
218
                'SELECT attnum, attname FROM pg_attribute WHERE attrelid=%d AND attnum IN (%s) ORDER BY attnum ASC',
219 540
                $row['indrelid'],
220 540
                implode(' ,', $colNumbers)
221
            );
222
223 540
            $stmt         = $this->_conn->executeQuery($columnNameSql);
224 540
            $indexColumns = $stmt->fetchAll();
225
226
            // required for getting the order of the columns right.
227 540
            foreach ($colNumbers as $colNum) {
228 540
                foreach ($indexColumns as $colRow) {
229 540
                    if ($colNum !== $colRow['attnum']) {
230 449
                        continue;
231
                    }
232
233 540
                    $buffer[] = [
234 540
                        'key_name' => $row['relname'],
235 540
                        'column_name' => trim($colRow['attname']),
236 540
                        'non_unique' => ! $row['indisunique'],
237 540
                        'primary' => $row['indisprimary'],
238 540
                        'where' => $row['where'],
239
                    ];
240
                }
241
            }
242
        }
243
244 568
        return parent::_getPortableTableIndexesList($buffer, $tableName);
245
    }
246
247
    /**
248
     * {@inheritdoc}
249
     */
250 383
    protected function _getPortableDatabaseDefinition($database)
251
    {
252 383
        return $database['datname'];
253
    }
254
255
    /**
256
     * {@inheritdoc}
257
     */
258 376
    protected function _getPortableSequencesList($sequences)
259
    {
260 376
        $sequenceDefinitions = [];
261
262 376
        foreach ($sequences as $sequence) {
263 376
            if ($sequence['schemaname'] !== 'public') {
264 376
                $sequenceName = $sequence['schemaname'] . '.' . $sequence['relname'];
265
            } else {
266 376
                $sequenceName = $sequence['relname'];
267
            }
268
269 376
            $sequenceDefinitions[$sequenceName] = $sequence;
270
        }
271
272 376
        $list = [];
273
274 376
        foreach ($this->filterAssetNames(array_keys($sequenceDefinitions)) as $sequenceName) {
275 376
            $list[] = $this->_getPortableSequenceDefinition($sequenceDefinitions[$sequenceName]);
276
        }
277
278 376
        return $list;
279
    }
280
281
    /**
282
     * {@inheritdoc}
283
     */
284 355
    protected function getPortableNamespaceDefinition(array $namespace)
285
    {
286 355
        return $namespace['nspname'];
287
    }
288
289
    /**
290
     * {@inheritdoc}
291
     */
292 376
    protected function _getPortableSequenceDefinition($sequence)
293
    {
294 376
        if ($sequence['schemaname'] !== 'public') {
295 376
            $sequenceName = $sequence['schemaname'] . '.' . $sequence['relname'];
296
        } else {
297 376
            $sequenceName = $sequence['relname'];
298
        }
299
300 376
        if (! isset($sequence['increment_by'], $sequence['min_value'])) {
301
            /** @var string[] $data */
302 267
            $data = $this->_conn->fetchAssoc('SELECT min_value, increment_by FROM ' . $this->_platform->quoteIdentifier($sequenceName));
303
304 267
            $sequence += $data;
305
        }
306
307 376
        return new Sequence($sequenceName, (int) $sequence['increment_by'], (int) $sequence['min_value']);
308
    }
309
310
    /**
311
     * {@inheritdoc}
312
     */
313 568
    protected function _getPortableTableColumnDefinition($tableColumn)
314
    {
315 568
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
316
317 568
        if (strtolower($tableColumn['type']) === 'varchar' || strtolower($tableColumn['type']) === 'bpchar') {
318
            // get length from varchar definition
319 484
            $length                = preg_replace('~.*\(([0-9]*)\).*~', '$1', $tableColumn['complete_type']);
320 484
            $tableColumn['length'] = $length;
321
        }
322
323 568
        $matches = [];
324
325 568
        $autoincrement = false;
326 568
        if (preg_match("/^nextval\('(.*)'(::.*)?\)$/", $tableColumn['default'], $matches)) {
327 533
            $tableColumn['sequence'] = $matches[1];
328 533
            $tableColumn['default']  = null;
329 533
            $autoincrement           = true;
330
        }
331
332 568
        if (preg_match("/^['(](.*)[')]::.*$/", $tableColumn['default'], $matches)) {
333 484
            $tableColumn['default'] = $matches[1];
334
        }
335
336 568
        if (stripos($tableColumn['default'], 'NULL') === 0) {
337 456
            $tableColumn['default'] = null;
338
        }
339
340 568
        $length = $tableColumn['length'] ?? null;
341 568
        if ($length === '-1' && isset($tableColumn['atttypmod'])) {
342
            $length = $tableColumn['atttypmod'] - 4;
343
        }
344 568
        if ((int) $length <= 0) {
345 568
            $length = null;
346
        }
347 568
        $fixed = null;
348
349 568
        if (! isset($tableColumn['name'])) {
350 568
            $tableColumn['name'] = '';
351
        }
352
353 568
        $precision = null;
354 568
        $scale     = null;
355 568
        $jsonb     = null;
356
357 568
        $dbType = strtolower($tableColumn['type']);
358 568
        if (strlen($tableColumn['domain_type']) && ! $this->_platform->hasDoctrineTypeMappingFor($tableColumn['type'])) {
359 540
            $dbType                       = strtolower($tableColumn['domain_type']);
360 540
            $tableColumn['complete_type'] = $tableColumn['domain_complete_type'];
361
        }
362
363 568
        $type                   = $this->_platform->getDoctrineTypeMapping($dbType);
364 568
        $type                   = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
365 568
        $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
366
367
        switch ($dbType) {
368 568
            case 'smallint':
369 568
            case 'int2':
370 432
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
371 432
                $length                 = null;
372 432
                break;
373 568
            case 'int':
374 568
            case 'int4':
375 561
            case 'integer':
376 568
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
377 568
                $length                 = null;
378 568
                break;
379 561
            case 'bigint':
380 561
            case 'int8':
381 432
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
382 432
                $length                 = null;
383 432
                break;
384 561
            case 'bool':
385 540
            case 'boolean':
386 561
                if ($tableColumn['default'] === 'true') {
387
                    $tableColumn['default'] = true;
388
                }
389
390 561
                if ($tableColumn['default'] === 'false') {
391 561
                    $tableColumn['default'] = false;
392
                }
393
394 561
                $length = null;
395 561
                break;
396 540
            case 'text':
397 456
                $fixed = false;
398 456
                break;
399 540
            case 'varchar':
400 540
            case 'interval':
401 540
            case '_varchar':
402 484
                $fixed = false;
403 484
                break;
404 540
            case 'char':
405 540
            case 'bpchar':
406 456
                $fixed = true;
407 456
                break;
408 540
            case 'float':
409 540
            case 'float4':
410 540
            case 'float8':
411 540
            case 'double':
412 540
            case 'double precision':
413 540
            case 'real':
414 540
            case 'decimal':
415 540
            case 'money':
416 540
            case 'numeric':
417 540
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
418
419 540
                if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['complete_type'], $match)) {
420 540
                    $precision = $match[1];
421 540
                    $scale     = $match[2];
422 540
                    $length    = null;
423
                }
424 540
                break;
425 540
            case 'year':
426
                $length = null;
427
                break;
428
429
            // PostgreSQL 9.4+ only
430 540
            case 'jsonb':
431 320
                $jsonb = true;
432 320
                break;
433
        }
434
435 568
        if ($tableColumn['default'] && preg_match("('([^']+)'::)", $tableColumn['default'], $match)) {
436
            $tableColumn['default'] = $match[1];
437
        }
438
439
        $options = [
440 568
            'length'        => $length,
441 568
            'notnull'       => (bool) $tableColumn['isnotnull'],
442 568
            'default'       => $tableColumn['default'],
443 568
            'precision'     => $precision,
444 568
            'scale'         => $scale,
445 568
            'fixed'         => $fixed,
446
            'unsigned'      => false,
447 568
            'autoincrement' => $autoincrement,
448 568
            'comment'       => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
449 229
                ? $tableColumn['comment']
450
                : null,
451
        ];
452
453 568
        $column = new Column($tableColumn['field'], Type::getType($type), $options);
454
455 568
        if (isset($tableColumn['collation']) && ! empty($tableColumn['collation'])) {
456
            $column->setPlatformOption('collation', $tableColumn['collation']);
457
        }
458
459 568
        if (in_array($column->getType()->getName(), [Type::JSON_ARRAY, Type::JSON], true)) {
460 349
            $column->setPlatformOption('jsonb', $jsonb);
461
        }
462
463 568
        return $column;
464
    }
465
466
    /**
467
     * PostgreSQL 9.4 puts parentheses around negative numeric default values that need to be stripped eventually.
468
     *
469
     * @param mixed $defaultValue
470
     *
471
     * @return mixed
472
     */
473 568
    private function fixVersion94NegativeNumericDefaultValue($defaultValue)
474
    {
475 568
        if (strpos($defaultValue, '(') === 0) {
476 185
            return trim($defaultValue, '()');
477
        }
478
479 568
        return $defaultValue;
480
    }
481
}
482