Oracle.php 18.6 KB
Newer Older
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
<?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_Oracle
 *
 * @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$
 */
lsmith's avatar
lsmith committed
34 35
class Doctrine_Export_Oracle extends Doctrine_Export
{
36 37 38 39 40 41 42 43
    /**
     * create a new database
     *
     * @param object $db database object that is extended by this class
     * @param string $name name of the database that should be created
     * @return mixed MDB2_OK on success, a MDB2 error on failure
     * @access public
     */
lsmith's avatar
lsmith committed
44
    public function createDatabase($name)
45 46
    {
        if ( ! $this->conn->getAttribute(Doctrine::ATTR_EMULATE_DATABASE))
47
            throw new Doctrine_Export_Exception('database creation is only supported if the "emulate_database" attribute is enabled');
zYne's avatar
zYne committed
48

49 50
        $username   = sprintf($this->conn->getAttribute(Doctrine::ATTR_DB_NAME_FORMAT), $name);
        $password   = $this->conn->dsn['password'] ? $this->conn->dsn['password'] : $name;
51

52 53
        $tablespace = $this->conn->getAttribute(Doctrine::ATTR_DB_NAME_FORMAT)
                    ? ' DEFAULT TABLESPACE '.$this->conn->options['default_tablespace'] : '';
zYne's avatar
zYne committed
54

55
        $query  = 'CREATE USER ' . $username . ' IDENTIFIED BY ' . $password . $tablespace;
lsmith's avatar
lsmith committed
56
        $result = $this->conn->exec($query);
57

lsmith's avatar
lsmith committed
58 59 60 61
        try {
            $query = 'GRANT CREATE SESSION, CREATE TABLE, UNLIMITED TABLESPACE, CREATE SEQUENCE, CREATE TRIGGER TO ' . $username;
            $result = $this->conn->exec($query);
        } catch (Exception $e) {
62
            $query = 'DROP USER '.$username.' CASCADE';
lsmith's avatar
lsmith committed
63
            $result2 = $this->conn->exec($query);
64
        }
lsmith's avatar
lsmith committed
65
        return true;
66 67 68 69
    }
    /**
     * drop an existing database
     *
70
     * @param object $this->conn database object that is extended by this class
71 72 73 74
     * @param string $name name of the database that should be dropped
     * @return mixed MDB2_OK on success, a MDB2 error on failure
     * @access public
     */
lsmith's avatar
lsmith committed
75
    public function dropDatabase($name)
76 77
    {
        if ( ! $this->conn->getAttribute(Doctrine::ATTR_EMULATE_DATABASE))
78
            throw new Doctrine_Export_Exception('database dropping is only supported if the
zYne's avatar
zYne committed
79 80
                                                       "emulate_database" option is enabled');

81 82
        $username = sprintf($this->conn->getAttribute(Doctrine::ATTR_DB_NAME_FORMAT), $name);

lsmith's avatar
lsmith committed
83
        return $this->conn->exec('DROP USER ' . $username . ' CASCADE');
84 85 86 87 88 89 90 91 92 93
    }
    /**
     * add an autoincrement sequence + trigger
     *
     * @param string $name  name of the PK field
     * @param string $table name of the table
     * @param string $start start value for the sequence
     * @return mixed        MDB2_OK on success, a MDB2 error on failure
     * @access private
     */
lsmith's avatar
lsmith committed
94
    public function _makeAutoincrement($name, $table, $start = 1)
95
    {
96 97 98 99 100 101
        $table = strtoupper($table);
        $index_name  = $table . '_AI_PK';
        $definition = array(
            'primary' => true,
            'fields' => array($name => true),
        );
102 103
        $result = $this->createConstraint($table, $index_name, $definition);

104
        if (is_null($start)) {
105 106
            $this->conn->beginTransaction();
            $query = 'SELECT MAX(' . $this->conn->quoteIdentifier($name, true) . ') FROM ' . $this->conn->quoteIdentifier($table, true);
lsmith's avatar
lsmith committed
107 108
            $start = $this->conn->fetchOne($query);

109
            ++$start;
110
            $result = $this->createSequence($table, $start);
111
            $this->conn->commit();
112
        } else {
113
            $result = $this->createSequence($table, $start);
114
        }
lsmith's avatar
lsmith committed
115

116 117 118 119 120
        $sequence_name = $this->conn->getSequenceName($table);
        $trigger_name  = $this->conn->quoteIdentifier($table . '_AI_PK', true);
        $table = $this->conn->quoteIdentifier($table, true);
        $name  = $this->conn->quoteIdentifier($name, true);
        $trigger_sql = 'CREATE TRIGGER '.$trigger_name.'
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
   BEFORE INSERT
   ON '.$table.'
   FOR EACH ROW
DECLARE
   last_Sequence NUMBER;
   last_InsertID NUMBER;
BEGIN
   SELECT '.$sequence_name.'.NEXTVAL INTO :NEW.'.$name.' FROM DUAL;
   IF (:NEW.'.$name.' IS NULL OR :NEW.'.$name.' = 0) THEN
      SELECT '.$sequence_name.'.NEXTVAL INTO :NEW.'.$name.' FROM DUAL;
   ELSE
      SELECT NVL(Last_Number, 0) INTO last_Sequence
        FROM User_Sequences
       WHERE UPPER(Sequence_Name) = UPPER(\''.$sequence_name.'\');
      SELECT :NEW.id INTO last_InsertID FROM DUAL;
      WHILE (last_InsertID > last_Sequence) LOOP
         SELECT '.$sequence_name.'.NEXTVAL INTO last_Sequence FROM DUAL;
      END LOOP;
   END IF;
END;
';
zYne's avatar
zYne committed
142
        return $this->conn->exec($trigger_sql);
143 144 145 146 147
    }
    /**
     * drop an existing autoincrement sequence + trigger
     *
     * @param string $table name of the table
148
     * @return void
149
     */
lsmith's avatar
lsmith committed
150
    public function dropAutoincrement($table)
151
    {
152
        $table = strtoupper($table);
153 154
        $triggerName = $table . '_AI_PK';
        $trigger_name_quoted = $this->conn->quote($triggerName);
155 156
        $query = 'SELECT trigger_name FROM user_triggers';
        $query.= ' WHERE trigger_name='.$trigger_name_quoted.' OR trigger_name='.strtoupper($trigger_name_quoted);
157
        $trigger = $this->conn->fetchOne($query);
158

lsmith's avatar
lsmith committed
159
        if ($trigger) {
160
            $trigger_name  = $this->conn->quoteIdentifier($table . '_AI_PK', true);
161
            $trigger_sql = 'DROP TRIGGER ' . $trigger_name;
lsmith's avatar
lsmith committed
162

163
            // if throws exception, trigger for autoincrement PK could not be dropped
zYne's avatar
zYne committed
164
            $this->conn->exec($trigger_sql);
165

166 167
            // if throws exception, sequence for autoincrement PK could not be dropped
            $this->dropSequence($table);
168

169
            $indexName = $table . '_AI_PK';
170

171 172 173
            // if throws exception, primary key for autoincrement PK could not be dropped
            $this->dropConstraint($table, $indexName);
        }
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
    }
    /**
     * create a new table
     *
     * @param string $name     Name of the database that should be created
     * @param array $fields Associative array that contains the definition of each field of the new table
     *                        The indexes of the array entries are the names of the fields of the table an
     *                        the array entry values are associative arrays like those that are meant to be
     *                         passed with the field definitions to get[Type]Declaration() functions.
     *
     *                        Example
     *                        array(
     *
     *                            'id' => array(
     *                                'type' => 'integer',
     *                                'unsigned' => 1
     *                                'notnull' => 1
     *                                'default' => 0
     *                            ),
     *                            'name' => array(
     *                                'type' => 'text',
     *                                'length' => 12
     *                            ),
     *                            'password' => array(
     *                                'type' => 'text',
     *                                'length' => 12
     *                            )
     *                        );
     * @param array $options  An associative array of table options:
     *
204
     * @return void
205
     */
lsmith's avatar
lsmith committed
206
    public function createTable($name, $fields, $options = array())
207
    {
208 209
        $this->conn->beginTransaction();

210
        $result = parent::createTable($name, $fields, $options);
211

lsmith's avatar
lsmith committed
212 213
        foreach ($fields as $field_name => $field) {
            if (isset($field['autoincrement']) && $field['autoincrement']) {
214
                $result = $this->_makeAutoincrement($field_name, $name);
215 216
            }
        }
217 218 219

        $this->conn->commit();

220 221 222 223 224 225
        return $result;
    }
    /**
     * drop an existing table
     *
     * @param string $name name of the table that should be dropped
226
     * @return void
227
     */
lsmith's avatar
lsmith committed
228
    public function dropTable($name)
229 230
    {
        //$this->conn->beginNestedTransaction();
231 232
        $result = $this->dropAutoincrement($name);
        $result = parent::dropTable($name);
233
        //$this->conn->completeNestedTransaction();
234 235 236 237 238 239 240 241 242 243 244 245 246 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 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
        return $result;
    }
    /**
     * 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 MDB2 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 MDB2 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
322
     * @return void
323
     */
lsmith's avatar
lsmith committed
324
    public function alterTable($name, array $changes, $check)
325
    {
326

327 328
        foreach ($changes as $changeName => $change) {
            switch ($changeName) {
329 330 331 332 333 334 335
                case 'add':
                case 'remove':
                case 'change':
                case 'name':
                case 'rename':
                    break;
                default:
zYne's avatar
zYne committed
336
                    throw new Doctrine_Export_Exception('change type "' . $changeName . '" not yet supported');
337 338 339 340
            }
        }

        if ($check) {
lsmith's avatar
lsmith committed
341
            return false;
342 343
        }

344
        $name = $this->conn->quoteIdentifier($name, true);
345

zYne's avatar
zYne committed
346
        if ( ! empty($changes['add']) && is_array($changes['add'])) {
347
            $fields = array();
zYne's avatar
zYne committed
348 349
            foreach ($changes['add'] as $fieldName => $field) {
                $fields[] = $this->conn->getDeclaration($field['type'], $fieldName, $field);
350
            }
zYne's avatar
zYne committed
351
            $result = $this->conn->exec('ALTER TABLE ' . $name . ' ADD (' . implode(', ', $fields) . ')');
352 353
        }

zYne's avatar
zYne committed
354
        if ( ! empty($changes['change']) && is_array($changes['change'])) {
355
            $fields = array();
zYne's avatar
zYne committed
356 357
            foreach ($changes['change'] as $fieldName => $field) {
                $fields[] = $fieldName. ' ' . $this->conn->getDeclaration($field['definition']['type'], '', $field['definition']);
358
            }
zYne's avatar
zYne committed
359
            $result = $this->conn->exec('ALTER TABLE ' . $name . ' MODIFY (' . implode(', ', $fields) . ')');
360 361
        }

zYne's avatar
zYne committed
362 363 364 365 366
        if ( ! empty($changes['rename']) && is_array($changes['rename'])) {
            foreach ($changes['rename'] as $fieldName => $field) {
                $query = 'ALTER TABLE ' . $name . ' RENAME COLUMN ' . $this->conn->quoteIdentifier($fieldName, true)
                       . ' TO ' . $this->conn->quoteIdentifier($field['name']);

367
                $result = $this->conn->exec($query);
368 369 370
            }
        }

zYne's avatar
zYne committed
371
        if ( ! empty($changes['remove']) && is_array($changes['remove'])) {
372
            $fields = array();
zYne's avatar
zYne committed
373 374
            foreach ($changes['remove'] as $fieldName => $field) {
                $fields[] = $this->conn->quoteIdentifier($fieldName, true);
375
            }
zYne's avatar
zYne committed
376
            $result = $this->conn->exec('ALTER TABLE ' . $name . ' DROP COLUMN ' . implode(', ', $fields));
377 378
        }

zYne's avatar
zYne committed
379 380 381
        if ( ! empty($changes['name'])) {
            $changeName = $this->conn->quoteIdentifier($changes['name'], true);
            $result = $this->conn->exec('ALTER TABLE ' . $name . ' RENAME TO ' . $changeName);
382 383
        }
    }
zYne's avatar
zYne committed
384 385 386 387 388 389 390 391 392
    /** 
     * getForeignKeyDeferredDeclaration
     *
     * @return string
     */
    public function getForeignKeyDeferredDeclaration($deferred)
    {
        return ($deferred) ? 'INITIALLY DEFERRED DEFERRABLE' : '';
    }
393 394 395
    /**
     * create sequence
     *
396
     * @param object $this->conn database object that is extended by this class
397
     * @param string $seqName name of the sequence to be created
398
     * @param string $start start value of the sequence; default is 1
zYne's avatar
zYne committed
399
     * @return void
400
     */
lsmith's avatar
lsmith committed
401 402
    public function createSequence($seqName, $start = 1)
    {
403 404 405
        $sequenceName = $this->conn->quoteIdentifier($this->conn->getSequenceName($seqName), true);
        $query = 'CREATE SEQUENCE ' . $sequenceName . ' START WITH ' . $start . ' INCREMENT BY 1 NOCACHE';
        $query.= ($start < 1 ? ' MINVALUE ' . $start : '');
zYne's avatar
zYne committed
406
        return $this->conn->exec($query);
407 408 409 410
    }
    /**
     * drop existing sequence
     *
411
     * @param object $this->conn database object that is extended by this class
412
     * @param string $seqName name of the sequence to be dropped
zYne's avatar
zYne committed
413
     * @return void
414
     */
lsmith's avatar
lsmith committed
415 416
    public function dropSequence($seqName)
    {
417
        $sequenceName = $this->conn->quoteIdentifier($this->conn->getSequenceName($seqName), true);
zYne's avatar
zYne committed
418
        return $this->conn->exec('DROP SEQUENCE ' . $sequenceName);
419 420
    }
}