PostgreSqlSchemaManager.php 15.1 KB
Newer Older
romanb's avatar
romanb committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
Benjamin Eberlei's avatar
Benjamin Eberlei committed
16
 * and is licensed under the MIT license. For more information, see
romanb's avatar
romanb committed
17
 * <http://www.doctrine-project.org>.
romanb's avatar
romanb committed
18 19
 */

20
namespace Doctrine\DBAL\Schema;
romanb's avatar
romanb committed
21

22
use Doctrine\DBAL\Exception\DriverException;
23 24
use Doctrine\DBAL\Types\Type;

romanb's avatar
romanb committed
25
/**
Benjamin Morel's avatar
Benjamin Morel committed
26
 * PostgreSQL Schema Manager.
romanb's avatar
romanb committed
27
 *
Benjamin Morel's avatar
Benjamin Morel committed
28 29 30 31
 * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
 * @author Benjamin Eberlei <kontakt@beberlei.de>
 * @since  2.0
romanb's avatar
romanb committed
32
 */
33
class PostgreSqlSchemaManager extends AbstractSchemaManager
34
{
35 36 37 38 39 40
    /**
     * @var array
     */
    private $existingSchemaPaths;

    /**
Benjamin Morel's avatar
Benjamin Morel committed
41
     * Gets all the existing schema names.
42 43 44 45 46
     *
     * @return array
     */
    public function getSchemaNames()
    {
47
        $rows = $this->_conn->fetchAll("SELECT nspname as schema_name FROM pg_namespace WHERE nspname !~ '^pg_.*' and nspname != 'information_schema'");
Benjamin Morel's avatar
Benjamin Morel committed
48

Steve Müller's avatar
Steve Müller committed
49
        return array_map(function ($v) { return $v['schema_name']; }, $rows);
50 51 52
    }

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

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

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

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

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

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

        $this->existingSchemaPaths = array_filter($paths, function ($v) use ($names) {
            return in_array($v, $names);
        });
    }
103

104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    /**
     * {@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;
            }

            $this->_execSql(
                array(
                    $this->_platform->getDisallowDatabaseConnectionsSQL($database),
                    $this->_platform->getCloseActiveDatabaseConnectionsSQL($database),
                )
            );

            parent::dropDatabase($database);
        }
    }

Benjamin Morel's avatar
Benjamin Morel committed
131 132 133
    /**
     * {@inheritdoc}
     */
134
    protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
romanb's avatar
romanb committed
135
    {
136 137
        $onUpdate = null;
        $onDelete = null;
138

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

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

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

Benjamin Morel's avatar
Benjamin Morel committed
160 161 162
    /**
     * {@inheritdoc}
     */
163
    protected function _getPortableTriggerDefinition($trigger)
romanb's avatar
romanb committed
164
    {
165 166
        return $trigger['trigger_name'];
    }
romanb's avatar
romanb committed
167

Benjamin Morel's avatar
Benjamin Morel committed
168 169 170
    /**
     * {@inheritdoc}
     */
171 172
    protected function _getPortableViewDefinition($view)
    {
173
        return new View($view['schemaname'].'.'.$view['viewname'], $view['definition']);
romanb's avatar
romanb committed
174 175
    }

Benjamin Morel's avatar
Benjamin Morel committed
176 177 178
    /**
     * {@inheritdoc}
     */
179
    protected function _getPortableUserDefinition($user)
romanb's avatar
romanb committed
180
    {
181 182 183 184
        return array(
            'user' => $user['usename'],
            'password' => $user['passwd']
        );
romanb's avatar
romanb committed
185 186
    }

Benjamin Morel's avatar
Benjamin Morel committed
187 188 189
    /**
     * {@inheritdoc}
     */
190
    protected function _getPortableTableDefinition($table)
romanb's avatar
romanb committed
191
    {
192 193 194 195
        $schemas = $this->getExistingSchemaSearchPaths();
        $firstSchema = array_shift($schemas);

        if ($table['schema_name'] == $firstSchema) {
196 197 198 199
            return $table['table_name'];
        } else {
            return $table['schema_name'] . "." . $table['table_name'];
        }
200 201
    }

202
    /**
Benjamin Morel's avatar
Benjamin Morel committed
203 204
     * {@inheritdoc}
     *
205 206 207 208
     * @license New BSD License
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
     */
    protected function _getPortableTableIndexesList($tableIndexes, $tableName=null)
209
    {
210
        $buffer = array();
211
        foreach ($tableIndexes as $row) {
212 213
            $colNumbers = explode(' ', $row['indkey']);
            $colNumbersSql = 'IN (' . join(' ,', $colNumbers) . ' )';
214 215
            $columnNameSql = "SELECT attnum, attname FROM pg_attribute
                WHERE attrelid={$row['indrelid']} AND attnum $colNumbersSql ORDER BY attnum ASC;";
216

217
            $stmt = $this->_conn->executeQuery($columnNameSql);
218 219
            $indexColumns = $stmt->fetchAll();

220
            // required for getting the order of the columns right.
221
            foreach ($colNumbers as $colNum) {
222
                foreach ($indexColumns as $colRow) {
223 224 225
                    if ($colNum == $colRow['attnum']) {
                        $buffer[] = array(
                            'key_name' => $row['relname'],
226
                            'column_name' => trim($colRow['attname']),
227
                            'non_unique' => !$row['indisunique'],
228 229
                            'primary' => $row['indisprimary'],
                            'where' => $row['where'],
230 231 232
                        );
                    }
                }
233 234
            }
        }
Benjamin Morel's avatar
Benjamin Morel committed
235

236
        return parent::_getPortableTableIndexesList($buffer, $tableName);
237 238
    }

Benjamin Morel's avatar
Benjamin Morel committed
239 240 241
    /**
     * {@inheritdoc}
     */
242 243 244 245 246
    protected function _getPortableDatabaseDefinition($database)
    {
        return $database['datname'];
    }

247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
    /**
     * {@inheritdoc}
     */
    protected function _getPortableSequencesList($sequences)
    {
        $sequenceDefinitions = array();

        foreach ($sequences as $sequence) {
            if ($sequence['schemaname'] != 'public') {
                $sequenceName = $sequence['schemaname'] . "." . $sequence['relname'];
            } else {
                $sequenceName = $sequence['relname'];
            }

            $sequenceDefinitions[$sequenceName] = $sequence;
        }

        $list = array();

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

        return $list;
    }

273 274 275 276 277 278 279 280
    /**
     * {@inheritdoc}
     */
    protected function getPortableNamespaceDefinition(array $namespace)
    {
        return $namespace['nspname'];
    }

Benjamin Morel's avatar
Benjamin Morel committed
281 282 283
    /**
     * {@inheritdoc}
     */
284 285
    protected function _getPortableSequenceDefinition($sequence)
    {
286 287 288 289 290 291
        if ($sequence['schemaname'] != 'public') {
            $sequenceName = $sequence['schemaname'] . "." . $sequence['relname'];
        } else {
            $sequenceName = $sequence['relname'];
        }

292
        $data = $this->_conn->fetchAll('SELECT min_value, increment_by FROM ' . $this->_platform->quoteIdentifier($sequenceName));
Benjamin Morel's avatar
Benjamin Morel committed
293

294
        return new Sequence($sequenceName, $data[0]['increment_by'], $data[0]['min_value']);
romanb's avatar
romanb committed
295 296
    }

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

304
        if (strtolower($tableColumn['type']) === 'varchar' || strtolower($tableColumn['type']) === 'bpchar') {
305 306 307 308
            // get length from varchar definition
            $length = preg_replace('~.*\(([0-9]*)\).*~', '$1', $tableColumn['complete_type']);
            $tableColumn['length'] = $length;
        }
309

310
        $matches = array();
311 312

        $autoincrement = false;
313 314 315
        if (preg_match("/^nextval\('(.*)'(::.*)?\)$/", $tableColumn['default'], $matches)) {
            $tableColumn['sequence'] = $matches[1];
            $tableColumn['default'] = null;
316
            $autoincrement = true;
317
        }
318

319
        if (preg_match("/^['(](.*)[')]::.*$/", $tableColumn['default'], $matches)) {
320 321 322
            $tableColumn['default'] = $matches[1];
        }

323
        if (stripos($tableColumn['default'], 'NULL') === 0) {
324 325
            $tableColumn['default'] = null;
        }
326

327 328 329 330
        $length = (isset($tableColumn['length'])) ? $tableColumn['length'] : null;
        if ($length == '-1' && isset($tableColumn['atttypmod'])) {
            $length = $tableColumn['atttypmod'] - 4;
        }
331
        if ((int) $length <= 0) {
332 333
            $length = null;
        }
334
        $fixed = null;
335 336

        if (!isset($tableColumn['name'])) {
337 338
            $tableColumn['name'] = '';
        }
339 340 341

        $precision = null;
        $scale = null;
342
        $jsonb = null;
343

344
        $dbType = strtolower($tableColumn['type']);
345
        if (strlen($tableColumn['domain_type']) && !$this->_platform->hasDoctrineTypeMappingFor($tableColumn['type'])) {
346 347 348
            $dbType = strtolower($tableColumn['domain_type']);
            $tableColumn['complete_type'] = $tableColumn['domain_complete_type'];
        }
349

350
        $type = $this->_platform->getDoctrineTypeMapping($dbType);
351 352 353
        $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
        $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);

354 355 356
        switch ($dbType) {
            case 'smallint':
            case 'int2':
357
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
358
                $length = null;
359 360 361 362
                break;
            case 'int':
            case 'int4':
            case 'integer':
363
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
364
                $length = null;
365
                break;
366 367
            case 'bigint':
            case 'int8':
368
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
369
                $length = null;
370 371 372
                break;
            case 'bool':
            case 'boolean':
373 374 375 376 377 378 379 380
                if ($tableColumn['default'] === 'true') {
                    $tableColumn['default'] = true;
                }

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

381
                $length = null;
382 383
                break;
            case 'text':
384 385
                $fixed = false;
                break;
386 387 388 389
            case 'varchar':
            case 'interval':
            case '_varchar':
                $fixed = false;
390
                break;
391 392
            case 'char':
            case 'bpchar':
393
                $fixed = true;
394 395 396 397 398 399 400 401 402 403
                break;
            case 'float':
            case 'float4':
            case 'float8':
            case 'double':
            case 'double precision':
            case 'real':
            case 'decimal':
            case 'money':
            case 'numeric':
404 405
                $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);

406
                if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['complete_type'], $match)) {
407 408 409 410
                    $precision = $match[1];
                    $scale = $match[2];
                    $length = null;
                }
411 412 413 414
                break;
            case 'year':
                $length = null;
                break;
415 416 417 418 419

            // PostgreSQL 9.4+ only
            case 'jsonb':
                $jsonb = true;
                break;
420 421
        }

422 423 424 425
        if ($tableColumn['default'] && preg_match("('([^']+)'::)", $tableColumn['default'], $match)) {
            $tableColumn['default'] = $match[1];
        }

426
        $options = array(
427 428 429 430 431 432 433 434
            'length'        => $length,
            'notnull'       => (bool) $tableColumn['isnotnull'],
            'default'       => $tableColumn['default'],
            'primary'       => (bool) ($tableColumn['pri'] == 't'),
            'precision'     => $precision,
            'scale'         => $scale,
            'fixed'         => $fixed,
            'unsigned'      => false,
435
            'autoincrement' => $autoincrement,
436 437 438
            'comment'       => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
                ? $tableColumn['comment']
                : null,
439 440
        );

441 442 443 444 445 446
        $column = new Column($tableColumn['field'], Type::getType($type), $options);

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

447 448 449 450
        if ($column->getType()->getName() === 'json_array') {
            $column->setPlatformOption('jsonb', $jsonb);
        }

451
        return $column;
romanb's avatar
romanb committed
452
    }
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468

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