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

3
namespace Doctrine\DBAL\Schema;
romanb's avatar
romanb committed
4

5
use Doctrine\DBAL\Exception\DriverException;
6
use Doctrine\DBAL\FetchMode;
7
use Doctrine\DBAL\Platforms\PostgreSqlPlatform;
8
use Doctrine\DBAL\Types\Type;
9
use Doctrine\DBAL\Types\Types;
10 11 12 13 14
use function array_change_key_case;
use function array_filter;
use function array_keys;
use function array_map;
use function array_shift;
15
use function assert;
16
use function explode;
17
use function implode;
18 19 20
use function in_array;
use function preg_match;
use function preg_replace;
21
use function sprintf;
22 23 24 25 26
use function str_replace;
use function strlen;
use function strpos;
use function strtolower;
use function trim;
Grégoire Paris's avatar
Grégoire Paris committed
27
use const CASE_LOWER;
28

romanb's avatar
romanb committed
29
/**
Benjamin Morel's avatar
Benjamin Morel committed
30
 * PostgreSQL Schema Manager.
romanb's avatar
romanb committed
31
 */
32
class PostgreSqlSchemaManager extends AbstractSchemaManager
33
{
34
    /** @var string[] */
35 36 37
    private $existingSchemaPaths;

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

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

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

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

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

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

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

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

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

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
    /**
     * {@inheritdoc}
     */
    public function dropDatabase($database)
    {
        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;
            }

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

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

            parent::dropDatabase($database);
        }
    }

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

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

145
        if (preg_match('(ON DELETE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
146 147 148
            $onDelete = $match[1];
        }

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

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

Benjamin Morel's avatar
Benjamin Morel committed
166 167 168
    /**
     * {@inheritdoc}
     */
169
    protected function _getPortableTriggerDefinition($trigger)
romanb's avatar
romanb committed
170
    {
171 172
        return $trigger['trigger_name'];
    }
romanb's avatar
romanb committed
173

Benjamin Morel's avatar
Benjamin Morel committed
174 175 176
    /**
     * {@inheritdoc}
     */
177 178
    protected function _getPortableViewDefinition($view)
    {
179
        return new View($view['schemaname'] . '.' . $view['viewname'], $view['definition']);
romanb's avatar
romanb committed
180 181
    }

Benjamin Morel's avatar
Benjamin Morel committed
182 183 184
    /**
     * {@inheritdoc}
     */
185
    protected function _getPortableUserDefinition($user)
romanb's avatar
romanb committed
186
    {
187
        return [
188
            'user' => $user['usename'],
189
            'password' => $user['passwd'],
190
        ];
romanb's avatar
romanb committed
191 192
    }

Benjamin Morel's avatar
Benjamin Morel committed
193 194 195
    /**
     * {@inheritdoc}
     */
196
    protected function _getPortableTableDefinition($table)
romanb's avatar
romanb committed
197
    {
198
        $schemas     = $this->getExistingSchemaSearchPaths();
199 200
        $firstSchema = array_shift($schemas);

201
        if ($table['schema_name'] === $firstSchema) {
202 203
            return $table['table_name'];
        }
Gabriel Caruso's avatar
Gabriel Caruso committed
204

205
        return $table['schema_name'] . '.' . $table['table_name'];
206 207
    }

208
    /**
Benjamin Morel's avatar
Benjamin Morel committed
209 210
     * {@inheritdoc}
     *
211 212
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
     */
213
    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
214
    {
215
        $buffer = [];
216
        foreach ($tableIndexes as $row) {
217
            $colNumbers    = array_map('intval', explode(' ', $row['indkey']));
218 219 220 221 222
            $columnNameSql = sprintf(
                'SELECT attnum, attname FROM pg_attribute WHERE attrelid=%d AND attnum IN (%s) ORDER BY attnum ASC',
                $row['indrelid'],
                implode(' ,', $colNumbers)
            );
223

224
            $stmt         = $this->_conn->executeQuery($columnNameSql);
225 226
            $indexColumns = $stmt->fetchAll();

227
            // required for getting the order of the columns right.
228
            foreach ($colNumbers as $colNum) {
229
                foreach ($indexColumns as $colRow) {
230 231
                    if ($colNum !== $colRow['attnum']) {
                        continue;
232
                    }
233 234 235 236 237 238 239 240

                    $buffer[] = [
                        'key_name' => $row['relname'],
                        'column_name' => trim($colRow['attname']),
                        'non_unique' => ! $row['indisunique'],
                        'primary' => $row['indisprimary'],
                        'where' => $row['where'],
                    ];
241
                }
242 243
            }
        }
Benjamin Morel's avatar
Benjamin Morel committed
244

245
        return parent::_getPortableTableIndexesList($buffer, $tableName);
246 247
    }

Benjamin Morel's avatar
Benjamin Morel committed
248 249 250
    /**
     * {@inheritdoc}
     */
251 252 253 254 255
    protected function _getPortableDatabaseDefinition($database)
    {
        return $database['datname'];
    }

256 257 258 259 260
    /**
     * {@inheritdoc}
     */
    protected function _getPortableSequencesList($sequences)
    {
261
        $sequenceDefinitions = [];
262 263

        foreach ($sequences as $sequence) {
264 265
            if ($sequence['schemaname'] !== 'public') {
                $sequenceName = $sequence['schemaname'] . '.' . $sequence['relname'];
266 267 268 269 270 271 272
            } else {
                $sequenceName = $sequence['relname'];
            }

            $sequenceDefinitions[$sequenceName] = $sequence;
        }

273
        $list = [];
274 275 276 277 278 279 280 281

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

        return $list;
    }

282 283 284 285 286 287 288 289
    /**
     * {@inheritdoc}
     */
    protected function getPortableNamespaceDefinition(array $namespace)
    {
        return $namespace['nspname'];
    }

Benjamin Morel's avatar
Benjamin Morel committed
290 291 292
    /**
     * {@inheritdoc}
     */
293 294
    protected function _getPortableSequenceDefinition($sequence)
    {
295
        if ($sequence['schemaname'] !== 'public') {
296
            $sequenceName = $sequence['schemaname'] . '.' . $sequence['relname'];
297 298 299 300
        } else {
            $sequenceName = $sequence['relname'];
        }

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

305 306
            $sequence += $data;
        }
Benjamin Morel's avatar
Benjamin Morel committed
307

308
        return new Sequence($sequenceName, (int) $sequence['increment_by'], (int) $sequence['min_value']);
romanb's avatar
romanb committed
309 310
    }

Benjamin Morel's avatar
Benjamin Morel committed
311 312 313
    /**
     * {@inheritdoc}
     */
314 315 316 317
    protected function _getPortableTableColumnDefinition($tableColumn)
    {
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);

318
        if (strtolower($tableColumn['type']) === 'varchar' || strtolower($tableColumn['type']) === 'bpchar') {
319
            // get length from varchar definition
320
            $length                = preg_replace('~.*\(([0-9]*)\).*~', '$1', $tableColumn['complete_type']);
321 322
            $tableColumn['length'] = $length;
        }
323

324
        $matches = [];
325 326

        $autoincrement = false;
327 328
        if (preg_match("/^nextval\('(.*)'(::.*)?\)$/", $tableColumn['default'], $matches)) {
            $tableColumn['sequence'] = $matches[1];
329 330
            $tableColumn['default']  = null;
            $autoincrement           = true;
331
        }
332

333
        if (preg_match("/^['(](.*)[')]::/", $tableColumn['default'], $matches)) {
334
            $tableColumn['default'] = $matches[1];
335
        } elseif (preg_match('/^NULL::/', $tableColumn['default'])) {
336 337
            $tableColumn['default'] = null;
        }
338

339
        $length = $tableColumn['length'] ?? null;
340
        if ($length === '-1' && isset($tableColumn['atttypmod'])) {
341 342
            $length = $tableColumn['atttypmod'] - 4;
        }
Grégoire Paris's avatar
Grégoire Paris committed
343

344
        if ((int) $length <= 0) {
345 346
            $length = null;
        }
Grégoire Paris's avatar
Grégoire Paris committed
347

348
        $fixed = null;
349

350
        if (! isset($tableColumn['name'])) {
351 352
            $tableColumn['name'] = '';
        }
353 354

        $precision = null;
355 356
        $scale     = null;
        $jsonb     = null;
357

358
        $dbType = strtolower($tableColumn['type']);
359 360
        if (strlen($tableColumn['domain_type']) && ! $this->_platform->hasDoctrineTypeMappingFor($tableColumn['type'])) {
            $dbType                       = strtolower($tableColumn['domain_type']);
361 362
            $tableColumn['complete_type'] = $tableColumn['domain_complete_type'];
        }
363

364 365
        $type                   = $this->_platform->getDoctrineTypeMapping($dbType);
        $type                   = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
366 367
        $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);

368 369 370
        switch ($dbType) {
            case 'smallint':
            case 'int2':
371
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
372
                $length                 = null;
373
                break;
Sergei Morozov's avatar
Sergei Morozov committed
374

375 376 377
            case 'int':
            case 'int4':
            case 'integer':
378
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
379
                $length                 = null;
380
                break;
Sergei Morozov's avatar
Sergei Morozov committed
381

382 383
            case 'bigint':
            case 'int8':
384
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
385
                $length                 = null;
386
                break;
Sergei Morozov's avatar
Sergei Morozov committed
387

388 389
            case 'bool':
            case 'boolean':
390 391 392 393 394 395 396 397
                if ($tableColumn['default'] === 'true') {
                    $tableColumn['default'] = true;
                }

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

398
                $length = null;
399
                break;
Sergei Morozov's avatar
Sergei Morozov committed
400

401
            case 'text':
402
            case '_varchar':
403
            case 'varchar':
404 405 406
                $tableColumn['default'] = $this->parseDefaultExpression($tableColumn['default']);
                $fixed                  = false;
                break;
407 408
            case 'interval':
                $fixed = false;
409
                break;
Sergei Morozov's avatar
Sergei Morozov committed
410

411 412
            case 'char':
            case 'bpchar':
413
                $fixed = true;
414
                break;
Sergei Morozov's avatar
Sergei Morozov committed
415

416 417 418 419 420 421 422 423 424
            case 'float':
            case 'float4':
            case 'float8':
            case 'double':
            case 'double precision':
            case 'real':
            case 'decimal':
            case 'money':
            case 'numeric':
425 426
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);

427
                if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['complete_type'], $match)) {
428
                    $precision = $match[1];
429 430
                    $scale     = $match[2];
                    $length    = null;
431
                }
Grégoire Paris's avatar
Grégoire Paris committed
432

433
                break;
Sergei Morozov's avatar
Sergei Morozov committed
434

435 436 437
            case 'year':
                $length = null;
                break;
438 439 440 441 442

            // PostgreSQL 9.4+ only
            case 'jsonb':
                $jsonb = true;
                break;
443 444
        }

445 446 447 448
        if ($tableColumn['default'] && preg_match("('([^']+)'::)", $tableColumn['default'], $match)) {
            $tableColumn['default'] = $match[1];
        }

449
        $options = [
450 451 452 453 454 455 456
            'length'        => $length,
            'notnull'       => (bool) $tableColumn['isnotnull'],
            'default'       => $tableColumn['default'],
            'precision'     => $precision,
            'scale'         => $scale,
            'fixed'         => $fixed,
            'unsigned'      => false,
457
            'autoincrement' => $autoincrement,
458 459 460
            'comment'       => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
                ? $tableColumn['comment']
                : null,
461
        ];
462

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

465
        if (isset($tableColumn['collation']) && ! empty($tableColumn['collation'])) {
466 467 468
            $column->setPlatformOption('collation', $tableColumn['collation']);
        }

469
        if (in_array($column->getType()->getName(), [Types::JSON_ARRAY, Types::JSON], true)) {
470 471 472
            $column->setPlatformOption('jsonb', $jsonb);
        }

473
        return $column;
romanb's avatar
romanb committed
474
    }
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490

    /**
     * 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)
    {
        if (strpos($defaultValue, '(') === 0) {
            return trim($defaultValue, '()');
        }

        return $defaultValue;
    }
491 492 493 494 495 496 497 498 499 500 501 502

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

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

Grégoire Paris's avatar
Grégoire Paris committed
504 505 506
    /**
     * {@inheritdoc}
     */
507 508 509 510 511
    public function listTableDetails($tableName) : Table
    {
        $table = parent::listTableDetails($tableName);

        $platform = $this->_platform;
Grégoire Paris's avatar
Grégoire Paris committed
512 513
        assert($platform instanceof PostgreSqlPlatform);
        $sql = $platform->getListTableMetadataSQL($tableName);
514 515 516

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

517 518 519
        if ($tableOptions !== false) {
            $table->addOption('comment', $tableOptions['table_comment']);
        }
520 521 522

        return $table;
    }
523
}