PostgreSqlSchemaManager.php 15.7 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 15
use function array_change_key_case;
use function array_filter;
use function array_keys;
use function array_map;
use function array_shift;
16
use function assert;
17
use function explode;
18
use function implode;
19 20 21
use function in_array;
use function preg_match;
use function preg_replace;
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

Grégoire Paris's avatar
Grégoire Paris committed
29
use const CASE_LOWER;
30

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

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

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

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

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

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

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

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

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

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

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    /**
     * {@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;
            }

119 120
            assert($this->_platform instanceof PostgreSqlPlatform);

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

            parent::dropDatabase($database);
        }
    }

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

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

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

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

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

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

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

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

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

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

207
        return $table['schema_name'] . '.' . $table['table_name'];
208 209
    }

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

226
            $indexColumns = $this->_conn->fetchAllAssociative($columnNameSql);
227

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

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

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

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

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

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

            $sequenceDefinitions[$sequenceName] = $sequence;
        }

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

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

        return $list;
    }

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

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

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

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

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

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

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

325
        $matches = [];
326 327

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

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

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

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

349
        $fixed = null;
350

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * 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;
    }
492 493 494 495

    /**
     * Parses a default value expression as given by PostgreSQL
     */
496
    private function parseDefaultExpression(?string $default): ?string
497 498 499 500 501 502 503
    {
        if ($default === null) {
            return $default;
        }

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

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

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

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

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

        return $table;
    }
524
}