Completed
Pull Request — master (#2960)
by Sergei
64:02
created

PostgreSqlSchemaManager::getSchemaSearchPaths()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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

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