Mysql.php 19.3 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
<?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_Mysql
 *
zYne's avatar
zYne committed
25 26
 * @package     Doctrine
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
27
 * @author      Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
zYne's avatar
zYne committed
28 29 30 31 32 33
 * @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_Mysql extends Doctrine_Export
{
36 37 38 39 40 41 42
   /**
     * create a new database
     *
     * @param string $name name of the database that should be created
     * @throws PDOException
     * @return void
     */
lsmith's avatar
lsmith committed
43 44
    public function createDatabase($name)
    {
45
        $query  = 'CREATE DATABASE ' . $this->conn->quoteIdentifier($name, true);
zYne's avatar
zYne committed
46
        $result = $this->conn->exec($query);
47 48 49 50 51 52 53 54
    }
    /**
     * drop an existing database
     *
     * @param string $name name of the database that should be dropped
     * @throws PDOException
     * @access public
     */
lsmith's avatar
lsmith committed
55 56
    public function dropDatabase($name)
    {
57
        $query  = 'DROP DATABASE ' . $this->conn->quoteIdentifier($name);
zYne's avatar
zYne committed
58
        $this->conn->exec($query);
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
    }
    /**
     * 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.
     *                          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:
     *                          array(
     *                              'comment' => 'Foo',
zYne's avatar
zYne committed
87
     *                              'charset' => 'utf8',
88 89 90 91 92
     *                              'collate' => 'utf8_unicode_ci',
     *                              'collate' => 'utf8_unicode_ci',
     *                              'type'    => 'innodb',
     *                          );
     *
zYne's avatar
zYne committed
93
     * @return void
94 95
     */
    public function createTable($name, array $fields, array $options = array()) {
lsmith's avatar
lsmith committed
96
        if ( ! $name)
zYne's avatar
zYne committed
97
            throw new Doctrine_Export_Exception('no valid table name specified');
zYne's avatar
zYne committed
98

lsmith's avatar
lsmith committed
99
        if (empty($fields)) {
zYne's avatar
zYne committed
100
            throw new Doctrine_Export_Exception('no fields specified for table "'.$name.'"');
lsmith's avatar
lsmith committed
101
        }
zYne's avatar
zYne committed
102
        $queryFields = $this->getFieldDeclarationList($fields);
103

104
        if (isset($options['primary']) && ! empty($options['primary'])) {
zYne's avatar
zYne committed
105
            $queryFields .= ', PRIMARY KEY(' . implode(', ', array_values($options['primary'])) . ')';
lsmith's avatar
lsmith committed
106
        }
zYne's avatar
zYne committed
107
        $name  = $this->conn->quoteIdentifier($name, true);
zYne's avatar
zYne committed
108
        $query = 'CREATE TABLE ' . $name . ' (' . $queryFields . ')';
109

zYne's avatar
zYne committed
110 111
        $optionStrings = array();

lsmith's avatar
lsmith committed
112
        if (isset($options['comment'])) {
113
            $optionStrings['comment'] = 'COMMENT = ' . $this->dbh->quote($options['comment'], 'text');
lsmith's avatar
lsmith committed
114 115
        }
        if (isset($options['charset'])) {
116
            $optionsSting['charset'] = 'DEFAULT CHARACTER SET ' . $options['charset'];
lsmith's avatar
lsmith committed
117
            if (isset($options['collate'])) {
118
                $optionStrings['charset'].= ' COLLATE ' . $options['collate'];
119 120 121 122
            }
        }

        $type = false;
zYne's avatar
zYne committed
123

124 125
        if (!empty($options['type'])) {
            $type = $options['type'];
126 127
        } else {
            $type = $this->conn->getAttribute(Doctrine::ATTR_DEFAULT_TABLE_TYPE);
128
        }
lsmith's avatar
lsmith committed
129

130
        if ($type) {
131
            $optionStrings[] = 'ENGINE = ' . $type;
132 133
        }

zYne's avatar
zYne committed
134 135
        if (!empty($optionStrings)) {
            $query.= ' '.implode(' ', $optionStrings);
136
        }
zYne's avatar
zYne committed
137
        return $this->conn->exec($query);
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 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    }
    /**
     * 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
zYne's avatar
zYne committed
223 224
     *                           can perform the requested table alterations if the value is true or
     *                           actually perform them otherwise.
225 226
     * @return boolean
     */
lsmith's avatar
lsmith committed
227 228
    public function alterTable($name, array $changes, $check)
    {
lsmith's avatar
lsmith committed
229
        if ( ! $name)
zYne's avatar
zYne committed
230
            throw new Doctrine_Export_Exception('no valid table name specified');
231

zYne's avatar
zYne committed
232 233
        foreach ($changes as $changeName => $change) {
            switch ($changeName) {
234 235 236 237 238
                case 'add':
                case 'remove':
                case 'change':
                case 'rename':
                case 'name':
239
                    break;
240
                default:
zYne's avatar
zYne committed
241
                    throw new Doctrine_Export_Exception('change type "'.$changeName.'" not yet supported');
242 243 244
            }
        }

lsmith's avatar
lsmith committed
245
        if ($check) {
246 247 248 249
            return true;
        }

        $query = '';
lsmith's avatar
lsmith committed
250
        if ( ! empty($changes['name'])) {
251 252 253 254
            $change_name = $this->conn->quoteIdentifier($changes['name'], true);
            $query .= 'RENAME TO ' . $change_name;
        }

lsmith's avatar
lsmith committed
255
        if ( ! empty($changes['add']) && is_array($changes['add'])) {
256 257 258 259
            foreach ($changes['add'] as $field_name => $field) {
                if ($query) {
                    $query.= ', ';
                }
260
                $query.= 'ADD ' . $this->getDeclaration($field['type'], $field_name, $field);
261 262 263
            }
        }

lsmith's avatar
lsmith committed
264
        if ( ! empty($changes['remove']) && is_array($changes['remove'])) {
265 266 267 268 269 270 271 272 273 274
            foreach ($changes['remove'] as $field_name => $field) {
                if ($query) {
                    $query.= ', ';
                }
                $field_name = $this->conn->quoteIdentifier($field_name, true);
                $query.= 'DROP ' . $field_name;
            }
        }

        $rename = array();
lsmith's avatar
lsmith committed
275
        if ( ! empty($changes['rename']) && is_array($changes['rename'])) {
276 277 278 279 280
            foreach ($changes['rename'] as $field_name => $field) {
                $rename[$field['name']] = $field_name;
            }
        }

lsmith's avatar
lsmith committed
281
        if ( ! empty($changes['change']) && is_array($changes['change'])) {
282 283 284 285 286 287 288 289 290 291 292
            foreach ($changes['change'] as $field_name => $field) {
                if ($query) {
                    $query.= ', ';
                }
                if (isset($rename[$field_name])) {
                    $old_field_name = $rename[$field_name];
                    unset($rename[$field_name]);
                } else {
                    $old_field_name = $field_name;
                }
                $old_field_name = $this->conn->quoteIdentifier($old_field_name, true);
293
                $query.= "CHANGE $old_field_name " . $this->getDeclaration($field['definition']['type'], $field_name, $field['definition']);
294 295 296
            }
        }

lsmith's avatar
lsmith committed
297
        if ( ! empty($rename) && is_array($rename)) {
298 299 300 301 302 303
            foreach ($rename as $rename_name => $renamed_field) {
                if ($query) {
                    $query.= ', ';
                }
                $field = $changes['rename'][$renamed_field];
                $renamed_field = $this->conn->quoteIdentifier($renamed_field, true);
304
                $query.= 'CHANGE ' . $renamed_field . ' ' . $this->getDeclaration($field['definition']['type'], $field['name'], $field['definition']);
305 306 307
            }
        }

lsmith's avatar
lsmith committed
308
        if ( ! $query) {
lsmith's avatar
lsmith committed
309
            return false;
310 311 312
        }

        $name = $this->conn->quoteIdentifier($name, true);
313
        return $this->conn->exec('ALTER TABLE ' . $name . ' ' . $query);
314 315 316 317
    }
    /**
     * create sequence
     *
zYne's avatar
zYne committed
318 319 320 321
     * @param string    $sequenceName name of the sequence to be created
     * @param string    $seqcol_name  the name of the sequence column
     * @param string    $start        start value of the sequence; default is 1
     * @return boolean
322
     */
zYne's avatar
zYne committed
323
    public function createSequence($sequenceName, $start = 1)
lsmith's avatar
lsmith committed
324
    {
gnat's avatar
gnat committed
325
        $sequenceName   = $this->conn->quoteIdentifier($this->conn->getSequenceName($sequenceName), true);
zYne's avatar
zYne committed
326 327
        $seqcolName     = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine::ATTR_SEQCOL_NAME), true);

zYne's avatar
zYne committed
328
        $query  = 'CREATE TABLE ' . $sequenceName
zYne's avatar
zYne committed
329
                . ' (' . $seqcolName . ' INT NOT NULL AUTO_INCREMENT, PRIMARY KEY ('
zYne's avatar
zYne committed
330
                . $seqcolName . '))'
zYne's avatar
zYne committed
331 332
                . strlen($this->conn->default_table_type) ? ' TYPE = '
                . $this->conn->default_table_type : '';
zYne's avatar
zYne committed
333

lsmith's avatar
lsmith committed
334
        $res    = $this->conn->exec($query);
335

zYne's avatar
zYne committed
336 337 338 339
        if ($start == 1)
            return true;

        $query  = 'INSERT INTO ' . $sequenceName
zYne's avatar
zYne committed
340
                . ' (' . $seqcolName . ') VALUES (' . ($start - 1) . ')';
341

lsmith's avatar
lsmith committed
342
        $res    = $this->conn->exec($query);
343 344

        // Handle error
zYne's avatar
zYne committed
345
        try {
lsmith's avatar
lsmith committed
346
            $result = $this->conn->exec('DROP TABLE ' . $sequenceName);
zYne's avatar
zYne committed
347
        } catch(Exception $e) {
zYne's avatar
zYne committed
348
            throw new Doctrine_Export_Exception('could not drop inconsistent sequence table');
349 350
        }

zYne's avatar
zYne committed
351
        throw new Doctrine_Export_Exception('could not create sequence table');
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
    }
    /**
     * Get the stucture of a field into an array
     *
     * @author Leoncx
     * @param string    $table         name of the table on which the index is to be created
     * @param string    $name          name of the index to be created
     * @param array     $definition    associative array that defines properties of the index to be created.
     *                                 Currently, only one property named FIELDS is supported. This property
     *                                 is also an associative with the names of the index fields as array
     *                                 indexes. Each entry of this array is set to another type of associative
     *                                 array that specifies properties of the index that are specific to
     *                                 each field.
     *
     *                                 Currently, only the sorting property is supported. It should be used
     *                                 to define the sorting direction of the index. It may be set to either
     *                                 ascending or descending.
     *
     *                                 Not all DBMS support index sorting direction configuration. The DBMS
     *                                 drivers of those that do not support it ignore this property. Use the
     *                                 function supports() to determine whether the DBMS driver can manage indexes.
     *
     *                                 Example
     *                                    array(
     *                                        'fields' => array(
     *                                            'user_name' => array(
     *                                                'sorting' => 'ascending'
     *                                                'length' => 10
     *                                            ),
     *                                            'last_login' => array()
     *                                        )
     *                                    )
     * @throws PDOException
     * @return void
     */
lsmith's avatar
lsmith committed
387 388
    public function createIndex($table, $name, array $definition)
    {
389
        $table  = $table;
390
        $name   = $this->conn->getIndexName($name);
391 392 393 394 395 396 397 398 399 400
        $query  = 'CREATE INDEX ' . $name . ' ON ' . $table;
        $fields = array();
        foreach ($definition['fields'] as $field => $fieldinfo) {
            if (!empty($fieldinfo['length'])) {
                $fields[] = $field . '(' . $fieldinfo['length'] . ')';
            } else {
                $fields[] = $field;
            }
        }
        $query .= ' ('. implode(', ', $fields) . ')';
401

zYne's avatar
zYne committed
402
        return $this->conn->exec($query);
403 404 405 406 407 408
    }
    /**
     * drop existing index
     *
     * @param string    $table          name of table that should be used in method
     * @param string    $name           name of the index to be dropped
zYne's avatar
zYne committed
409
     * @return void
410
     */
lsmith's avatar
lsmith committed
411 412
    public function dropIndex($table, $name)
    {
413
        $table  = $this->conn->quoteIdentifier($table, true);
414
        $name   = $this->conn->quoteIdentifier($this->conn->getIndexName($name), true);
zYne's avatar
zYne committed
415
        return $this->conn->exec('DROP INDEX ' . $name . ' ON ' . $table);
416 417 418 419 420 421
    }
    /**
     * dropTable
     *
     * @param string    $table          name of table that should be dropped from the database
     * @throws PDOException
zYne's avatar
zYne committed
422
     * @return void
423
     */
lsmith's avatar
lsmith committed
424 425
    public function dropTable($table)
    {
zYne's avatar
zYne committed
426
        $table  = $this->conn->quoteIdentifier($table, true);
zYne's avatar
zYne committed
427
        $this->conn->exec('DROP TABLE ' . $table);
428 429
    }
}
lsmith's avatar
lsmith committed
430