Completed
Pull Request — develop (#3570)
by Jonathan
155:39 queued 152:58
created

_getPortableTableForeignKeyDefinition()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 29
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 4

Importance

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