Mysql.php 23.7 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
     *                              'collate' => 'utf8_unicode_ci',
     *                              'type'    => 'innodb',
     *                          );
     *
zYne's avatar
zYne committed
92
     * @return void
93
     */
zYne's avatar
zYne committed
94
    public function createTableSql($name, array $fields, array $options = array()) {
lsmith's avatar
lsmith committed
95
        if ( ! $name)
zYne's avatar
zYne committed
96
            throw new Doctrine_Export_Exception('no valid table name specified');
zYne's avatar
zYne committed
97

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

zYne's avatar
zYne committed
103 104 105 106 107
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
            foreach($options['indexes'] as $index => $definition) {
                $queryFields .= ', ' . $this->getIndexDeclaration($index, $definition);
            }
        }
108 109 110 111 112 113 114

        if (isset($options['foreignKeys']) && ! empty($options['foreignKeys'])) {
            foreach($options['foreignKeys'] as $definition) {
                $queryFields .= ', ' . $this->getForeignKeyDeclaration($definition);
            }
        }

zYne's avatar
zYne committed
115 116 117 118 119
        if (isset($options['primary']) && ! empty($options['primary'])) {
            $queryFields .= ', PRIMARY KEY(' . implode(', ', array_values($options['primary'])) . ')';
        }


zYne's avatar
zYne committed
120

zYne's avatar
zYne committed
121
        $name  = $this->conn->quoteIdentifier($name, true);
zYne's avatar
zYne committed
122
        $query = 'CREATE TABLE ' . $name . ' (' . $queryFields . ')';
123

zYne's avatar
zYne committed
124 125
        $optionStrings = array();

lsmith's avatar
lsmith committed
126
        if (isset($options['comment'])) {
127
            $optionStrings['comment'] = 'COMMENT = ' . $this->dbh->quote($options['comment'], 'text');
lsmith's avatar
lsmith committed
128 129
        }
        if (isset($options['charset'])) {
fabien's avatar
fabien committed
130
            $optionStrings['charset'] = 'DEFAULT CHARACTER SET ' . $options['charset'];
lsmith's avatar
lsmith committed
131
            if (isset($options['collate'])) {
132
                $optionStrings['charset'].= ' COLLATE ' . $options['collate'];
133 134 135 136
            }
        }

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

138 139
        if (!empty($options['type'])) {
            $type = $options['type'];
140 141
        } else {
            $type = $this->conn->getAttribute(Doctrine::ATTR_DEFAULT_TABLE_TYPE);
142
        }
lsmith's avatar
lsmith committed
143

144
        if ($type) {
145
            $optionStrings[] = 'ENGINE = ' . $type;
146 147
        }

zYne's avatar
zYne committed
148 149
        if (!empty($optionStrings)) {
            $query.= ' '.implode(' ', $optionStrings);
150
        }
zYne's avatar
zYne committed
151
        return $query;
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 223 224 225 226 227 228 229 230 231 232 233 234 235 236
    }
    /**
     * 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
237 238
     *                           can perform the requested table alterations if the value is true or
     *                           actually perform them otherwise.
239 240
     * @return boolean
     */
zYne's avatar
zYne committed
241
    public function alterTableSql($name, array $changes, $check)
lsmith's avatar
lsmith committed
242
    {
lsmith's avatar
lsmith committed
243
        if ( ! $name)
zYne's avatar
zYne committed
244
            throw new Doctrine_Export_Exception('no valid table name specified');
245

zYne's avatar
zYne committed
246 247
        foreach ($changes as $changeName => $change) {
            switch ($changeName) {
248 249 250 251 252
                case 'add':
                case 'remove':
                case 'change':
                case 'rename':
                case 'name':
253
                    break;
254
                default:
zYne's avatar
zYne committed
255
                    throw new Doctrine_Export_Exception('change type "'.$changeName.'" not yet supported');
256 257 258
            }
        }

lsmith's avatar
lsmith committed
259
        if ($check) {
260 261 262 263
            return true;
        }

        $query = '';
lsmith's avatar
lsmith committed
264
        if ( ! empty($changes['name'])) {
265 266 267 268
            $change_name = $this->conn->quoteIdentifier($changes['name'], true);
            $query .= 'RENAME TO ' . $change_name;
        }

lsmith's avatar
lsmith committed
269
        if ( ! empty($changes['add']) && is_array($changes['add'])) {
270 271 272 273
            foreach ($changes['add'] as $field_name => $field) {
                if ($query) {
                    $query.= ', ';
                }
274
                $query.= 'ADD ' . $this->getDeclaration($field['type'], $field_name, $field);
275 276 277
            }
        }

lsmith's avatar
lsmith committed
278
        if ( ! empty($changes['remove']) && is_array($changes['remove'])) {
279 280 281 282 283 284 285 286 287 288
            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
289
        if ( ! empty($changes['rename']) && is_array($changes['rename'])) {
290 291 292 293 294
            foreach ($changes['rename'] as $field_name => $field) {
                $rename[$field['name']] = $field_name;
            }
        }

lsmith's avatar
lsmith committed
295
        if ( ! empty($changes['change']) && is_array($changes['change'])) {
zYne's avatar
zYne committed
296
            foreach ($changes['change'] as $fieldName => $field) {
297 298 299
                if ($query) {
                    $query.= ', ';
                }
zYne's avatar
zYne committed
300 301 302
                if (isset($rename[$fieldName])) {
                    $oldFieldName = $rename[$fieldName];
                    unset($rename[$fieldName]);
303
                } else {
zYne's avatar
zYne committed
304
                    $oldFieldName = $fieldName;
305
                }
zYne's avatar
zYne committed
306 307
                $oldFieldName = $this->conn->quoteIdentifier($old_field_name, true);
                $query .= "CHANGE $oldFieldName " . $this->getDeclaration($field['definition']['type'], $fieldName, $field['definition']);
308 309 310
            }
        }

lsmith's avatar
lsmith committed
311
        if ( ! empty($rename) && is_array($rename)) {
312 313 314 315 316 317
            foreach ($rename as $rename_name => $renamed_field) {
                if ($query) {
                    $query.= ', ';
                }
                $field = $changes['rename'][$renamed_field];
                $renamed_field = $this->conn->quoteIdentifier($renamed_field, true);
318
                $query.= 'CHANGE ' . $renamed_field . ' ' . $this->getDeclaration($field['definition']['type'], $field['name'], $field['definition']);
319 320 321
            }
        }

lsmith's avatar
lsmith committed
322
        if ( ! $query) {
lsmith's avatar
lsmith committed
323
            return false;
324 325 326
        }

        $name = $this->conn->quoteIdentifier($name, true);
327
        return $this->conn->exec('ALTER TABLE ' . $name . ' ' . $query);
328 329 330 331
    }
    /**
     * create sequence
     *
zYne's avatar
zYne committed
332 333 334 335
     * @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
336
     */
zYne's avatar
zYne committed
337
    public function createSequence($sequenceName, $start = 1)
lsmith's avatar
lsmith committed
338
    {
gnat's avatar
gnat committed
339
        $sequenceName   = $this->conn->quoteIdentifier($this->conn->getSequenceName($sequenceName), true);
zYne's avatar
zYne committed
340 341
        $seqcolName     = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine::ATTR_SEQCOL_NAME), true);

342 343 344 345 346 347 348 349 350 351 352
        try {
            $query  = 'CREATE TABLE ' . $sequenceName
                    . ' (' . $seqcolName . ' INT NOT NULL AUTO_INCREMENT, PRIMARY KEY ('
                    . $seqcolName . '))'
                    . strlen($this->conn->default_table_type) ? ' TYPE = '
                    . $this->conn->default_table_type : '';
    
            $res    = $this->conn->exec($query);
        } catch(Doctrine_Connection_Exception $e) {
            throw new Doctrine_Export_Exception('could not create sequence table');
        }
353

zYne's avatar
zYne committed
354 355 356 357
        if ($start == 1)
            return true;

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

lsmith's avatar
lsmith committed
360
        $res    = $this->conn->exec($query);
361 362

        // Handle error
zYne's avatar
zYne committed
363
        try {
lsmith's avatar
lsmith committed
364
            $result = $this->conn->exec('DROP TABLE ' . $sequenceName);
365
        } catch(Doctrine_Connection_Exception $e) {
zYne's avatar
zYne committed
366
            throw new Doctrine_Export_Exception('could not drop inconsistent sequence table');
367 368
        }

369

370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
    }
    /**
     * 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(
zYne's avatar
zYne committed
396
     *                                                'sorting' => 'ASC'
397 398 399 400 401 402 403 404
     *                                                'length' => 10
     *                                            ),
     *                                            'last_login' => array()
     *                                        )
     *                                    )
     * @throws PDOException
     * @return void
     */
zYne's avatar
zYne committed
405
    public function createIndexSql($table, $name, array $definition)
lsmith's avatar
lsmith committed
406
    {
407
        $table  = $table;
408
        $name   = $this->conn->getIndexName($name);
zYne's avatar
zYne committed
409 410 411
        $type   = '';
        if(isset($definition['type'])) {
            switch (strtolower($definition['type'])) {
zYne's avatar
zYne committed
412 413
                case 'fulltext':
                case 'unique':
zYne's avatar
zYne committed
414
                    $type = strtoupper($definition['type']) . ' ';
zYne's avatar
zYne committed
415 416
                break;
                default:
zYne's avatar
zYne committed
417
                    throw new Doctrine_Export_Exception('Unknown index type ' . $definition['type']);
zYne's avatar
zYne committed
418 419 420
            }
        }
        $query  = 'CREATE ' . $type . 'INDEX ' . $name . ' ON ' . $table;
zYne's avatar
zYne committed
421
        $query .= ' ('. $this->getIndexFieldDeclarationList() . ')';
zYne's avatar
zYne committed
422

zYne's avatar
zYne committed
423 424
        return $query;
    }
zYne's avatar
zYne committed
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
    /** 
     * getDefaultDeclaration
     * Obtain DBMS specific SQL code portion needed to set a default value
     * declaration to be used in statements like CREATE TABLE.
     *
     * @param array $field      field definition array
     * @return string           DBMS specific SQL code portion needed to set a default value
     */
    public function getDefaultFieldDeclaration($field)
    {
        $default = '';
        if (isset($field['default']) && $field['length'] <= 255) {
            if ($field['default'] === '') {
                $field['default'] = empty($field['notnull'])
                    ? null : $this->valid_default_values[$field['type']];

                if ($field['default'] === ''
                    && ($conn->getAttribute(Doctrine::ATTR_PORTABILITY) & Doctrine::PORTABILITY_EMPTY_TO_NULL)
                ) {
                    $field['default'] = ' ';
                }
            }
    
            $default = ' DEFAULT ' . $this->conn->quote($field['default'], $field['type']);
        }
        return $default;
    }
zYne's avatar
zYne committed
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
    /**
     * Obtain DBMS specific SQL code portion needed to set an index 
     * declaration to be used in statements like CREATE TABLE.
     *
     * @param string $charset       name of the index
     * @param array $definition     index definition
     * @return string  DBMS specific SQL code portion needed to set an index
     */
    public function getIndexDeclaration($name, array $definition)
    {
        $name   = $this->conn->quoteIdentifier($name);
        $type   = '';
        if(isset($definition['type'])) {
            switch (strtolower($definition['type'])) {
                case 'fulltext':
                case 'unique':
                    $type = strtoupper($definition['type']) . ' ';
                break;
                default:
                    throw new Doctrine_Export_Exception('Unknown index type ' . $definition['type']);
472 473
            }
        }
zYne's avatar
zYne committed
474
        
475
        if ( ! isset($definition['fields'])) {
zYne's avatar
zYne committed
476 477
            throw new Doctrine_Export_Exception('No index columns given.');
        }
478 479 480
        if ( ! is_array($definition['fields'])) {
            $definition['fields'] = array($definition['fields']);
        }
zYne's avatar
zYne committed
481 482

        $query = $type . 'INDEX ' . $name;
483

zYne's avatar
zYne committed
484 485
        $query .= ' (' . $this->getIndexFieldDeclarationList($definition['fields']) . ')';
        
zYne's avatar
zYne committed
486
        return $query;
487
    }
zYne's avatar
zYne committed
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
    /**
     * getIndexFieldDeclarationList
     * Obtain DBMS specific SQL code portion needed to set an index
     * declaration to be used in statements like CREATE TABLE.
     *
     * @return string
     */
    public function getIndexFieldDeclarationList(array $fields)
    {
    	$declFields = array();

        foreach ($fields as $fieldName => $field) {
            $fieldString = $fieldName;

            if (is_array($field)) {
                if (isset($field['length'])) {
                    $fieldString .= '(' . $field['length'] . ')';
                }

                if (isset($field['sorting'])) {
                    $sort = strtoupper($field['sorting']);
                    switch ($sort) {
                        case 'ASC':
                        case 'DESC':
                            $fieldString .= ' ' . $sort;
                            break;
                        default:
                            throw new Doctrine_Export_Exception('Unknown index sorting option given.');
                    }
                }
            } else {
                $fieldString = $field;
            }
            $declFields[] = $fieldString;
        }
        return implode(', ', $declFields);
    }
525 526 527 528 529
    /**
     * 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
530
     * @return void
531
     */
lsmith's avatar
lsmith committed
532 533
    public function dropIndex($table, $name)
    {
534
        $table  = $this->conn->quoteIdentifier($table, true);
535
        $name   = $this->conn->quoteIdentifier($this->conn->getIndexName($name), true);
zYne's avatar
zYne committed
536
        return $this->conn->exec('DROP INDEX ' . $name . ' ON ' . $table);
537 538 539 540 541 542
    }
    /**
     * dropTable
     *
     * @param string    $table          name of table that should be dropped from the database
     * @throws PDOException
zYne's avatar
zYne committed
543
     * @return void
544
     */
lsmith's avatar
lsmith committed
545 546
    public function dropTable($table)
    {
zYne's avatar
zYne committed
547
        $table  = $this->conn->quoteIdentifier($table, true);
zYne's avatar
zYne committed
548
        $this->conn->exec('DROP TABLE ' . $table);
549 550
    }
}
lsmith's avatar
lsmith committed
551