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
use function array_change_key_case;
use function array_filter;
use function array_keys;
use function array_map;
use function array_shift;
17
use function assert;
18
use function explode;
19
use function implode;
20 21
use function in_array;
use function preg_match;
22
use function sprintf;
23 24 25 26 27
use function str_replace;
use function strlen;
use function strpos;
use function strtolower;
use function trim;
28
use const CASE_LOWER;
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
    public function dropDatabase(string $database) : void
101 102 103 104 105 106 107 108 109 110 111 112
    {
        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;
            }

113 114
            assert($this->_platform instanceof PostgreSqlPlatform);

115
            $this->_execSql(
116
                [
117 118
                    $this->_platform->getDisallowDatabaseConnectionsSQL($database),
                    $this->_platform->getCloseActiveDatabaseConnectionsSQL($database),
119
                ]
120 121 122 123 124 125
            );

            parent::dropDatabase($database);
        }
    }

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

137
        if (preg_match('(ON UPDATE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
138
            $onUpdate = $match[1];
romanb's avatar
romanb committed
139
        }
140

141
        if (preg_match('(ON DELETE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
142 143 144
            $onDelete = $match[1];
        }

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

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

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

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

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

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

193
        return $table['schema_name'] . '.' . $table['table_name'];
194 195
    }

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

212
            $stmt         = $this->_conn->executeQuery($columnNameSql);
213 214
            $indexColumns = $stmt->fetchAll();

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

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

233
        return parent::_getPortableTableIndexesList($buffer, $tableName);
234 235
    }

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

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

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

            $sequenceDefinitions[$sequenceName] = $sequence;
        }

261
        $list = [];
262 263 264 265 266 267 268 269

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

        return $list;
    }

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

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

289
        if (! isset($sequence['increment_by'], $sequence['min_value'])) {
290
            /** @var string[] $data */
291
            $data = $this->_conn->fetchAssoc('SELECT min_value, increment_by FROM ' . $this->_platform->quoteIdentifier($sequenceName));
292

293 294
            $sequence += $data;
        }
Benjamin Morel's avatar
Benjamin Morel committed
295

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

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

306 307 308 309 310
        $length = null;

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

313
        $matches = [];
314 315

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

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

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

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

        $fixed = false;
339

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

        $precision = null;
345
        $scale     = 0;
346
        $jsonb     = null;
347

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

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

360 361 362
        switch ($dbType) {
            case 'smallint':
            case 'int2':
363
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
364
                $length                 = null;
365
                break;
366

367 368 369
            case 'int':
            case 'int4':
            case 'integer':
370
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
371
                $length                 = null;
372
                break;
373

374 375
            case 'bigint':
            case 'int8':
376
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
377
                $length                 = null;
378
                break;
379

380 381
            case 'bool':
            case 'boolean':
382 383 384 385 386 387 388 389
                if ($tableColumn['default'] === 'true') {
                    $tableColumn['default'] = true;
                }

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

390
                $length = null;
391
                break;
392

393
            case 'text':
394
            case '_varchar':
395
            case 'varchar':
396
                $tableColumn['default'] = $this->parseDefaultExpression($tableColumn['default']);
397
                break;
398

399 400
            case 'char':
            case 'bpchar':
401
                $fixed = true;
402
                break;
403

404 405 406 407 408 409 410 411 412
            case 'float':
            case 'float4':
            case 'float8':
            case 'double':
            case 'double precision':
            case 'real':
            case 'decimal':
            case 'money':
            case 'numeric':
413 414
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);

415
                if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['complete_type'], $match)) {
416 417
                    $precision = (int) $match[1];
                    $scale     = (int) $match[2];
418
                    $length    = null;
419
                }
420

421
                break;
422

423 424 425
            case 'year':
                $length = null;
                break;
426 427 428 429 430

            // PostgreSQL 9.4+ only
            case 'jsonb':
                $jsonb = true;
                break;
431 432
        }

433 434 435 436
        if ($tableColumn['default'] && preg_match("('([^']+)'::)", $tableColumn['default'], $match)) {
            $tableColumn['default'] = $match[1];
        }

437
        $options = [
438 439 440 441 442 443 444
            'length'        => $length,
            'notnull'       => (bool) $tableColumn['isnotnull'],
            'default'       => $tableColumn['default'],
            'precision'     => $precision,
            'scale'         => $scale,
            'fixed'         => $fixed,
            'unsigned'      => false,
445
            'autoincrement' => $autoincrement,
446 447 448
            'comment'       => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
                ? $tableColumn['comment']
                : null,
449
        ];
450

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

453
        if (isset($tableColumn['collation']) && ! empty($tableColumn['collation'])) {
454 455 456
            $column->setPlatformOption('collation', $tableColumn['collation']);
        }

457
        if ($column->getType()->getName() === Types::JSON) {
458 459 460
            $column->setPlatformOption('jsonb', $jsonb);
        }

461
        return $column;
romanb's avatar
romanb committed
462
    }
463 464 465 466 467 468 469 470 471 472

    /**
     * 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
473
        if ($defaultValue !== null && strpos($defaultValue, '(') === 0) {
474 475 476 477 478
            return trim($defaultValue, '()');
        }

        return $defaultValue;
    }
479 480 481 482 483 484 485 486 487 488 489 490

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

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

492
    public function listTableDetails(string $tableName) : Table
493 494 495 496
    {
        $table = parent::listTableDetails($tableName);

        $platform = $this->_platform;
497 498
        assert($platform instanceof PostgreSqlPlatform);
        $sql = $platform->getListTableMetadataSQL($tableName);
499 500 501 502 503 504 505

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

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

        return $table;
    }
506
}