PostgreSqlSchemaManager.php 9.1 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
    protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
romanb's avatar
romanb committed
37
    {
38 39
        $onUpdate = null;
        $onDelete = null;
40

41
        if (preg_match('(ON UPDATE ([a-zA-Z0-9]+))', $tableForeignKey['condef'], $match)) {
42
            $onUpdate = $match[1];
romanb's avatar
romanb committed
43
        }
44
        if (preg_match('(ON DELETE ([a-zA-Z0-9]+))', $tableForeignKey['condef'], $match)) {
45 46 47
            $onDelete = $match[1];
        }

48
        if (preg_match('/FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)/', $tableForeignKey['condef'], $values)) {
49 50 51 52 53
            $localColumns = explode(",", $values[1]);
            $foreignColumns = explode(",", $values[3]);
            $foreignTable = $values[2];
        }

54
        return new ForeignKeyConstraint(
55 56
                $localColumns, $foreignTable, $foreignColumns, $tableForeignKey['conname'],
                array('onUpdate' => $onUpdate, 'onDelete' => $onDelete)
57
        );
romanb's avatar
romanb committed
58 59
    }

60 61
    public function dropDatabase($database)
    {
62 63 64 65 66 67 68 69 70 71 72 73
        $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;
74 75 76 77
    }

    public function createDatabase($database)
    {
78 79 80 81 82 83 84 85 86 87 88 89
        $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;
90
    }
91

92
    protected function _getPortableTriggerDefinition($trigger)
romanb's avatar
romanb committed
93
    {
94 95
        return $trigger['trigger_name'];
    }
romanb's avatar
romanb committed
96

97 98
    protected function _getPortableViewDefinition($view)
    {
99
        return new View($view['viewname'], $view['definition']);
romanb's avatar
romanb committed
100 101
    }

102
    protected function _getPortableUserDefinition($user)
romanb's avatar
romanb committed
103
    {
104 105 106 107
        return array(
            'user' => $user['usename'],
            'password' => $user['passwd']
        );
romanb's avatar
romanb committed
108 109
    }

110
    protected function _getPortableTableDefinition($table)
romanb's avatar
romanb committed
111
    {
112 113 114
        return $table['table_name'];
    }

115 116 117 118 119 120 121 122
    /**
     * @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)
123
    {
124
        $buffer = array();
125 126 127
        foreach ($tableIndexes AS $row) {
            $colNumbers = explode(' ', $row['indkey']);
            $colNumbersSql = 'IN (' . join(' ,', $colNumbers) . ' )';
128 129
            $columnNameSql = "SELECT attnum, attname FROM pg_attribute
                WHERE attrelid={$row['indrelid']} AND attnum $colNumbersSql ORDER BY attnum ASC;";
130

131
            $stmt = $this->_conn->executeQuery($columnNameSql);
132 133
            $indexColumns = $stmt->fetchAll();

134 135
            // required for getting the order of the columns right.
            foreach ($colNumbers AS $colNum) {
136
                foreach ($indexColumns as $colRow) {
137 138 139 140 141 142 143 144 145
                    if ($colNum == $colRow['attnum']) {
                        $buffer[] = array(
                            'key_name' => $row['relname'],
                            'column_name' => $colRow['attname'],
                            'non_unique' => !$row['indisunique'],
                            'primary' => $row['indisprimary']
                        );
                    }
                }
146 147 148
            }
        }
        return parent::_getPortableTableIndexesList($buffer);
149 150 151 152 153 154 155 156 157
    }

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

    protected function _getPortableSequenceDefinition($sequence)
    {
158
        $data = $this->_conn->fetchAll('SELECT min_value, increment_by FROM ' . $sequence['relname']);
159
        return new Sequence($sequence['relname'], $data[0]['increment_by'], $data[0]['min_value']);
romanb's avatar
romanb committed
160 161
    }

162 163 164 165 166 167 168 169 170
    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;
        }
171

172
        $matches = array();
173 174

        $autoincrement = false;
175 176 177
        if (preg_match("/^nextval\('(.*)'(::.*)?\)$/", $tableColumn['default'], $matches)) {
            $tableColumn['sequence'] = $matches[1];
            $tableColumn['default'] = null;
178
            $autoincrement = true;
179
        }
180

181
        if (stripos($tableColumn['default'], 'NULL') === 0) {
182 183
            $tableColumn['default'] = null;
        }
184

185 186 187 188
        $length = (isset($tableColumn['length'])) ? $tableColumn['length'] : null;
        if ($length == '-1' && isset($tableColumn['atttypmod'])) {
            $length = $tableColumn['atttypmod'] - 4;
        }
189
        if ((int) $length <= 0) {
190 191 192
            $length = null;
        }
        $type = array();
193
        $fixed = null;
194 195

        if (!isset($tableColumn['name'])) {
196 197
            $tableColumn['name'] = '';
        }
198 199 200

        $precision = null;
        $scale = null;
201 202 203 204 205 206 207

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

209
        $type = $this->_platform->getDoctrineTypeMapping($dbType);
210 211 212
        switch ($dbType) {
            case 'smallint':
            case 'int2':
213
                $length = null;
214 215 216 217
                break;
            case 'int':
            case 'int4':
            case 'integer':
218
                $length = null;
219
                break;
220 221
            case 'bigint':
            case 'int8':
222
                $length = null;
223 224 225
                break;
            case 'bool':
            case 'boolean':
226
                $length = null;
227 228
                break;
            case 'text':
229 230
                $fixed = false;
                break;
231 232 233 234
            case 'varchar':
            case 'interval':
            case '_varchar':
                $fixed = false;
235
                break;
236 237
            case 'char':
            case 'bpchar':
238
                $fixed = true;
239 240 241 242 243 244 245 246 247 248
                break;
            case 'float':
            case 'float4':
            case 'float8':
            case 'double':
            case 'double precision':
            case 'real':
            case 'decimal':
            case 'money':
            case 'numeric':
249
                if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['complete_type'], $match)) {
250 251 252 253
                    $precision = $match[1];
                    $scale = $match[2];
                    $length = null;
                }
254 255 256 257 258 259
                break;
            case 'year':
                $length = null;
                break;
        }

260
        $options = array(
261 262 263 264
            'length' => $length,
            'notnull' => (bool) $tableColumn['isnotnull'],
            'default' => $tableColumn['default'],
            'primary' => (bool) ($tableColumn['pri'] == 't'),
265
            'precision' => $precision,
266 267 268
            'scale' => $scale,
            'fixed' => $fixed,
            'unsigned' => false,
269
            'autoincrement' => $autoincrement,
270 271
        );

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

275
}