Passed
Pull Request — master (#3070)
by Sergei
07:45
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 Doctrine\DBAL\Types\Types;
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 sprintf;
23
use function str_replace;
24
use function strlen;
25
use function strpos;
26
use function strtolower;
27
use function trim;
28
use const CASE_LOWER;
29
30
/**
31
 * PostgreSQL Schema Manager.
32
 */
33
class PostgreSqlSchemaManager extends AbstractSchemaManager
34
{
35
    /** @var array<int, string> */
36
    private $existingSchemaPaths;
37
38
    /**
39
     * Gets all the existing schema names.
40
     *
41
     * @return array<int, string>
42
     */
43 16
    public function getSchemaNames() : array
44
    {
45 16
        $statement = $this->_conn->executeQuery("SELECT nspname FROM pg_namespace WHERE nspname !~ '^pg_.*' AND nspname != 'information_schema'");
46
47 16
        return $statement->fetchAll(FetchMode::COLUMN);
48
    }
49
50
    /**
51
     * Returns an array of schema search paths.
52
     *
53
     * This is a PostgreSQL only function.
54
     *
55
     * @return array<int, string>
56
     */
57 136
    public function getSchemaSearchPaths() : array
58
    {
59 136
        $params = $this->_conn->getParams();
60 136
        $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

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