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