PostgreSqlSchemaManager.php 16.1 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\PostgreSQL94Platform;
8
use Doctrine\DBAL\Types\Type;
9
use Doctrine\DBAL\Types\Types;
10 11 12 13 14 15
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;
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

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) : bool {
97
            return in_array($v, $names, true);
98 99
        });
    }
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
            assert($this->_platform instanceof PostgreSQL94Platform);
118

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 142 143 144 145
        if (preg_match(
            '(ON UPDATE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))',
            $tableForeignKey['condef'],
            $match
        ) === 1) {
146
            $onUpdate = $match[1];
romanb's avatar
romanb committed
147
        }
148 149 150 151 152
        if (preg_match(
            '(ON DELETE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))',
            $tableForeignKey['condef'],
            $match
        ) === 1) {
153 154 155
            $onDelete = $match[1];
        }

156 157 158 159 160
        if (preg_match(
            '/FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)/',
            $tableForeignKey['condef'],
            $values
        ) === 1) {
161 162
            // PostgreSQL returns identifiers that are keywords with quotes, we need them later, don't get
            // the idea to trim them here.
163 164 165
            $localColumns   = array_map('trim', explode(',', $values[1]));
            $foreignColumns = array_map('trim', explode(',', $values[3]));
            $foreignTable   = $values[2];
166 167
        }

168
        return new ForeignKeyConstraint(
169 170 171 172
            $localColumns,
            $foreignTable,
            $foreignColumns,
            $tableForeignKey['conname'],
173
            ['onUpdate' => $onUpdate, 'onDelete' => $onDelete]
174
        );
romanb's avatar
romanb committed
175 176
    }

Benjamin Morel's avatar
Benjamin Morel committed
177 178 179
    /**
     * {@inheritdoc}
     */
180
    protected function _getPortableTriggerDefinition($trigger)
romanb's avatar
romanb committed
181
    {
182 183
        return $trigger['trigger_name'];
    }
romanb's avatar
romanb committed
184

Benjamin Morel's avatar
Benjamin Morel committed
185 186 187
    /**
     * {@inheritdoc}
     */
188 189
    protected function _getPortableViewDefinition($view)
    {
190
        return new View($view['schemaname'] . '.' . $view['viewname'], $view['definition']);
romanb's avatar
romanb committed
191 192
    }

Benjamin Morel's avatar
Benjamin Morel committed
193 194 195
    /**
     * {@inheritdoc}
     */
196
    protected function _getPortableUserDefinition($user)
romanb's avatar
romanb committed
197
    {
198
        return [
199
            'user' => $user['usename'],
200
            'password' => $user['passwd'],
201
        ];
romanb's avatar
romanb committed
202 203
    }

Benjamin Morel's avatar
Benjamin Morel committed
204 205 206
    /**
     * {@inheritdoc}
     */
207
    protected function _getPortableTableDefinition($table)
romanb's avatar
romanb committed
208
    {
209
        $schemas     = $this->getExistingSchemaSearchPaths();
210 211
        $firstSchema = array_shift($schemas);

212
        if ($table['schema_name'] === $firstSchema) {
213 214
            return $table['table_name'];
        }
Gabriel Caruso's avatar
Gabriel Caruso committed
215

216
        return $table['schema_name'] . '.' . $table['table_name'];
217 218
    }

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

235
            $stmt         = $this->_conn->executeQuery($columnNameSql);
236 237
            $indexColumns = $stmt->fetchAll();

238
            // required for getting the order of the columns right.
239
            foreach ($colNumbers as $colNum) {
240
                foreach ($indexColumns as $colRow) {
241 242
                    if ($colNum !== $colRow['attnum']) {
                        continue;
243
                    }
244 245 246 247 248 249 250 251

                    $buffer[] = [
                        'key_name' => $row['relname'],
                        'column_name' => trim($colRow['attname']),
                        'non_unique' => ! $row['indisunique'],
                        'primary' => $row['indisprimary'],
                        'where' => $row['where'],
                    ];
252
                }
253 254
            }
        }
Benjamin Morel's avatar
Benjamin Morel committed
255

256
        return parent::_getPortableTableIndexesList($buffer, $tableName);
257 258
    }

Benjamin Morel's avatar
Benjamin Morel committed
259 260 261
    /**
     * {@inheritdoc}
     */
262 263 264 265 266
    protected function _getPortableDatabaseDefinition($database)
    {
        return $database['datname'];
    }

267 268 269 270 271
    /**
     * {@inheritdoc}
     */
    protected function _getPortableSequencesList($sequences)
    {
272
        $sequenceDefinitions = [];
273 274

        foreach ($sequences as $sequence) {
275 276
            if ($sequence['schemaname'] !== 'public') {
                $sequenceName = $sequence['schemaname'] . '.' . $sequence['relname'];
277 278 279 280 281 282 283
            } else {
                $sequenceName = $sequence['relname'];
            }

            $sequenceDefinitions[$sequenceName] = $sequence;
        }

284
        $list = [];
285 286 287 288 289 290 291 292

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

        return $list;
    }

293 294 295 296 297 298 299 300
    /**
     * {@inheritdoc}
     */
    protected function getPortableNamespaceDefinition(array $namespace)
    {
        return $namespace['nspname'];
    }

Benjamin Morel's avatar
Benjamin Morel committed
301 302 303
    /**
     * {@inheritdoc}
     */
304 305
    protected function _getPortableSequenceDefinition($sequence)
    {
306
        if ($sequence['schemaname'] !== 'public') {
307
            $sequenceName = $sequence['schemaname'] . '.' . $sequence['relname'];
308 309 310 311
        } else {
            $sequenceName = $sequence['relname'];
        }

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

316 317
            $sequence += $data;
        }
Benjamin Morel's avatar
Benjamin Morel committed
318

319
        return new Sequence($sequenceName, (int) $sequence['increment_by'], (int) $sequence['min_value']);
romanb's avatar
romanb committed
320 321
    }

Benjamin Morel's avatar
Benjamin Morel committed
322 323 324
    /**
     * {@inheritdoc}
     */
325 326 327 328
    protected function _getPortableTableColumnDefinition($tableColumn)
    {
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);

329
        if (strtolower($tableColumn['type']) === 'varchar' || strtolower($tableColumn['type']) === 'bpchar') {
330
            // get length from varchar definition
331
            $length                = preg_replace('~.*\(([0-9]*)\).*~', '$1', $tableColumn['complete_type']);
332 333
            $tableColumn['length'] = $length;
        }
334

335
        $matches = [];
336 337

        $autoincrement = false;
338
        if (preg_match("/^nextval\('(.*)'(::.*)?\)$/", $tableColumn['default'], $matches) === 1) {
339
            $tableColumn['sequence'] = $matches[1];
340 341
            $tableColumn['default']  = null;
            $autoincrement           = true;
342
        }
343

344
        if (preg_match("/^['(](.*)[')]::/", $tableColumn['default'], $matches) === 1) {
345
            $tableColumn['default'] = $matches[1];
346
        } elseif (preg_match('/^NULL::/', $tableColumn['default']) === 1) {
347 348
            $tableColumn['default'] = null;
        }
349

350
        $length = $tableColumn['length'] ?? null;
351
        if ($length === '-1' && isset($tableColumn['atttypmod'])) {
352 353
            $length = $tableColumn['atttypmod'] - 4;
        }
354
        if ((int) $length <= 0) {
355 356
            $length = null;
        }
357
        $fixed = null;
358

359
        if (! isset($tableColumn['name'])) {
360 361
            $tableColumn['name'] = '';
        }
362 363

        $precision = null;
364 365
        $scale     = null;
        $jsonb     = null;
366

367
        $dbType = strtolower($tableColumn['type']);
368 369
        if (strlen($tableColumn['domain_type']) > 0
            && ! $this->_platform->hasDoctrineTypeMappingFor($tableColumn['type'])) {
370
            $dbType                       = strtolower($tableColumn['domain_type']);
371 372
            $tableColumn['complete_type'] = $tableColumn['domain_complete_type'];
        }
373

374 375
        $type                   = $this->_platform->getDoctrineTypeMapping($dbType);
        $type                   = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
376 377
        $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);

378 379 380
        switch ($dbType) {
            case 'smallint':
            case 'int2':
381
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
382
                $length                 = null;
383 384 385 386
                break;
            case 'int':
            case 'int4':
            case 'integer':
387
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
388
                $length                 = null;
389
                break;
390 391
            case 'bigint':
            case 'int8':
392
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
393
                $length                 = null;
394 395 396
                break;
            case 'bool':
            case 'boolean':
397 398 399 400 401 402 403 404
                if ($tableColumn['default'] === 'true') {
                    $tableColumn['default'] = true;
                }

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

405
                $length = null;
406 407
                break;
            case 'text':
408
            case '_varchar':
409
            case 'varchar':
410 411 412
                $tableColumn['default'] = $this->parseDefaultExpression($tableColumn['default']);
                $fixed                  = false;
                break;
413 414
            case 'interval':
                $fixed = false;
415
                break;
416 417
            case 'char':
            case 'bpchar':
418
                $fixed = true;
419 420 421 422 423 424 425 426 427 428
                break;
            case 'float':
            case 'float4':
            case 'float8':
            case 'double':
            case 'double precision':
            case 'real':
            case 'decimal':
            case 'money':
            case 'numeric':
429 430
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);

431 432 433 434 435
                if (preg_match(
                    '([A-Za-z]+\(([0-9]+)\,([0-9]+)\))',
                    $tableColumn['complete_type'],
                    $match
                ) === 1) {
436
                    $precision = $match[1];
437 438
                    $scale     = $match[2];
                    $length    = null;
439
                }
440 441 442 443
                break;
            case 'year':
                $length = null;
                break;
444 445 446 447 448

            // PostgreSQL 9.4+ only
            case 'jsonb':
                $jsonb = true;
                break;
449 450
        }

451 452 453 454 455
        if ($tableColumn['default'] !== null && preg_match(
            "('([^']+)'::)",
            $tableColumn['default'],
            $match
        ) === 1) {
456 457 458
            $tableColumn['default'] = $match[1];
        }

459
        $options = [
460 461 462 463 464 465 466
            'length'        => $length,
            'notnull'       => (bool) $tableColumn['isnotnull'],
            'default'       => $tableColumn['default'],
            'precision'     => $precision,
            'scale'         => $scale,
            'fixed'         => $fixed,
            'unsigned'      => false,
467
            'autoincrement' => $autoincrement,
468 469 470
            'comment'       => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
                ? $tableColumn['comment']
                : null,
471
        ];
472

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

475
        if (isset($tableColumn['collation']) && ! empty($tableColumn['collation'])) {
476 477 478
            $column->setPlatformOption('collation', $tableColumn['collation']);
        }

479
        if (in_array($column->getType()->getName(), [Types::JSON_ARRAY, Types::JSON], true)) {
480 481 482
            $column->setPlatformOption('jsonb', $jsonb);
        }

483
        return $column;
romanb's avatar
romanb committed
484
    }
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500

    /**
     * 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;
    }
501 502 503 504 505 506 507 508 509 510 511 512

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

        return str_replace("''", "'", $default);
    }
513 514 515 516 517

    public function listTableDetails($tableName) : Table
    {
        $table = parent::listTableDetails($tableName);

518
        /** @var PostgreSQL94Platform $platform */
519 520 521 522 523
        $platform = $this->_platform;
        $sql      = $platform->getListTableMetadataSQL($tableName);

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

524 525 526
        if ($tableOptions !== false) {
            $table->addOption('comment', $tableOptions['table_comment']);
        }
527 528 529

        return $table;
    }
530
}