PostgreSqlSchemaManager.php 14.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 10 11 12 13 14
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;
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 27
use function str_replace;
use function stripos;
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) {
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 137 138 139
        $onUpdate       = null;
        $onDelete       = null;
        $localColumns   = null;
        $foreignColumns = null;
        $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
        }
144
        if (preg_match('(ON DELETE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
145 146 147
            $onDelete = $match[1];
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            $sequenceDefinitions[$sequenceName] = $sequence;
        }

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

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

        return $list;
    }

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

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

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

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

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

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

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

323
        $matches = [];
324 325

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

332
        if (preg_match("/^['(](.*)[')]::.*$/", $tableColumn['default'], $matches)) {
333 334 335
            $tableColumn['default'] = $matches[1];
        }

336
        if (stripos($tableColumn['default'], 'NULL') === 0) {
337 338
            $tableColumn['default'] = null;
        }
339

340
        $length = $tableColumn['length'] ?? null;
341
        if ($length === '-1' && isset($tableColumn['atttypmod'])) {
342 343
            $length = $tableColumn['atttypmod'] - 4;
        }
344
        if ((int) $length <= 0) {
345 346
            $length = null;
        }
347
        $fixed = null;
348

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

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

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

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

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

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

394
                $length = null;
395 396
                break;
            case 'text':
397 398
                $fixed = false;
                break;
399
            case 'varchar':
400
            case 'interval':
401
            case '_varchar':
402
                $fixed = false;
403
                break;
404 405
            case 'char':
            case 'bpchar':
406
                $fixed = true;
407 408 409 410 411 412 413 414 415 416
                break;
            case 'float':
            case 'float4':
            case 'float8':
            case 'double':
            case 'double precision':
            case 'real':
            case 'decimal':
            case 'money':
            case 'numeric':
417 418
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);

419
                if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['complete_type'], $match)) {
420
                    $precision = $match[1];
421 422
                    $scale     = $match[2];
                    $length    = null;
423
                }
424 425 426 427
                break;
            case 'year':
                $length = null;
                break;
428 429 430 431 432

            // PostgreSQL 9.4+ only
            case 'jsonb':
                $jsonb = true;
                break;
433 434
        }

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

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

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

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

459
        if (in_array($column->getType()->getName(), [Type::JSON_ARRAY, Type::JSON], true)) {
460 461 462
            $column->setPlatformOption('jsonb', $jsonb);
        }

463
        return $column;
romanb's avatar
romanb committed
464
    }
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480

    /**
     * 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;
    }
481
}