PostgreSqlSchemaManager.php 11.8 KB
Newer Older
romanb's avatar
romanb committed
1
<?php
2

romanb's avatar
romanb committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * 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
 * and is licensed under the LGPL. For more information, see
romanb's avatar
romanb committed
18
 * <http://www.doctrine-project.org>.
romanb's avatar
romanb committed
19 20
 */

21
namespace Doctrine\DBAL\Schema;
romanb's avatar
romanb committed
22 23 24 25 26 27 28

/**
 * xxx
 *
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @author      Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
29
 * @author      Benjamin Eberlei <kontakt@beberlei.de>
romanb's avatar
romanb committed
30 31 32
 * @version     $Revision$
 * @since       2.0
 */
33
class PostgreSqlSchemaManager extends AbstractSchemaManager
34
{
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
    /**
     * @var array
     */
    private $existingSchemaPaths;

    /**
     * Get all the existing schema names.
     *
     * @return array
     */
    public function getSchemaNames()
    {
        $rows = $this->_conn->fetchAll('SELECT schema_name FROM information_schema.schemata');
        return array_map(function($v) { return $v['schema_name']; }, $rows);
    }

    /**
     * Return an array of schema search paths
     *
     * This is a PostgreSQL only function.
     *
     * @return array
     */
    public function getSchemaSearchPaths()
    {
        $params = $this->_conn->getParams();
        $schema = explode(",", $this->_conn->fetchColumn('SHOW search_path'));
        if (isset($params['user'])) {
            $schema = str_replace('"$user"', $params['user'], $schema);
        }
        return $schema;
    }

    /**
     * Get names of all existing schemas in the current users search path.
     *
     * This is a PostgreSQL only function.
     *
     * @return array
     */
    public function getExistingSchemaSearchPaths()
    {
        if ($this->existingSchemaPaths === null) {
            $this->determineExistingSchemaSearchPaths();
        }
        return $this->existingSchemaPaths;
    }

    /**
     * Use this to set or reset the order of the existing schemas in the current search path of the user
     *
     * This is a PostgreSQL only function.
     *
     * @return type
     */
    public function determineExistingSchemaSearchPaths()
    {
        $names = $this->getSchemaNames();
        $paths = $this->getSchemaSearchPaths();

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

100
    protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
romanb's avatar
romanb committed
101
    {
102 103
        $onUpdate = null;
        $onDelete = null;
104

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

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

120
        return new ForeignKeyConstraint(
121 122
                $localColumns, $foreignTable, $foreignColumns, $tableForeignKey['conname'],
                array('onUpdate' => $onUpdate, 'onDelete' => $onDelete)
123
        );
romanb's avatar
romanb committed
124 125
    }

126 127
    public function dropDatabase($database)
    {
128 129 130 131 132 133 134 135 136 137 138 139
        $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);

        $this->_platform = $tmpPlatform;
        $this->_conn = $tmpConn;
140 141 142 143
    }

    public function createDatabase($database)
    {
144 145 146 147 148 149 150 151 152 153 154 155
        $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);

        $this->_platform = $tmpPlatform;
        $this->_conn = $tmpConn;
156
    }
157

158
    protected function _getPortableTriggerDefinition($trigger)
romanb's avatar
romanb committed
159
    {
160 161
        return $trigger['trigger_name'];
    }
romanb's avatar
romanb committed
162

163 164
    protected function _getPortableViewDefinition($view)
    {
165
        return new View($view['viewname'], $view['definition']);
romanb's avatar
romanb committed
166 167
    }

168
    protected function _getPortableUserDefinition($user)
romanb's avatar
romanb committed
169
    {
170 171 172 173
        return array(
            'user' => $user['usename'],
            'password' => $user['passwd']
        );
romanb's avatar
romanb committed
174 175
    }

176
    protected function _getPortableTableDefinition($table)
romanb's avatar
romanb committed
177
    {
178 179 180 181
        $schemas = $this->getExistingSchemaSearchPaths();
        $firstSchema = array_shift($schemas);

        if ($table['schema_name'] == $firstSchema) {
182 183 184 185
            return $table['table_name'];
        } else {
            return $table['schema_name'] . "." . $table['table_name'];
        }
186 187
    }

188 189 190 191 192 193 194 195
    /**
     * @license New BSD License
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
     * @param  array $tableIndexes
     * @param  string $tableName
     * @return array
     */
    protected function _getPortableTableIndexesList($tableIndexes, $tableName=null)
196
    {
197
        $buffer = array();
198 199 200
        foreach ($tableIndexes AS $row) {
            $colNumbers = explode(' ', $row['indkey']);
            $colNumbersSql = 'IN (' . join(' ,', $colNumbers) . ' )';
201 202
            $columnNameSql = "SELECT attnum, attname FROM pg_attribute
                WHERE attrelid={$row['indrelid']} AND attnum $colNumbersSql ORDER BY attnum ASC;";
203

204
            $stmt = $this->_conn->executeQuery($columnNameSql);
205 206
            $indexColumns = $stmt->fetchAll();

207 208
            // required for getting the order of the columns right.
            foreach ($colNumbers AS $colNum) {
209
                foreach ($indexColumns as $colRow) {
210 211 212
                    if ($colNum == $colRow['attnum']) {
                        $buffer[] = array(
                            'key_name' => $row['relname'],
213
                            'column_name' => trim($colRow['attname']),
214 215 216 217 218
                            'non_unique' => !$row['indisunique'],
                            'primary' => $row['indisprimary']
                        );
                    }
                }
219 220
            }
        }
221
        return parent::_getPortableTableIndexesList($buffer, $tableName);
222 223 224 225 226 227 228 229 230
    }

    protected function _getPortableDatabaseDefinition($database)
    {
        return $database['datname'];
    }

    protected function _getPortableSequenceDefinition($sequence)
    {
231 232 233 234 235 236 237 238
        if ($sequence['schemaname'] != 'public') {
            $sequenceName = $sequence['schemaname'] . "." . $sequence['relname'];
        } else {
            $sequenceName = $sequence['relname'];
        }

        $data = $this->_conn->fetchAll('SELECT min_value, increment_by FROM ' . $sequenceName);
        return new Sequence($sequenceName, $data[0]['increment_by'], $data[0]['min_value']);
romanb's avatar
romanb committed
239 240
    }

241 242 243 244 245 246 247 248 249
    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;
        }
250

251
        $matches = array();
252 253

        $autoincrement = false;
254 255 256
        if (preg_match("/^nextval\('(.*)'(::.*)?\)$/", $tableColumn['default'], $matches)) {
            $tableColumn['sequence'] = $matches[1];
            $tableColumn['default'] = null;
257
            $autoincrement = true;
258
        }
259

260
        if (stripos($tableColumn['default'], 'NULL') === 0) {
261 262
            $tableColumn['default'] = null;
        }
263

264 265 266 267
        $length = (isset($tableColumn['length'])) ? $tableColumn['length'] : null;
        if ($length == '-1' && isset($tableColumn['atttypmod'])) {
            $length = $tableColumn['atttypmod'] - 4;
        }
268
        if ((int) $length <= 0) {
269 270
            $length = null;
        }
271
        $fixed = null;
272 273

        if (!isset($tableColumn['name'])) {
274 275
            $tableColumn['name'] = '';
        }
276 277 278

        $precision = null;
        $scale = null;
279 280 281 282 283 284 285

        if ($this->_platform->hasDoctrineTypeMappingFor($tableColumn['type'])) {
            $dbType = strtolower($tableColumn['type']);
        } else {
            $dbType = strtolower($tableColumn['domain_type']);
            $tableColumn['complete_type'] = $tableColumn['domain_complete_type'];
        }
286

287
        $type = $this->_platform->getDoctrineTypeMapping($dbType);
288 289 290
        $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
        $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);

291 292 293
        switch ($dbType) {
            case 'smallint':
            case 'int2':
294
                $length = null;
295 296 297 298
                break;
            case 'int':
            case 'int4':
            case 'integer':
299
                $length = null;
300
                break;
301 302
            case 'bigint':
            case 'int8':
303
                $length = null;
304 305 306
                break;
            case 'bool':
            case 'boolean':
307
                $length = null;
308 309
                break;
            case 'text':
310 311
                $fixed = false;
                break;
312 313 314 315
            case 'varchar':
            case 'interval':
            case '_varchar':
                $fixed = false;
316
                break;
317 318
            case 'char':
            case 'bpchar':
319
                $fixed = true;
320 321 322 323 324 325 326 327 328 329
                break;
            case 'float':
            case 'float4':
            case 'float8':
            case 'double':
            case 'double precision':
            case 'real':
            case 'decimal':
            case 'money':
            case 'numeric':
330
                if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['complete_type'], $match)) {
331 332 333 334
                    $precision = $match[1];
                    $scale = $match[2];
                    $length = null;
                }
335 336 337 338 339 340
                break;
            case 'year':
                $length = null;
                break;
        }

341
        $options = array(
342 343 344 345 346 347 348 349
            'length'        => $length,
            'notnull'       => (bool) $tableColumn['isnotnull'],
            'default'       => $tableColumn['default'],
            'primary'       => (bool) ($tableColumn['pri'] == 't'),
            'precision'     => $precision,
            'scale'         => $scale,
            'fixed'         => $fixed,
            'unsigned'      => false,
350
            'autoincrement' => $autoincrement,
351
            'comment'       => $tableColumn['comment'],
352 353
        );

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

357
}