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