Passed
Push — drop-deprecated ( db0b1f )
by Michael
27:00
created

_getPortableTableColumnDefinition()   F

Complexity

Conditions 52
Paths > 20000

Size

Total Lines 153
Code Lines 111

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 77
CRAP Score 120.4344

Importance

Changes 0
Metric Value
eloc 111
dl 0
loc 153
ccs 77
cts 109
cp 0.7064
rs 0
c 0
b 0
f 0
cc 52
nc 344064
nop 1
crap 120.4344

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
declare(strict_types=1);
4
5
namespace Doctrine\DBAL\Schema;
6
7
use Doctrine\DBAL\Exception\DriverException;
8
use Doctrine\DBAL\FetchMode;
9
use Doctrine\DBAL\Platforms\PostgreSqlPlatform;
10
use Doctrine\DBAL\Types\Type;
11
use const CASE_LOWER;
12
use function array_change_key_case;
13
use function array_filter;
14
use function array_keys;
15
use function array_map;
16
use function array_shift;
17
use function assert;
18
use function explode;
19
use function implode;
20
use function in_array;
21
use function preg_match;
22
use function preg_replace;
23
use function sprintf;
24
use function str_replace;
25
use function stripos;
26
use function strlen;
27
use function strpos;
28
use function strtolower;
29
use function trim;
30
31
/**
32
 * PostgreSQL Schema Manager.
33
 */
34
class PostgreSqlSchemaManager extends AbstractSchemaManager
35
{
36
    /** @var string[] */
37
    private $existingSchemaPaths;
38
39
    /**
40
     * Gets all the existing schema names.
41
     *
42
     * @return string[]
43
     */
44 468
    public function getSchemaNames()
45
    {
46 468
        $statement = $this->_conn->executeQuery("SELECT nspname FROM pg_namespace WHERE nspname !~ '^pg_.*' AND nspname != 'information_schema'");
47
48 468
        return $statement->fetchAll(FetchMode::COLUMN);
49
    }
50
51
    /**
52
     * Returns an array of schema search paths.
53
     *
54
     * This is a PostgreSQL only function.
55
     *
56
     * @return string[]
57
     */
58 468
    public function getSchemaSearchPaths()
59
    {
60 468
        $params = $this->_conn->getParams();
61 468
        $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

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