Completed
Pull Request — master (#3422)
by
unknown
65:13
created

_getPortableSequencesList()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

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