PostgreSqlSchemaManager.php 12.5 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

/**
Benjamin Morel's avatar
Benjamin Morel committed
23
 * PostgreSQL Schema Manager.
romanb's avatar
romanb committed
24
 *
Benjamin Morel's avatar
Benjamin Morel committed
25 26 27 28
 * @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
29
 */
30
class PostgreSqlSchemaManager extends AbstractSchemaManager
31
{
32 33 34 35 36 37
    /**
     * @var array
     */
    private $existingSchemaPaths;

    /**
Benjamin Morel's avatar
Benjamin Morel committed
38
     * Gets all the existing schema names.
39 40 41 42 43
     *
     * @return array
     */
    public function getSchemaNames()
    {
44
        $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
45

46 47 48 49
        return array_map(function($v) { return $v['schema_name']; }, $rows);
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
50
     * Returns an array of schema search paths.
51 52 53 54 55 56 57 58 59
     *
     * This is a PostgreSQL only function.
     *
     * @return array
     */
    public function getSchemaSearchPaths()
    {
        $params = $this->_conn->getParams();
        $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 73 74 75 76 77 78 79
     *
     * This is a PostgreSQL only function.
     *
     * @return array
     */
    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 96 97 98 99
     */
    public function determineExistingSchemaSearchPaths()
    {
        $names = $this->getSchemaNames();
        $paths = $this->getSchemaSearchPaths();

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

Benjamin Morel's avatar
Benjamin Morel committed
101 102 103
    /**
     * {@inheritdoc}
     */
104
    protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
romanb's avatar
romanb committed
105
    {
106 107
        $onUpdate = null;
        $onDelete = null;
108

109
        if (preg_match('(ON UPDATE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
110
            $onUpdate = $match[1];
romanb's avatar
romanb committed
111
        }
112
        if (preg_match('(ON DELETE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
113 114 115
            $onDelete = $match[1];
        }

116
        if (preg_match('/FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)/', $tableForeignKey['condef'], $values)) {
117 118
            // PostgreSQL returns identifiers that are keywords with quotes, we need them later, don't get
            // the idea to trim them here.
119 120
            $localColumns = array_map('trim', explode(",", $values[1]));
            $foreignColumns = array_map('trim', explode(",", $values[3]));
121 122 123
            $foreignTable = $values[2];
        }

124
        return new ForeignKeyConstraint(
125 126
                $localColumns, $foreignTable, $foreignColumns, $tableForeignKey['conname'],
                array('onUpdate' => $onUpdate, 'onDelete' => $onDelete)
127
        );
romanb's avatar
romanb committed
128 129
    }

Benjamin Morel's avatar
Benjamin Morel committed
130 131 132
    /**
     * {@inheritdoc}
     */
133 134
    public function dropDatabase($database)
    {
135 136 137 138 139 140 141 142 143 144
        $params = $this->_conn->getParams();
        $params["dbname"] = "postgres";
        $tmpPlatform = $this->_platform;
        $tmpConn = $this->_conn;

        $this->_conn = \Doctrine\DBAL\DriverManager::getConnection($params);
        $this->_platform = $this->_conn->getDatabasePlatform();

        parent::dropDatabase($database);

145 146
        $this->_conn->close();

147 148
        $this->_platform = $tmpPlatform;
        $this->_conn = $tmpConn;
149 150
    }

Benjamin Morel's avatar
Benjamin Morel committed
151 152 153
    /**
     * {@inheritdoc}
     */
154 155
    public function createDatabase($database)
    {
156 157 158 159 160 161 162 163 164 165
        $params = $this->_conn->getParams();
        $params["dbname"] = "postgres";
        $tmpPlatform = $this->_platform;
        $tmpConn = $this->_conn;

        $this->_conn = \Doctrine\DBAL\DriverManager::getConnection($params);
        $this->_platform = $this->_conn->getDatabasePlatform();

        parent::createDatabase($database);

166 167
        $this->_conn->close();

168 169
        $this->_platform = $tmpPlatform;
        $this->_conn = $tmpConn;
170
    }
171

Benjamin Morel's avatar
Benjamin Morel committed
172 173 174
    /**
     * {@inheritdoc}
     */
175
    protected function _getPortableTriggerDefinition($trigger)
romanb's avatar
romanb committed
176
    {
177 178
        return $trigger['trigger_name'];
    }
romanb's avatar
romanb committed
179

Benjamin Morel's avatar
Benjamin Morel committed
180 181 182
    /**
     * {@inheritdoc}
     */
183 184
    protected function _getPortableViewDefinition($view)
    {
185
        return new View($view['viewname'], $view['definition']);
romanb's avatar
romanb committed
186 187
    }

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

Benjamin Morel's avatar
Benjamin Morel committed
199 200 201
    /**
     * {@inheritdoc}
     */
202
    protected function _getPortableTableDefinition($table)
romanb's avatar
romanb committed
203
    {
204 205 206 207
        $schemas = $this->getExistingSchemaSearchPaths();
        $firstSchema = array_shift($schemas);

        if ($table['schema_name'] == $firstSchema) {
208 209 210 211
            return $table['table_name'];
        } else {
            return $table['schema_name'] . "." . $table['table_name'];
        }
212 213
    }

214
    /**
Benjamin Morel's avatar
Benjamin Morel committed
215 216
     * {@inheritdoc}
     *
217 218 219 220
     * @license New BSD License
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
     */
    protected function _getPortableTableIndexesList($tableIndexes, $tableName=null)
221
    {
222
        $buffer = array();
223
        foreach ($tableIndexes as $row) {
224 225
            $colNumbers = explode(' ', $row['indkey']);
            $colNumbersSql = 'IN (' . join(' ,', $colNumbers) . ' )';
226 227
            $columnNameSql = "SELECT attnum, attname FROM pg_attribute
                WHERE attrelid={$row['indrelid']} AND attnum $colNumbersSql ORDER BY attnum ASC;";
228

229
            $stmt = $this->_conn->executeQuery($columnNameSql);
230 231
            $indexColumns = $stmt->fetchAll();

232
            // required for getting the order of the columns right.
233
            foreach ($colNumbers as $colNum) {
234
                foreach ($indexColumns as $colRow) {
235 236 237
                    if ($colNum == $colRow['attnum']) {
                        $buffer[] = array(
                            'key_name' => $row['relname'],
238
                            'column_name' => trim($colRow['attname']),
239 240 241 242 243
                            'non_unique' => !$row['indisunique'],
                            'primary' => $row['indisprimary']
                        );
                    }
                }
244 245
            }
        }
Benjamin Morel's avatar
Benjamin Morel committed
246

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

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

Benjamin Morel's avatar
Benjamin Morel committed
258 259 260
    /**
     * {@inheritdoc}
     */
261 262
    protected function _getPortableSequenceDefinition($sequence)
    {
263 264 265 266 267 268
        if ($sequence['schemaname'] != 'public') {
            $sequenceName = $sequence['schemaname'] . "." . $sequence['relname'];
        } else {
            $sequenceName = $sequence['relname'];
        }

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

271
        return new Sequence($sequenceName, $data[0]['increment_by'], $data[0]['min_value']);
romanb's avatar
romanb committed
272 273
    }

Benjamin Morel's avatar
Benjamin Morel committed
274 275 276
    /**
     * {@inheritdoc}
     */
277 278 279 280 281 282 283 284 285
    protected function _getPortableTableColumnDefinition($tableColumn)
    {
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);

        if (strtolower($tableColumn['type']) === 'varchar') {
            // get length from varchar definition
            $length = preg_replace('~.*\(([0-9]*)\).*~', '$1', $tableColumn['complete_type']);
            $tableColumn['length'] = $length;
        }
286

287
        $matches = array();
288 289

        $autoincrement = false;
290 291 292
        if (preg_match("/^nextval\('(.*)'(::.*)?\)$/", $tableColumn['default'], $matches)) {
            $tableColumn['sequence'] = $matches[1];
            $tableColumn['default'] = null;
293
            $autoincrement = true;
294
        }
295

296 297 298 299
        if (preg_match("/^'(.*)'::.*$/", $tableColumn['default'], $matches)) {
            $tableColumn['default'] = $matches[1];
        }

300
        if (stripos($tableColumn['default'], 'NULL') === 0) {
301 302
            $tableColumn['default'] = null;
        }
303

304 305 306 307
        $length = (isset($tableColumn['length'])) ? $tableColumn['length'] : null;
        if ($length == '-1' && isset($tableColumn['atttypmod'])) {
            $length = $tableColumn['atttypmod'] - 4;
        }
308
        if ((int) $length <= 0) {
309 310
            $length = null;
        }
311
        $fixed = null;
312 313

        if (!isset($tableColumn['name'])) {
314 315
            $tableColumn['name'] = '';
        }
316 317 318

        $precision = null;
        $scale = null;
319

320
        $dbType = strtolower($tableColumn['type']);
321
        if (strlen($tableColumn['domain_type']) && !$this->_platform->hasDoctrineTypeMappingFor($tableColumn['type'])) {
322 323 324
            $dbType = strtolower($tableColumn['domain_type']);
            $tableColumn['complete_type'] = $tableColumn['domain_complete_type'];
        }
325

326
        $type = $this->_platform->getDoctrineTypeMapping($dbType);
327 328 329
        $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
        $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);

330 331 332
        switch ($dbType) {
            case 'smallint':
            case 'int2':
333
                $length = null;
334 335 336 337
                break;
            case 'int':
            case 'int4':
            case 'integer':
338
                $length = null;
339
                break;
340 341
            case 'bigint':
            case 'int8':
342
                $length = null;
343 344 345
                break;
            case 'bool':
            case 'boolean':
346
                $length = null;
347 348
                break;
            case 'text':
349 350
                $fixed = false;
                break;
351 352 353 354
            case 'varchar':
            case 'interval':
            case '_varchar':
                $fixed = false;
355
                break;
356 357
            case 'char':
            case 'bpchar':
358
                $fixed = true;
359 360 361 362 363 364 365 366 367 368
                break;
            case 'float':
            case 'float4':
            case 'float8':
            case 'double':
            case 'double precision':
            case 'real':
            case 'decimal':
            case 'money':
            case 'numeric':
369
                if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['complete_type'], $match)) {
370 371 372 373
                    $precision = $match[1];
                    $scale = $match[2];
                    $length = null;
                }
374 375 376 377 378 379
                break;
            case 'year':
                $length = null;
                break;
        }

380 381 382 383
        if ($tableColumn['default'] && preg_match("('([^']+)'::)", $tableColumn['default'], $match)) {
            $tableColumn['default'] = $match[1];
        }

384
        $options = array(
385 386 387 388 389 390 391 392
            'length'        => $length,
            'notnull'       => (bool) $tableColumn['isnotnull'],
            'default'       => $tableColumn['default'],
            'primary'       => (bool) ($tableColumn['pri'] == 't'),
            'precision'     => $precision,
            'scale'         => $scale,
            'fixed'         => $fixed,
            'unsigned'      => false,
393
            'autoincrement' => $autoincrement,
394
            'comment'       => $tableColumn['comment'],
395 396
        );

397
        return new Column($tableColumn['field'], \Doctrine\DBAL\Types\Type::getType($type), $options);
romanb's avatar
romanb committed
398
    }
399
}