Pgsql.php 15 KB
Newer Older
romanb's avatar
romanb committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
<?php
/*
 *  $Id$
 *
 * 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
 * <http://www.phpdoctrine.com>.
 */
Doctrine::autoload('Doctrine_Export');
/**
 * Doctrine_Export_Pgsql
 *
 * @package     Doctrine
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @author      Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @category    Object Relational Mapping
 * @link        www.phpdoctrine.com
 * @since       1.0
 * @version     $Revision$
 */
class Doctrine_Export_Pgsql extends Doctrine_Export
{
   /**
     * create a new database
     *
     * @param string $name name of the database that should be created
     * @throws PDOException
     * @return void
     */
zYne's avatar
zYne committed
43
    public function createDatabaseSql($name)
romanb's avatar
romanb committed
44 45
    {
        $query  = 'CREATE DATABASE ' . $this->conn->quoteIdentifier($name);
zYne's avatar
zYne committed
46 47
        
        return $query;
romanb's avatar
romanb committed
48 49 50 51 52 53 54 55
    }
    /**
     * drop an existing database
     *
     * @param string $name name of the database that should be dropped
     * @throws PDOException
     * @access public
     */
zYne's avatar
zYne committed
56
    public function dropDatabaseSql($name)
romanb's avatar
romanb committed
57 58
    {
        $query  = 'DROP DATABASE ' . $this->conn->quoteIdentifier($name);
zYne's avatar
zYne committed
59 60
        
        return $query;
romanb's avatar
romanb committed
61
    }
zYne's avatar
zYne committed
62 63 64 65 66 67 68 69 70 71 72 73 74
    /**
     * getAdvancedForeignKeyOptions
     * Return the FOREIGN KEY query section dealing with non-standard options
     * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
     *
     * @param array $definition         foreign key definition
     * @return string
     * @access protected
     */
    public function getAdvancedForeignKeyOptions(array $definition)
    {
        $query = '';
        if (isset($definition['match'])) {
zYne's avatar
zYne committed
75
            $query .= ' MATCH ' . $definition['match'];
zYne's avatar
zYne committed
76 77
        }
        if (isset($definition['onUpdate'])) {
zYne's avatar
zYne committed
78
            $query .= ' ON UPDATE ' . $definition['onUpdate'];
zYne's avatar
zYne committed
79 80
        }
        if (isset($definition['onDelete'])) {
zYne's avatar
zYne committed
81
            $query .= ' ON DELETE ' . $definition['onDelete'];
zYne's avatar
zYne committed
82 83 84 85 86 87 88 89 90 91 92 93 94 95
        }
        if (isset($definition['deferrable'])) {
            $query .= ' DEFERRABLE';
        } else {
            $query .= ' NOT DEFERRABLE';
        }
        if (isset($definition['feferred'])) {
            $query .= ' INITIALLY DEFERRED';
        } else {
            $query .= ' INITIALLY IMMEDIATE';
        }
        return $query;
    }

romanb's avatar
romanb committed
96 97 98 99 100 101 102 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 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    /**
     * alter an existing table
     *
     * @param string $name         name of the table that is intended to be changed.
     * @param array $changes     associative array that contains the details of each type
     *                             of change that is intended to be performed. The types of
     *                             changes that are currently supported are defined as follows:
     *
     *                             name
     *
     *                                New name for the table.
     *
     *                            add
     *
     *                                Associative array with the names of fields to be added as
     *                                 indexes of the array. The value of each entry of the array
     *                                 should be set to another associative array with the properties
     *                                 of the fields to be added. The properties of the fields should
     *                                 be the same as defined by the Metabase parser.
     *
     *
     *                            remove
     *
     *                                Associative array with the names of fields to be removed as indexes
     *                                 of the array. Currently the values assigned to each entry are ignored.
     *                                 An empty array should be used for future compatibility.
     *
     *                            rename
     *
     *                                Associative array with the names of fields to be renamed as indexes
     *                                 of the array. The value of each entry of the array should be set to
     *                                 another associative array with the entry named name with the new
     *                                 field name and the entry named Declaration that is expected to contain
     *                                 the portion of the field declaration already in DBMS specific SQL code
     *                                 as it is used in the CREATE TABLE statement.
     *
     *                            change
     *
     *                                Associative array with the names of the fields to be changed as indexes
     *                                 of the array. Keep in mind that if it is intended to change either the
     *                                 name of a field and any other properties, the change array entries
     *                                 should have the new names of the fields as array indexes.
     *
     *                                The value of each entry of the array should be set to another associative
     *                                 array with the properties of the fields to that are meant to be changed as
     *                                 array entries. These entries should be assigned to the new values of the
     *                                 respective properties. The properties of the fields should be the same
     *                                 as defined by the Metabase parser.
     *
     *                            Example
     *                                array(
     *                                    'name' => 'userlist',
     *                                    'add' => array(
     *                                        'quota' => array(
     *                                            'type' => 'integer',
     *                                            'unsigned' => 1
     *                                        )
     *                                    ),
     *                                    'remove' => array(
     *                                        'file_limit' => array(),
     *                                        'time_limit' => array()
     *                                    ),
     *                                    'change' => array(
     *                                        'name' => array(
     *                                            'length' => '20',
     *                                            'definition' => array(
     *                                                'type' => 'text',
     *                                                'length' => 20,
     *                                            ),
     *                                        )
     *                                    ),
     *                                    'rename' => array(
     *                                        'sex' => array(
     *                                            'name' => 'gender',
     *                                            'definition' => array(
     *                                                'type' => 'text',
     *                                                'length' => 1,
     *                                                'default' => 'M',
     *                                            ),
     *                                        )
     *                                    )
     *                                )
     *
     * @param boolean $check     indicates whether the function should just check if the DBMS driver
     *                             can perform the requested table alterations if the value is true or
     *                             actually perform them otherwise.
zYne's avatar
zYne committed
182
     * @throws Doctrine_Connection_Exception
romanb's avatar
romanb committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
     * @return boolean
     */
    public function alterTable($name, array $changes, $check)
    {
        foreach ($changes as $changeName => $change) {
            switch ($changeName) {
                case 'add':
                case 'remove':
                case 'change':
                case 'name':
                case 'rename':
                    break;
                default:
                    throw new Doctrine_Export_Exception('change type "' . $changeName . '\" not yet supported');
            }
        }

        if ($check) {
            return true;
        }

        if (isset($changes['add']) && is_array($changes['add'])) {
zYne's avatar
zYne committed
205
            foreach ($changes['add'] as $fieldName => $field) {
zYne's avatar
zYne committed
206
                $query = 'ADD ' . $this->getDeclaration($fieldName, $field);
romanb's avatar
romanb committed
207 208 209 210 211
                $this->conn->exec('ALTER TABLE ' . $name . ' ' . $query);
            }
        }

        if (isset($changes['remove']) && is_array($changes['remove'])) {
zYne's avatar
zYne committed
212 213 214
            foreach ($changes['remove'] as $fieldName => $field) {
                $fieldName = $this->conn->quoteIdentifier($fieldName, true);
                $query = 'DROP ' . $fieldName;
romanb's avatar
romanb committed
215 216 217 218 219
                $this->conn->exec('ALTER TABLE ' . $name . ' ' . $query);
            }
        }

        if (isset($changes['change']) && is_array($changes['change'])) {
zYne's avatar
zYne committed
220 221
            foreach ($changes['change'] as $fieldName => $field) {
                $fieldName = $this->conn->quoteIdentifier($fieldName, true);
romanb's avatar
romanb committed
222
                if (isset($field['type'])) {
zYne's avatar
zYne committed
223
                    $serverInfo = $this->conn->getServerVersion();
romanb's avatar
romanb committed
224

zYne's avatar
zYne committed
225
                    if (is_array($serverInfo) && $serverInfo['major'] < 8) {
romanb's avatar
romanb committed
226 227
                        throw new Doctrine_Export_Exception('changing column type for "'.$field['type'].'\" requires PostgreSQL 8.0 or above');
                    }
zYne's avatar
zYne committed
228
                    $query = 'ALTER ' . $fieldName . ' TYPE ' . $this->conn->datatype->getTypeDeclaration($field['definition']);
romanb's avatar
romanb committed
229 230 231
                    $this->conn->exec('ALTER TABLE ' . $name . ' ' . $query);;
                }
                if (array_key_exists('default', $field)) {
zYne's avatar
zYne committed
232
                    $query = 'ALTER ' . $fieldName . ' SET DEFAULT ' . $this->conn->quote($field['definition']['default'], $field['definition']['type']);
romanb's avatar
romanb committed
233 234 235
                    $this->conn->exec('ALTER TABLE ' . $name . ' ' . $query);
                }
                if (!empty($field['notnull'])) {
zYne's avatar
zYne committed
236
                    $query = 'ALTER ' . $fieldName . ' ' . ($field['definition']['notnull'] ? 'SET' : 'DROP') . ' NOT NULL';
romanb's avatar
romanb committed
237 238 239 240 241 242 243
                    $this->conn->exec('ALTER TABLE ' . $name . ' ' . $query);
                }
            }
        }

        if (isset($changes['rename']) && is_array($changes['rename'])) {
            foreach ($changes['rename'] as $fieldName => $field) {
zYne's avatar
zYne committed
244
                $fieldName = $this->conn->quoteIdentifier($fieldName, true);
romanb's avatar
romanb committed
245 246 247 248 249 250 251 252 253 254
                $this->conn->exec('ALTER TABLE ' . $name . ' RENAME COLUMN ' . $fieldName . ' TO ' . $this->conn->quoteIdentifier($field['name'], true));
            }
        }

        $name = $this->conn->quoteIdentifier($name, true);
        if (isset($changes['name'])) {
            $changeName = $this->conn->quoteIdentifier($changes['name'], true);
            $this->conn->exec('ALTER TABLE ' . $name . ' RENAME TO ' . $changeName);
        }
    }
zYne's avatar
zYne committed
255
    /**
zYne's avatar
zYne committed
256
     * return RDBMS specific create sequence statement
zYne's avatar
zYne committed
257
     *
zYne's avatar
zYne committed
258 259 260 261 262 263 264 265 266 267
     * @throws Doctrine_Connection_Exception     if something fails at database level
     * @param string    $seqName        name of the sequence to be created
     * @param string    $start          start value of the sequence; default is 1
     * @param array     $options  An associative array of table options:
     *                          array(
     *                              'comment' => 'Foo',
     *                              'charset' => 'utf8',
     *                              'collate' => 'utf8_unicode_ci',
     *                          );
     * @return string
zYne's avatar
zYne committed
268
     */
zYne's avatar
zYne committed
269
    public function createSequenceSql($sequenceName, $start = 1, array $options = array())
zYne's avatar
zYne committed
270 271 272 273 274 275 276 277 278 279
    {
        $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($sequenceName), true);
        return $this->conn->exec('CREATE SEQUENCE ' . $sequenceName . ' INCREMENT 1' .
                    ($start < 1 ? ' MINVALUE ' . $start : '') . ' START ' . $start);
    }
    /**
     * drop existing sequence
     *
     * @param string $sequenceName name of the sequence to be dropped
     */
zYne's avatar
zYne committed
280
    public function dropSequenceSql($sequenceName)
zYne's avatar
zYne committed
281 282
    {
        $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($sequenceName), true);
zYne's avatar
zYne committed
283
        return 'DROP SEQUENCE ' . $sequenceName;
zYne's avatar
zYne committed
284 285
    }

286 287 288 289 290 291 292 293
    /**
     * Creates a table.
     *
     * @param unknown_type $name
     * @param array $fields
     * @param array $options
     * @return unknown
     */
294
    public function createTableSql($name, array $fields, array $options = array())
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    {
        if ( ! $name) {
            throw new Doctrine_Export_Exception('no valid table name specified');
        }
        
        if (empty($fields)) {
            throw new Doctrine_Export_Exception('no fields specified for table ' . $name);
        }

        $queryFields = $this->getFieldDeclarationList($fields);


        if (isset($options['primary']) && ! empty($options['primary'])) {
            $queryFields .= ', PRIMARY KEY(' . implode(', ', array_values($options['primary'])) . ')';
        }

311
        $query = 'CREATE TABLE ' . $this->conn->quoteIdentifier($name, true) . ' (' . $queryFields . ')';
312 313 314 315 316 317 318 319 320

        $sql[] = $query;

        if (isset($options['indexes']) && ! empty($options['indexes'])) {
            foreach($options['indexes'] as $index => $definition) {
                $sql[] = $this->createIndexSql($name, $index, $definition);
            }
        }
        
321
        if (isset($options['foreignKeys'])) {
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347

            foreach ((array) $options['foreignKeys'] as $k => $definition) {
                if (is_array($definition)) {
                    $sql[] = $this->createForeignKeySql($name, $definition);
                }
            }
        }
        
        return $sql;
    }
    
    /**
     * createForeignKeySql
     *
     * @param string    $table         name of the table on which the foreign key is to be created
     * @param array     $definition    associative array that defines properties of the foreign key to be created.
     * @return string
     */
    public function createForeignKeySql($table, array $definition)
    {
        $table = $this->conn->quoteIdentifier($table);

        $query = 'ALTER TABLE ' . $table . ' ADD ' . $this->getForeignKeyDeclaration($definition);

        return $query;
    }
romanb's avatar
romanb committed
348 349
}