Failed Conditions
Pull Request — develop (#3348)
by Sergei
10:40
created

_getPortableTableIndexesList()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 5.0026

Importance

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