PostgreSqlSchemaManager.php 15.5 KB
Newer Older
romanb's avatar
romanb committed
1 2
<?php

Michael Moravec's avatar
Michael Moravec committed
3 4
declare(strict_types=1);

5
namespace Doctrine\DBAL\Schema;
romanb's avatar
romanb committed
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 13 14 15 16 17
use const CASE_LOWER;
use function array_change_key_case;
use function array_filter;
use function array_keys;
use function array_map;
use function array_shift;
18
use function assert;
19
use function explode;
20
use function implode;
21 22
use function in_array;
use function preg_match;
23
use function sprintf;
24 25 26 27 28
use function str_replace;
use function strlen;
use function strpos;
use function strtolower;
use function trim;
29

romanb's avatar
romanb committed
30
/**
Benjamin Morel's avatar
Benjamin Morel committed
31
 * PostgreSQL Schema Manager.
romanb's avatar
romanb committed
32
 */
33
class PostgreSqlSchemaManager extends AbstractSchemaManager
34
{
35
    /** @var array<int, string> */
36 37 38
    private $existingSchemaPaths;

    /**
Benjamin Morel's avatar
Benjamin Morel committed
39
     * Gets all the existing schema names.
40
     *
41
     * @return array<int, string>
42
     */
43
    public function getSchemaNames() : array
44
    {
45
        $statement = $this->_conn->executeQuery("SELECT nspname FROM pg_namespace WHERE nspname !~ '^pg_.*' AND nspname != 'information_schema'");
Benjamin Morel's avatar
Benjamin Morel committed
46

47
        return $statement->fetchAll(FetchMode::COLUMN);
48 49 50
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
51
     * Returns an array of schema search paths.
52 53 54
     *
     * This is a PostgreSQL only function.
     *
55
     * @return array<int, string>
56
     */
57
    public function getSchemaSearchPaths() : array
58 59
    {
        $params = $this->_conn->getParams();
60
        $schema = explode(',', $this->_conn->fetchColumn('SHOW search_path'));
61

62 63 64
        if (isset($params['user'])) {
            $schema = str_replace('"$user"', $params['user'], $schema);
        }
65 66

        return array_map('trim', $schema);
67 68 69
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
70
     * Gets names of all existing schemas in the current users search path.
71 72 73
     *
     * This is a PostgreSQL only function.
     *
74
     * @return array<int, string>
75
     */
76
    public function getExistingSchemaSearchPaths() : array
77 78 79 80
    {
        if ($this->existingSchemaPaths === null) {
            $this->determineExistingSchemaSearchPaths();
        }
Benjamin Morel's avatar
Benjamin Morel committed
81

82 83 84 85
        return $this->existingSchemaPaths;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
86
     * Sets or resets the order of the existing schemas in the current search path of the user.
87 88 89
     *
     * This is a PostgreSQL only function.
     */
90
    public function determineExistingSchemaSearchPaths() : void
91 92 93 94
    {
        $names = $this->getSchemaNames();
        $paths = $this->getSchemaSearchPaths();

95
        $this->existingSchemaPaths = array_filter($paths, static function ($v) use ($names) : bool {
96 97 98
            return in_array($v, $names);
        });
    }
99

100 101 102
    /**
     * {@inheritdoc}
     */
103
    public function dropDatabase(string $database) : void
104 105 106 107 108 109 110 111 112 113 114 115
    {
        try {
            parent::dropDatabase($database);
        } catch (DriverException $exception) {
            // If we have a SQLSTATE 55006, the drop database operation failed
            // because of active connections on the database.
            // To force dropping the database, we first have to close all active connections
            // on that database and issue the drop database operation again.
            if ($exception->getSQLState() !== '55006') {
                throw $exception;
            }

116 117
            assert($this->_platform instanceof PostgreSqlPlatform);

118
            $this->_execSql(
119
                [
120 121
                    $this->_platform->getDisallowDatabaseConnectionsSQL($database),
                    $this->_platform->getCloseActiveDatabaseConnectionsSQL($database),
122
                ]
123 124 125 126 127 128
            );

            parent::dropDatabase($database);
        }
    }

Benjamin Morel's avatar
Benjamin Morel committed
129 130 131
    /**
     * {@inheritdoc}
     */
132
    protected function _getPortableTableForeignKeyDefinition(array $tableForeignKey) : ForeignKeyConstraint
romanb's avatar
romanb committed
133
    {
134 135
        $onUpdate       = null;
        $onDelete       = null;
Sergei Morozov's avatar
Sergei Morozov committed
136 137
        $localColumns   = [];
        $foreignColumns = [];
138
        $foreignTable   = null;
139

140
        if (preg_match('(ON UPDATE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
141
            $onUpdate = $match[1];
romanb's avatar
romanb committed
142
        }
143
        if (preg_match('(ON DELETE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
144 145 146
            $onDelete = $match[1];
        }

147
        if (preg_match('/FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)/', $tableForeignKey['condef'], $values)) {
148 149
            // PostgreSQL returns identifiers that are keywords with quotes, we need them later, don't get
            // the idea to trim them here.
150 151 152
            $localColumns   = array_map('trim', explode(',', $values[1]));
            $foreignColumns = array_map('trim', explode(',', $values[3]));
            $foreignTable   = $values[2];
153 154
        }

155
        return new ForeignKeyConstraint(
156 157 158 159
            $localColumns,
            $foreignTable,
            $foreignColumns,
            $tableForeignKey['conname'],
160
            ['onUpdate' => $onUpdate, 'onDelete' => $onDelete]
161
        );
romanb's avatar
romanb committed
162 163
    }

Benjamin Morel's avatar
Benjamin Morel committed
164 165 166
    /**
     * {@inheritdoc}
     */
167
    protected function _getPortableViewDefinition(array $view) : View
168
    {
169
        return new View($view['schemaname'] . '.' . $view['viewname'], $view['definition']);
romanb's avatar
romanb committed
170 171
    }

Benjamin Morel's avatar
Benjamin Morel committed
172 173 174
    /**
     * {@inheritdoc}
     */
175
    protected function _getPortableUserDefinition(array $user) : array
romanb's avatar
romanb committed
176
    {
177
        return [
178
            'user' => $user['usename'],
179
            'password' => $user['passwd'],
180
        ];
romanb's avatar
romanb committed
181 182
    }

Benjamin Morel's avatar
Benjamin Morel committed
183 184 185
    /**
     * {@inheritdoc}
     */
186
    protected function _getPortableTableDefinition(array $table) : string
romanb's avatar
romanb committed
187
    {
188
        $schemas     = $this->getExistingSchemaSearchPaths();
189 190
        $firstSchema = array_shift($schemas);

191
        if ($table['schema_name'] === $firstSchema) {
192 193
            return $table['table_name'];
        }
Gabriel Caruso's avatar
Gabriel Caruso committed
194

195
        return $table['schema_name'] . '.' . $table['table_name'];
196 197
    }

198
    /**
Benjamin Morel's avatar
Benjamin Morel committed
199 200
     * {@inheritdoc}
     *
201 202
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
     */
203
    protected function _getPortableTableIndexesList(array $tableIndexRows, string $tableName) : array
204
    {
205
        $buffer = [];
206
        foreach ($tableIndexRows as $row) {
207
            $colNumbers    = array_map('intval', explode(' ', $row['indkey']));
208 209 210 211 212
            $columnNameSql = sprintf(
                'SELECT attnum, attname FROM pg_attribute WHERE attrelid=%d AND attnum IN (%s) ORDER BY attnum ASC',
                $row['indrelid'],
                implode(' ,', $colNumbers)
            );
213

214
            $stmt         = $this->_conn->executeQuery($columnNameSql);
215 216
            $indexColumns = $stmt->fetchAll();

217
            // required for getting the order of the columns right.
218
            foreach ($colNumbers as $colNum) {
219
                foreach ($indexColumns as $colRow) {
220 221
                    if ($colNum !== $colRow['attnum']) {
                        continue;
222
                    }
223 224 225 226 227 228 229 230

                    $buffer[] = [
                        'key_name' => $row['relname'],
                        'column_name' => trim($colRow['attname']),
                        'non_unique' => ! $row['indisunique'],
                        'primary' => $row['indisprimary'],
                        'where' => $row['where'],
                    ];
231
                }
232 233
            }
        }
Benjamin Morel's avatar
Benjamin Morel committed
234

235
        return parent::_getPortableTableIndexesList($buffer, $tableName);
236 237
    }

Benjamin Morel's avatar
Benjamin Morel committed
238 239 240
    /**
     * {@inheritdoc}
     */
241
    protected function _getPortableDatabaseDefinition(array $database) : string
242 243 244 245
    {
        return $database['datname'];
    }

246 247 248
    /**
     * {@inheritdoc}
     */
249
    protected function _getPortableSequencesList(array $sequences) : array
250
    {
251
        $sequenceDefinitions = [];
252 253

        foreach ($sequences as $sequence) {
254 255
            if ($sequence['schemaname'] !== 'public') {
                $sequenceName = $sequence['schemaname'] . '.' . $sequence['relname'];
256 257 258 259 260 261 262
            } else {
                $sequenceName = $sequence['relname'];
            }

            $sequenceDefinitions[$sequenceName] = $sequence;
        }

263
        $list = [];
264 265 266 267 268 269 270 271

        foreach ($this->filterAssetNames(array_keys($sequenceDefinitions)) as $sequenceName) {
            $list[] = $this->_getPortableSequenceDefinition($sequenceDefinitions[$sequenceName]);
        }

        return $list;
    }

272 273 274
    /**
     * {@inheritdoc}
     */
275
    protected function getPortableNamespaceDefinition(array $namespace) : string
276 277 278 279
    {
        return $namespace['nspname'];
    }

Benjamin Morel's avatar
Benjamin Morel committed
280 281 282
    /**
     * {@inheritdoc}
     */
283
    protected function _getPortableSequenceDefinition(array $sequence) : Sequence
284
    {
285
        if ($sequence['schemaname'] !== 'public') {
286
            $sequenceName = $sequence['schemaname'] . '.' . $sequence['relname'];
287 288 289 290
        } else {
            $sequenceName = $sequence['relname'];
        }

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

295 296
            $sequence += $data;
        }
Benjamin Morel's avatar
Benjamin Morel committed
297

298
        return new Sequence($sequenceName, (int) $sequence['increment_by'], (int) $sequence['min_value']);
romanb's avatar
romanb committed
299 300
    }

Benjamin Morel's avatar
Benjamin Morel committed
301 302 303
    /**
     * {@inheritdoc}
     */
304
    protected function _getPortableTableColumnDefinition(array $tableColumn) : Column
305 306 307
    {
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);

308 309 310 311 312
        $length = null;

        if (in_array(strtolower($tableColumn['type']), ['varchar', 'bpchar'], true)
            && preg_match('/\((\d*)\)/', $tableColumn['complete_type'], $matches)) {
            $length = (int) $matches[1];
313
        }
314

315
        $matches = [];
316 317

        $autoincrement = false;
Michael Moravec's avatar
Michael Moravec committed
318
        if ($tableColumn['default'] !== null && preg_match("/^nextval\('(.*)'(::.*)?\)$/", $tableColumn['default'], $matches)) {
319
            $tableColumn['sequence'] = $matches[1];
320 321
            $tableColumn['default']  = null;
            $autoincrement           = true;
322
        }
323

Michael Moravec's avatar
Michael Moravec committed
324 325 326 327 328 329
        if ($tableColumn['default'] !== null) {
            if (preg_match("/^['(](.*)[')]::/", $tableColumn['default'], $matches)) {
                $tableColumn['default'] = $matches[1];
            } elseif (preg_match('/^NULL::/', $tableColumn['default'])) {
                $tableColumn['default'] = null;
            }
330
        }
331

332
        if ($length === -1 && isset($tableColumn['atttypmod'])) {
333 334
            $length = $tableColumn['atttypmod'] - 4;
        }
335

336
        if ((int) $length <= 0) {
337 338
            $length = null;
        }
339 340

        $fixed = false;
341

342
        if (! isset($tableColumn['name'])) {
343 344
            $tableColumn['name'] = '';
        }
345 346

        $precision = null;
347
        $scale     = 0;
348
        $jsonb     = null;
349

350
        $dbType = strtolower($tableColumn['type']);
Michael Moravec's avatar
Michael Moravec committed
351 352 353 354
        if ($tableColumn['domain_type'] !== null
            && strlen($tableColumn['domain_type'])
            && ! $this->_platform->hasDoctrineTypeMappingFor($tableColumn['type'])
        ) {
355
            $dbType                       = strtolower($tableColumn['domain_type']);
356 357
            $tableColumn['complete_type'] = $tableColumn['domain_complete_type'];
        }
358

359 360
        $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'])
            ?? $this->_platform->getDoctrineTypeMapping($dbType);
361

362 363 364
        switch ($dbType) {
            case 'smallint':
            case 'int2':
365
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
366
                $length                 = null;
367 368 369 370
                break;
            case 'int':
            case 'int4':
            case 'integer':
371
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
372
                $length                 = null;
373
                break;
374 375
            case 'bigint':
            case 'int8':
376
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
377
                $length                 = null;
378 379 380
                break;
            case 'bool':
            case 'boolean':
381 382 383 384 385 386 387 388
                if ($tableColumn['default'] === 'true') {
                    $tableColumn['default'] = true;
                }

                if ($tableColumn['default'] === 'false') {
                    $tableColumn['default'] = false;
                }

389
                $length = null;
390 391
                break;
            case 'text':
392
            case '_varchar':
393
            case 'varchar':
394
                $tableColumn['default'] = $this->parseDefaultExpression($tableColumn['default']);
395
                break;
396 397
            case 'char':
            case 'bpchar':
398
                $fixed = true;
399 400 401 402 403 404 405 406 407 408
                break;
            case 'float':
            case 'float4':
            case 'float8':
            case 'double':
            case 'double precision':
            case 'real':
            case 'decimal':
            case 'money':
            case 'numeric':
409 410
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);

411
                if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['complete_type'], $match)) {
412 413
                    $precision = (int) $match[1];
                    $scale     = (int) $match[2];
414
                    $length    = null;
415
                }
416 417 418 419
                break;
            case 'year':
                $length = null;
                break;
420 421 422 423 424

            // PostgreSQL 9.4+ only
            case 'jsonb':
                $jsonb = true;
                break;
425 426
        }

427 428 429 430
        if ($tableColumn['default'] && preg_match("('([^']+)'::)", $tableColumn['default'], $match)) {
            $tableColumn['default'] = $match[1];
        }

431
        $options = [
432 433 434 435 436 437 438
            'length'        => $length,
            'notnull'       => (bool) $tableColumn['isnotnull'],
            'default'       => $tableColumn['default'],
            'precision'     => $precision,
            'scale'         => $scale,
            'fixed'         => $fixed,
            'unsigned'      => false,
439
            'autoincrement' => $autoincrement,
440 441 442
            'comment'       => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
                ? $tableColumn['comment']
                : null,
443
        ];
444

445 446
        $column = new Column($tableColumn['field'], Type::getType($type), $options);

447
        if (isset($tableColumn['collation']) && ! empty($tableColumn['collation'])) {
448 449 450
            $column->setPlatformOption('collation', $tableColumn['collation']);
        }

451
        if ($column->getType()->getName() === Types::JSON) {
452 453 454
            $column->setPlatformOption('jsonb', $jsonb);
        }

455
        return $column;
romanb's avatar
romanb committed
456
    }
457 458 459 460 461 462 463 464 465 466

    /**
     * PostgreSQL 9.4 puts parentheses around negative numeric default values that need to be stripped eventually.
     *
     * @param mixed $defaultValue
     *
     * @return mixed
     */
    private function fixVersion94NegativeNumericDefaultValue($defaultValue)
    {
Michael Moravec's avatar
Michael Moravec committed
467
        if ($defaultValue !== null && strpos($defaultValue, '(') === 0) {
468 469 470 471 472
            return trim($defaultValue, '()');
        }

        return $defaultValue;
    }
473 474 475 476 477 478 479 480 481 482 483 484

    /**
     * Parses a default value expression as given by PostgreSQL
     */
    private function parseDefaultExpression(?string $default) : ?string
    {
        if ($default === null) {
            return $default;
        }

        return str_replace("''", "'", $default);
    }
485

486
    public function listTableDetails(string $tableName) : Table
487 488 489 490 491 492 493 494 495 496 497 498 499
    {
        $table = parent::listTableDetails($tableName);

        /** @var PostgreSqlPlatform $platform */
        $platform = $this->_platform;
        $sql      = $platform->getListTableMetadataSQL($tableName);

        $tableOptions = $this->_conn->fetchAssoc($sql);

        $table->addOption('comment', $tableOptions['table_comment']);

        return $table;
    }
500
}