Export.php 36.4 KB
Newer Older
zYne's avatar
zYne committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
<?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>.
 */
zYne's avatar
zYne committed
21
Doctrine::autoload('Doctrine_Connection_Module');
zYne's avatar
zYne committed
22 23 24
/**
 * Doctrine_Export
 *
25 26
 * @package     Doctrine
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
zYne's avatar
zYne committed
27
 * @author      Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
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 extends Doctrine_Connection_Module
{
36 37
    /**
     * drop an existing database
38
     * (this method is implemented by the drivers)
39 40 41 42
     *
     * @param string $name name of the database that should be dropped
     * @return void
     */
lsmith's avatar
lsmith committed
43 44
    public function dropDatabase($database)
    {
45 46
        throw new Doctrine_Export_Exception('Drop database not supported by this driver.');
    }
47 48
    /**
     * dropTable
zYne's avatar
zYne committed
49
     * drop an existing table
50
     *
zYne's avatar
zYne committed
51
     * @param string $table           name of table that should be dropped from the database
52 53 54
     * @throws PDOException
     * @return void
     */
lsmith's avatar
lsmith committed
55 56
    public function dropTable($table)
    {
zYne's avatar
zYne committed
57
        $this->conn->execute('DROP TABLE ' . $table);
58
    }
59 60 61 62

    /**
     * drop existing index
     *
zYne's avatar
zYne committed
63
     * @param string    $table        name of table that should be used in method
64 65 66
     * @param string    $name         name of the index to be dropped
     * @return void
     */
lsmith's avatar
lsmith committed
67 68
    public function dropIndex($table, $name)
    {
69
        $name = $this->conn->quoteIdentifier($this->conn->getIndexName($name), true);
zYne's avatar
zYne committed
70
        return $this->conn->exec('DROP INDEX ' . $name);
71 72 73 74 75 76 77 78 79
    }
    /**
     * drop existing constraint
     *
     * @param string    $table        name of table that should be used in method
     * @param string    $name         name of the constraint to be dropped
     * @param string    $primary      hint if the constraint is primary
     * @return void
     */
lsmith's avatar
lsmith committed
80 81
    public function dropConstraint($table, $name, $primary = false)
    {
82 83
        $table = $this->conn->quoteIdentifier($table, true);
        $name  = $this->conn->quoteIdentifier($this->conn->getIndexName($name), true);
zYne's avatar
zYne committed
84
        return $this->conn->exec('ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $name);
85 86 87
    }
    /**
     * drop existing sequence
88
     * (this method is implemented by the drivers)
89 90 91 92
     *
     * @param string    $seq_name     name of the sequence to be dropped
     * @return void
     */
lsmith's avatar
lsmith committed
93 94
    public function dropSequence($name)
    {
95 96 97 98
        throw new Doctrine_Export_Exception('Drop sequence not supported by this driver.');
    }
    /**
     * create a new database
99
     * (this method is implemented by the drivers)
100 101 102 103
     *
     * @param string $name name of the database that should be created
     * @return void
     */
lsmith's avatar
lsmith committed
104 105
    public function createDatabase($database)
    {
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
        throw new Doctrine_Export_Exception('Create database not supported by this driver.');
    }
    /**
     * 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:
     *
zYne's avatar
zYne committed
134
     * @return string
135
     */
zYne's avatar
zYne committed
136
    public function createTableSql($name, array $fields, array $options = array())
zYne's avatar
zYne committed
137 138
    {
        if ( ! $name) {
139
            throw new Doctrine_Export_Exception('no valid table name specified');
zYne's avatar
zYne committed
140 141
        }
        
lsmith's avatar
lsmith committed
142
        if (empty($fields)) {
143
            throw new Doctrine_Export_Exception('no fields specified for table '.$name);
lsmith's avatar
lsmith committed
144
        }
145
        $queryFields = $this->getFieldDeclarationList($fields);
146

zYne's avatar
zYne committed
147 148 149 150 151 152
        if (isset($options['foreignKeys']) && ! empty($options['foreignKeys'])) {
            foreach($options['foreignKeys'] as $definition) {
                $queryFields .= ', ' . $this->getForeignKeyDeclaration($definition);
            }
        }

153
        if (isset($options['primary']) && ! empty($options['primary'])) {
zYne's avatar
zYne committed
154 155
            $queryFields .= ', PRIMARY KEY(' . implode(', ', array_values($options['primary'])) . ')';
        }
zYne's avatar
zYne committed
156
        
zYne's avatar
zYne committed
157 158 159 160
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
            foreach($options['indexes'] as $index => $definition) {
                $queryFields .= ', ' . $this->getIndexDeclaration($index, $definition);
            }
161 162
        }

163 164
        $name  = $this->conn->quoteIdentifier($name, true);
        $query = 'CREATE TABLE ' . $name . ' (' . $queryFields . ')';
zYne's avatar
zYne committed
165

zYne's avatar
zYne committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
        return $query;
    }
    /**
     * 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
     * @param array $options  An associative array of table options:
     * @see Doctrine_Export::createTableSql()
     *
     * @return void
     */
    public function createTable($name, array $fields, array $options = array())
    {
        return $this->conn->execute($this->createTableSql($name, $fields, $options));
181 182 183 184
    }
    /**
     * create sequence
     *
zYne's avatar
zYne committed
185 186
     * @param string    $seqName        name of the sequence to be created
     * @param string    $start          start value of the sequence; default is 1
187 188
     * @return void
     */
zYne's avatar
zYne committed
189
    public function createSequence($seqName, $start = 1)
zYne's avatar
zYne committed
190 191 192 193 194 195 196 197 198 199 200 201
    {
        return $this->conn->execute($this->createSequenceSql($seqName, $start = 1));  
    }
    /**
     * return RDBMS specific create sequence statement
     * (this method is implemented by the drivers)
     *
     * @param string    $seqName        name of the sequence to be created
     * @param string    $start          start value of the sequence; default is 1
     * @return string
     */
    public function createSequenceSql($seqName, $start = 1)
lsmith's avatar
lsmith committed
202
    {
203 204
        throw new Doctrine_Export_Exception('Create sequence not supported by this driver.');
    }
205
    /**
206 207 208 209 210 211 212 213 214 215
     * create a constraint on a table
     *
     * @param string    $table         name of the table on which the constraint is to be created
     * @param string    $name          name of the constraint to be created
     * @param array     $definition    associative array that defines properties of the constraint to be created.
     *                                 Currently, only one property named FIELDS is supported. This property
     *                                 is also an associative with the names of the constraint fields as array
     *                                 constraints. Each entry of this array is set to another type of associative
     *                                 array that specifies properties of the constraint that are specific to
     *                                 each field.
216
     *
217 218 219 220 221 222 223 224 225
     *                                 Example
     *                                    array(
     *                                        'fields' => array(
     *                                            'user_name' => array(),
     *                                            'last_login' => array()
     *                                        )
     *                                    )
     * @return void
     */
lsmith's avatar
lsmith committed
226 227
    public function createConstraint($table, $name, $definition)
    {
228 229
        $table = $this->conn->quoteIdentifier($table, true);
        $name = $this->conn->quoteIdentifier($this->conn->getIndexName($name), true);
230
        $query = 'ALTER TABLE ' . $table . ' ADD CONSTRAINT ' . $name;
231
        if (!empty($definition['primary'])) {
232
            $query .= ' PRIMARY KEY';
233
        } elseif (!empty($definition['unique'])) {
234
            $query .= ' UNIQUE';
235 236 237
        }
        $fields = array();
        foreach (array_keys($definition['fields']) as $field) {
238
            $fields[] = $this->conn->quoteIdentifier($field, true);
239 240
        }
        $query .= ' ('. implode(', ', $fields) . ')';
zYne's avatar
zYne committed
241
        return $this->conn->exec($query);
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
     * Get the stucture of a field into an array
     *
     * @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'
     *                                            ),
     *                                            'last_login' => array()
     *                                        )
     *                                    )
     * @return void
     */
lsmith's avatar
lsmith committed
274 275
    public function createIndex($table, $name, array $definition)
    {
zYne's avatar
zYne committed
276
        return $this->conn->execute($this->createIndexSql($table, $name, $definition));
277 278 279 280 281 282 283
    }
    /**
     * Get the stucture of a field into an array
     *
     * @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.
284
     * @see Doctrine_Export::createIndex()
285 286
     * @return string
     */
lsmith's avatar
lsmith committed
287 288
    public function createIndexSql($table, $name, array $definition)
    {
289 290
        $table  = $this->conn->quoteIdentifier($table);
        $name   = $this->conn->quoteIdentifier($name);
zYne's avatar
zYne committed
291
        $type   = '';
zYne's avatar
zYne committed
292

zYne's avatar
zYne committed
293 294 295 296 297 298 299 300 301 302 303
        if(isset($definition['type'])) {
            switch (strtolower($definition['type'])) {
                case 'unique':
                    $type = strtoupper($definition['type']) . ' ';
                break;
                default:
                    throw new Doctrine_Export_Exception('Unknown index type ' . $definition['type']);
            }
        }

        $query = 'CREATE ' . $type . 'INDEX ' . $name . ' ON ' . $table;
304 305 306 307 308

        $fields = array();
        foreach (array_keys($definition['fields']) as $field) {
            $fields[] = $this->conn->quoteIdentifier($field);
        }
zYne's avatar
zYne committed
309
        $query .= ' (' . implode(', ', $fields) . ')';
zYne's avatar
zYne committed
310

311
        return $query;
312 313 314 315 316 317 318 319 320 321 322
    }
    /**
     * createForeignKey
     *
     * @param string    $table         name of the table on which the index is to be created
     * @param string    $name          name of the foreign key to be created
     * @param array     $definition    associative array that defines properties of the foreign key to be created.
     */
    public function createForeignKey($table, $name, array $definition)
    {

323
    }
324 325
    /**
     * alter an existing table
326
     * (this method is implemented by the drivers)
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 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 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
     *
     * @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.
     * @return void
     */
lsmith's avatar
lsmith committed
413 414
    public function alterTable($name, array $changes, $check)
    {
zYne's avatar
zYne committed
415
        $this->conn->execute($this->alterTableSql($name, $changes, $check));
416 417
    }
    /**
zYne's avatar
zYne committed
418
     * generates the sql for altering an existing table
419 420
     * (this method is implemented by the drivers)
     *
zYne's avatar
zYne committed
421 422 423 424 425 426
     * @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      *
     * @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.
     * @see Doctrine_Export::alterTable()
427 428
     * @return string
     */
lsmith's avatar
lsmith committed
429 430
    public function alterTableSql($name, array $changes, $check)
    {
431 432 433 434 435
        throw new Doctrine_Export_Exception('Alter table not supported by this driver.');
    }
    /**
     * Get declaration of a number of field in bulk
     *
zYne's avatar
zYne committed
436
     * @param array $fields  a multidimensional associative array.
437 438 439 440 441
     *      The first dimension determines the field name, while the second
     *      dimension is keyed with the name of the properties
     *      of the field being declared as array indexes. Currently, the types
     *      of supported field properties are as follows:
     *
zYne's avatar
zYne committed
442 443 444 445 446
     *      length
     *          Integer value that determines the maximum length of the text
     *          field. If this argument is missing the field should be
     *          declared to have the longest length allowed by the DBMS.
     *
447
     *      default
zYne's avatar
zYne committed
448
     *          Text value to be used as default for this field.
449 450 451 452
     *
     *      notnull
     *          Boolean flag that indicates whether this field is constrained
     *          to not be set to null.
zYne's avatar
zYne committed
453 454 455 456
     *      charset
     *          Text value with the default CHARACTER SET for this field.
     *      collation
     *          Text value with the default COLLATION for this field.
zYne's avatar
zYne committed
457 458
     *      unique
     *          unique constraint
459 460 461
     *
     * @return string
     */
lsmith's avatar
lsmith committed
462 463
    public function getFieldDeclarationList(array $fields)
    {
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
        foreach ($fields as $fieldName => $field) {
            $query = $this->getDeclaration($fieldName, $field);

            $queryFields[] = $query;
        }
        return implode(', ', $queryFields);
    }
    /**
     * Obtain DBMS specific SQL code portion needed to declare a generic type
     * field to be used in statements like CREATE TABLE.
     *
     * @param string $name   name the field to be declared.
     * @param array  $field  associative array with the name of the properties
     *      of the field being declared as array indexes. Currently, the types
     *      of supported field properties are as follows:
     *
     *      length
     *          Integer value that determines the maximum length of the text
     *          field. If this argument is missing the field should be
     *          declared to have the longest length allowed by the DBMS.
     *
     *      default
     *          Text value to be used as default for this field.
     *
     *      notnull
     *          Boolean flag that indicates whether this field is constrained
     *          to not be set to null.
     *      charset
     *          Text value with the default CHARACTER SET for this field.
     *      collation
     *          Text value with the default COLLATION for this field.
zYne's avatar
zYne committed
495 496
     *      unique
     *          unique constraint
zYne's avatar
zYne committed
497 498
     *      check   
     *          column check constraint
zYne's avatar
zYne committed
499
     *
500 501 502
     * @return string  DBMS specific SQL code portion that should be used to
     *      declare the specified field.
     */
lsmith's avatar
lsmith committed
503 504
    public function getDeclaration($name, array $field)
    {
505

zYne's avatar
zYne committed
506
        $default   = $this->getDefaultFieldDeclaration($field);
507

zYne's avatar
zYne committed
508 509 510 511 512
        $charset   = (isset($field['charset']) && $field['charset']) ?
                    ' ' . $this->getCharsetFieldDeclaration($field['charset']) : '';

        $collation = (isset($field['collation']) && $field['collation']) ?
                    ' ' . $this->getCollationFieldDeclaration($field['collation']) : '';
lsmith's avatar
lsmith committed
513

zYne's avatar
zYne committed
514
        $notnull   = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : '';
lsmith's avatar
lsmith committed
515

zYne's avatar
zYne committed
516 517
        $unique    = (isset($field['unique']) && $field['unique']) ?
                    ' ' . $this->getUniqueFieldDeclaration() : '';
zYne's avatar
zYne committed
518 519 520
                    
        $check     = (isset($field['check']) && $field['check']) ?
                    ' ' . $field['check'] : '';
521 522 523

        $method = 'get' . $field['type'] . 'Declaration';

lsmith's avatar
lsmith committed
524
        if (method_exists($this->conn->dataDict, $method)) {
525
            return $this->conn->dataDict->$method($name, $field);
lsmith's avatar
lsmith committed
526
        } else {
527
            $dec = $this->conn->dataDict->getNativeDeclaration($field);
lsmith's avatar
lsmith committed
528
        }
zYne's avatar
zYne committed
529
        return $this->conn->quoteIdentifier($name, true) . ' ' . $dec . $charset . $default . $notnull . $unique . $check . $collation;
zYne's avatar
zYne committed
530
    }
zYne's avatar
zYne committed
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
    /**
     * 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'])) {
            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'] = ' ';
                }
            }
    
zYne's avatar
zYne committed
554 555 556
            if ($field['type'] === 'boolean') {
                $fields['default'] = $this->conn->convertBooleans($field['default']);                                 	
            }
zYne's avatar
zYne committed
557 558 559 560
            $default = ' DEFAULT ' . $this->conn->quote($field['default'], $field['type']);
        }
        return $default;
    }
zYne's avatar
zYne committed
561 562 563 564 565 566
    /**
     * 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
zYne's avatar
zYne committed
567
     * @return string               DBMS specific SQL code portion needed to set an index
zYne's avatar
zYne committed
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
     */
    public function getIndexDeclaration($name, array $definition)
    {
        $name   = $this->conn->quoteIdentifier($name);
        $type   = '';

        if (isset($definition['type'])) {
            if (strtolower($definition['type']) == 'unique') {
                $type = strtoupper($definition['type']) . ' ';
            } else {
                throw new Doctrine_Export_Exception('Unknown index type ' . $definition['type']);
            }
        }
        
        if ( ! isset($definition['fields']) || ! is_array($definition['fields'])) {
            throw new Doctrine_Export_Exception('No index columns given.');
        }

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

        $query .= ' (' . $this->getIndexFieldDeclarationList($definition['fields']) . ')';
        
        return $query;
    }
    /**
     * 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)
    {
zYne's avatar
zYne committed
601
    	$ret = array();
zYne's avatar
zYne committed
602 603
        foreach ($fields as $field => $definition) {
            if(is_array($definition)) {
zYne's avatar
zYne committed
604
                $ret[] = $this->conn->quoteIdentifier($field);
zYne's avatar
zYne committed
605
            } else {
zYne's avatar
zYne committed
606
                $ret[] = $this->conn->quoteIdentifier($definition);
zYne's avatar
zYne committed
607 608
            }
        }
zYne's avatar
zYne committed
609
        return implode(', ', $ret);
zYne's avatar
zYne committed
610
    }
zYne's avatar
zYne committed
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
    /**
     * A method to return the required SQL string that fits between CREATE ... TABLE
     * to create the table as a temporary table.
     *
     * Should be overridden in driver classes to return the correct string for the
     * specific database type.
     *
     * The default is to return the string "TEMPORARY" - this will result in a
     * SQL error for any database that does not support temporary tables, or that
     * requires a different SQL command from "CREATE TEMPORARY TABLE".
     *
     * @return string The string required to be placed between "CREATE" and "TABLE"
     *                to generate a temporary table, if possible.
     */
    public function getTemporaryTableQuery()
    {
        return 'TEMPORARY';
    }
zYne's avatar
zYne committed
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
    /**
     * getForeignKeyDeclaration
     * Obtain DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
     * of a field declaration to be used in statements like CREATE TABLE.
     *
     * @param array $definition         an associative array with the following structure:
     *          name                    optional constraint name
     * 
     *          local                   the local field(s)
     *
     *          foreign                 the foreign reference field(s)
     *
     *          foreignTable            the name of the foreign table
     *
     *          onDelete                referential delete action
     *  
     *          onUpdate                referential update action
     *
zYne's avatar
zYne committed
647 648
     *          deferred                deferred constraint checking
     *
zYne's avatar
zYne committed
649 650 651
     * The onDelete and onUpdate keys accept the following values:
     *
     * CASCADE: Delete or update the row from the parent table and automatically delete or 
652
     *          update the matching rows in the child table. Both ON DELETE CASCADE and ON UPDATE CASCADE are supported.
zYne's avatar
zYne committed
653 654 655 656 657 658 659 660
     *          Between two tables, you should not define several ON UPDATE CASCADE clauses that act on the same column
     *          in the parent table or in the child table.
     *
     * SET NULL: Delete or update the row from the parent table and set the foreign key column or columns in the
     *          child table to NULL. This is valid only if the foreign key columns do not have the NOT NULL qualifier 
     *          specified. Both ON DELETE SET NULL and ON UPDATE SET NULL clauses are supported.
     *
     * NO ACTION: In standard SQL, NO ACTION means no action in the sense that an attempt to delete or update a primary 
661
     *           key value is not allowed to proceed if there is a related foreign key value in the referenced table.
zYne's avatar
zYne committed
662 663 664 665 666 667 668 669 670
     *
     * RESTRICT: Rejects the delete or update operation for the parent table. NO ACTION and RESTRICT are the same as
     *           omitting the ON DELETE or ON UPDATE clause.
     *
     * SET DEFAULT
     *
     * @return string  DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
     *                 of a field declaration.
     */
671
    public function getForeignKeyDeclaration(array $definition)
zYne's avatar
zYne committed
672
    {
673
        $sql  = $this->getForeignKeyBaseDeclaration($definition);
zYne's avatar
zYne committed
674 675 676 677 678 679 680 681 682 683
        
        if (isset($definition['deferred'])) {
            $sql .= ' ' . $this->getForeignKeyDeferredDeclaration();
        }

        $a = array('onUpdate', 'onDelete');
        foreach($a as $v) {
            $keyword = ($v == 'onUpdate') ? ' ON UPDATE ' : ' ON DELETE ';

            if (isset($definition[$v])) {
zYne's avatar
zYne committed
684
                $upper = strtoupper($definition[$v]);
zYne's avatar
zYne committed
685

zYne's avatar
zYne committed
686
                switch ($upper) {
zYne's avatar
zYne committed
687 688 689 690 691
                    case 'CASCADE':
                    case 'SET NULL':
                    case 'NO ACTION':
                    case 'RESTRICT':
                    case 'SET DEFAULT':
zYne's avatar
zYne committed
692
                        $sql .= $keyword . $upper;
zYne's avatar
zYne committed
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
                    break;
                    default:
                        throw new Doctrine_Export_Exception('Unknown foreign key referential action option given.');
                }
            }
        }
        return $sql;
    }
    /** 
     * getForeignKeyDeferredDeclaration
     *
     * @return string
     */
    public function getForeignKeyDeferredDeclaration($deferred)
    {
        return '';
    }
    /**
     * getForeignKeyBaseDeclaration
712 713
     * Obtain DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
     * of a field declaration to be used in statements like CREATE TABLE.
zYne's avatar
zYne committed
714
     *
715
     * @param array $definition
zYne's avatar
zYne committed
716 717
     * @return string
     */
718
    public function getForeignKeyBaseDeclaration(array $definition)
zYne's avatar
zYne committed
719 720 721
    {
    	$sql = '';
        if (isset($definition['name'])) {
722
            $sql .= 'CONSTRAINT ' . $definition['name'] . ' ';
zYne's avatar
zYne committed
723
        }
zYne's avatar
zYne committed
724
        $sql .= 'FOREIGN KEY (';
zYne's avatar
zYne committed
725

zYne's avatar
zYne committed
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
        if ( ! isset($definition['local'])) {
            throw new Doctrine_Export_Exception('Local reference field missing from definition.');
        }
        if ( ! isset($definition['foreign'])) {
            throw new Doctrine_Export_Exception('Foreign reference field missing from definition.');
        }
        if ( ! isset($definition['foreignTable'])) {
            throw new Doctrine_Export_Exception('Foreign reference table missing from definition.');
        }

        if ( ! is_array($definition['local'])) {
            $definition['local'] = array($definition['local']);
        }
        if ( ! is_array($definition['foreign'])) {
            $definition['foreign'] = array($definition['foreign']);
        }
        $sql .= implode(', ', array_map(array($this->conn, 'quoteIdentifier'), $definition['local']))
zYne's avatar
zYne committed
743
              . ') REFERENCES '
zYne's avatar
zYne committed
744 745
              . $definition['foreignTable'] . '('
              . implode(', ', array_map(array($this->conn, 'quoteIdentifier'), $definition['foreign'])) . ')';
zYne's avatar
zYne committed
746
        
zYne's avatar
zYne committed
747 748
        return $sql;
    }
zYne's avatar
zYne committed
749 750 751 752 753 754 755 756 757 758
    /**
     * Obtain DBMS specific SQL code portion needed to set the UNIQUE constraint
     * of a field declaration to be used in statements like CREATE TABLE.
     *
     * @return string  DBMS specific SQL code portion needed to set the UNIQUE constraint
     *                 of a field declaration.
     */
    public function getUniqueFieldDeclaration()
    {
        return 'UNIQUE';
759 760 761 762 763 764 765 766 767
    }
    /**
     * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET
     * of a field declaration to be used in statements like CREATE TABLE.
     *
     * @param string $charset   name of the charset
     * @return string  DBMS specific SQL code portion needed to set the CHARACTER SET
     *                 of a field declaration.
     */
lsmith's avatar
lsmith committed
768 769
    public function getCharsetFieldDeclaration($charset)
    {
770 771 772 773 774 775 776 777 778 779
        return '';
    }
    /**
     * Obtain DBMS specific SQL code portion needed to set the COLLATION
     * of a field declaration to be used in statements like CREATE TABLE.
     *
     * @param string $collation   name of the collation
     * @return string  DBMS specific SQL code portion needed to set the COLLATION
     *                 of a field declaration.
     */
lsmith's avatar
lsmith committed
780 781
    public function getCollationFieldDeclaration($collation)
    {
782
        return '';
783
    }
784 785
    /**
     * export
zYne's avatar
zYne committed
786 787 788
     * method for exporting Doctrine_Record classes to a schema
     *
     * @return void
789
     */
lsmith's avatar
lsmith committed
790 791
    public static function exportAll()
    {
792 793 794 795 796
        $parent = new ReflectionClass('Doctrine_Record');
        $conn   = Doctrine_Manager::getInstance()->getCurrentConnection();
        $old    = $conn->getAttribute(Doctrine::ATTR_CREATE_TABLES);

        $conn->setAttribute(Doctrine::ATTR_CREATE_TABLES, true);
lsmith's avatar
lsmith committed
797 798

        foreach (get_declared_classes() as $name) {
799 800
            $class = new ReflectionClass($name);

lsmith's avatar
lsmith committed
801
            if ($class->isSubclassOf($parent) && ! $class->isAbstract()) {
802
                $obj = new $class();
lsmith's avatar
lsmith committed
803
            }
804 805 806
        }
        $conn->setAttribute(Doctrine::ATTR_CREATE_TABLES, $old);
    }
lsmith's avatar
lsmith committed
807 808
    public function export($record)
    {
lsmith's avatar
lsmith committed
809
        if ( ! $record instanceof Doctrine_Record)
zYne's avatar
zYne committed
810 811 812
            $record = new $record();

        $table = $record->getTable();
lsmith's avatar
lsmith committed
813

zYne's avatar
zYne committed
814 815
        $reporter = new Doctrine_Reporter();

lsmith's avatar
lsmith committed
816
        if ( ! Doctrine::isValidClassname($table->getComponentName())) {
817
            $reporter->add(E_WARNING, 'Badly named class.');
zYne's avatar
zYne committed
818
        }
lsmith's avatar
lsmith committed
819

zYne's avatar
zYne committed
820 821
        try {
            $columns = array();
lsmith's avatar
lsmith committed
822
            foreach ($table->getColumns() as $name => $column) {
zYne's avatar
zYne committed
823 824 825 826
                $definition = $column[2];
                $definition['type'] = $column[0];
                $definition['length'] = $column[1];

lsmith's avatar
lsmith committed
827
                if ($definition['type'] == 'enum' && isset($definition['default'])) {
zYne's avatar
zYne committed
828
                    $definition['default'] = $table->enumIndex($name, $definition['default']);
lsmith's avatar
lsmith committed
829 830
                }
                if ($definition['type'] == 'boolean' && isset($definition['default'])) {
zYne's avatar
zYne committed
831
                    $definition['default'] = (int) $definition['default'];
lsmith's avatar
lsmith committed
832
                }
zYne's avatar
zYne committed
833 834
                $columns[$name] = $definition;
            }
835

zYne's avatar
zYne committed
836 837 838
            $this->createTable($table->getTableName(), $columns);

        } catch(Doctrine_Connection_Exception $e) {
zYne's avatar
zYne committed
839
            $reporter->add(E_ERROR, $e->getMessage());
840
        }
zYne's avatar
zYne committed
841 842 843

        return $reporter;
    }
zYne's avatar
zYne committed
844
}