Failed Conditions
Pull Request — develop (#3348)
by Sergei
161:07 queued 96:04
created

_getPortableTriggerDefinition()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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