Export.php 35 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

147
        if (isset($options['primary']) && ! empty($options['primary'])) {
zYne's avatar
zYne committed
148 149 150 151 152 153
            $queryFields .= ', PRIMARY KEY(' . implode(', ', array_values($options['primary'])) . ')';
        }
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
            foreach($options['indexes'] as $index => $definition) {
                $queryFields .= ', ' . $this->getIndexDeclaration($index, $definition);
            }
154 155
        }

156 157
        $name  = $this->conn->quoteIdentifier($name, true);
        $query = 'CREATE TABLE ' . $name . ' (' . $queryFields . ')';
zYne's avatar
zYne committed
158

zYne's avatar
zYne committed
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
        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));
174 175 176 177
    }
    /**
     * create sequence
     *
zYne's avatar
zYne committed
178 179
     * @param string    $seqName        name of the sequence to be created
     * @param string    $start          start value of the sequence; default is 1
180 181
     * @return void
     */
zYne's avatar
zYne committed
182
    public function createSequence($seqName, $start = 1)
zYne's avatar
zYne committed
183 184 185 186 187 188 189 190 191 192 193 194
    {
        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
195
    {
196 197
        throw new Doctrine_Export_Exception('Create sequence not supported by this driver.');
    }
198
    /**
199 200 201 202 203 204 205 206 207 208
     * 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.
209
     *
210 211 212 213 214 215 216 217 218
     *                                 Example
     *                                    array(
     *                                        'fields' => array(
     *                                            'user_name' => array(),
     *                                            'last_login' => array()
     *                                        )
     *                                    )
     * @return void
     */
lsmith's avatar
lsmith committed
219 220
    public function createConstraint($table, $name, $definition)
    {
221 222
        $table = $this->conn->quoteIdentifier($table, true);
        $name = $this->conn->quoteIdentifier($this->conn->getIndexName($name), true);
223
        $query = 'ALTER TABLE ' . $table . ' ADD CONSTRAINT ' . $name;
224
        if (!empty($definition['primary'])) {
225
            $query .= ' PRIMARY KEY';
226
        } elseif (!empty($definition['unique'])) {
227
            $query .= ' UNIQUE';
228 229 230
        }
        $fields = array();
        foreach (array_keys($definition['fields']) as $field) {
231
            $fields[] = $this->conn->quoteIdentifier($field, true);
232 233
        }
        $query .= ' ('. implode(', ', $fields) . ')';
zYne's avatar
zYne committed
234
        return $this->conn->exec($query);
235 236
    }
    /**
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
     * 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
267 268
    public function createIndex($table, $name, array $definition)
    {
zYne's avatar
zYne committed
269
        return $this->conn->execute($this->createIndexSql($table, $name, $definition));
270 271 272 273 274 275 276
    }
    /**
     * 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.
277
     * @see Doctrine_Export::createIndex()
278 279
     * @return string
     */
lsmith's avatar
lsmith committed
280 281
    public function createIndexSql($table, $name, array $definition)
    {
282 283
        $table  = $this->conn->quoteIdentifier($table);
        $name   = $this->conn->quoteIdentifier($name);
zYne's avatar
zYne committed
284
        $type   = '';
zYne's avatar
zYne committed
285

zYne's avatar
zYne committed
286 287 288 289 290 291 292 293 294 295 296
        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;
297 298 299 300 301

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

304
        return $query;
305 306 307 308 309 310 311 312 313 314 315
    }
    /**
     * 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)
    {

316
    }
317 318
    /**
     * alter an existing table
319
     * (this method is implemented by the drivers)
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 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
     *
     * @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
406 407
    public function alterTable($name, array $changes, $check)
    {
zYne's avatar
zYne committed
408
        $this->conn->execute($this->alterTableSql($name, $changes, $check));
409 410
    }
    /**
zYne's avatar
zYne committed
411
     * generates the sql for altering an existing table
412 413
     * (this method is implemented by the drivers)
     *
zYne's avatar
zYne committed
414 415 416 417 418 419
     * @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()
420 421
     * @return string
     */
lsmith's avatar
lsmith committed
422 423
    public function alterTableSql($name, array $changes, $check)
    {
424 425 426 427 428
        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
429
     * @param array $fields  a multidimensional associative array.
430 431 432 433 434
     *      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
435 436 437 438 439
     *      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.
     *
440
     *      default
zYne's avatar
zYne committed
441
     *          Text value to be used as default for this field.
442 443 444 445
     *
     *      notnull
     *          Boolean flag that indicates whether this field is constrained
     *          to not be set to null.
zYne's avatar
zYne committed
446 447 448 449
     *      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
450 451
     *      unique
     *          unique constraint
452 453 454
     *
     * @return string
     */
lsmith's avatar
lsmith committed
455 456
    public function getFieldDeclarationList(array $fields)
    {
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
        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
488 489 490
     *      unique
     *          unique constraint
     *
491 492 493
     * @return string  DBMS specific SQL code portion that should be used to
     *      declare the specified field.
     */
lsmith's avatar
lsmith committed
494 495
    public function getDeclaration($name, array $field)
    {
496

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

zYne's avatar
zYne committed
499 500 501 502 503
        $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
504

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

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

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

lsmith's avatar
lsmith committed
512
        if (method_exists($this->conn->dataDict, $method)) {
513
            return $this->conn->dataDict->$method($name, $field);
lsmith's avatar
lsmith committed
514
        } else {
515
            $dec = $this->conn->dataDict->getNativeDeclaration($field);
lsmith's avatar
lsmith committed
516
        }
zYne's avatar
zYne committed
517 518
        return $this->conn->quoteIdentifier($name, true) . ' ' . $dec . $charset . $default . $notnull . $unique . $collation;
    }
zYne's avatar
zYne committed
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
    /**
     * 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'] = ' ';
                }
            }
    
            $default = ' DEFAULT ' . $this->conn->quote($field['default'], $field['type']);
        }
        return $default;
    }
zYne's avatar
zYne committed
546 547 548 549 550 551
    /**
     * 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
552
     * @return string               DBMS specific SQL code portion needed to set an index
zYne's avatar
zYne committed
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
     */
    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
586
    	$ret = array();
zYne's avatar
zYne committed
587 588
        foreach ($fields as $field => $definition) {
            if(is_array($definition)) {
zYne's avatar
zYne committed
589
                $ret[] = $this->conn->quoteIdentifier($field);
zYne's avatar
zYne committed
590
            } else {
zYne's avatar
zYne committed
591
                $ret[] = $this->conn->quoteIdentifier($definition);
zYne's avatar
zYne committed
592 593
            }
        }
zYne's avatar
zYne committed
594
        return implode(', ', $ret);
zYne's avatar
zYne committed
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
    }
    /**
     * 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
614 615
     *          deferred                deferred constraint checking
     *
zYne's avatar
zYne committed
616 617 618
     * The onDelete and onUpdate keys accept the following values:
     *
     * CASCADE: Delete or update the row from the parent table and automatically delete or 
619
     *          update the matching rows in the child table. Both ON DELETE CASCADE and ON UPDATE CASCADE are supported.
zYne's avatar
zYne committed
620 621 622 623 624 625 626 627
     *          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 
628
     *           key value is not allowed to proceed if there is a related foreign key value in the referenced table.
zYne's avatar
zYne committed
629 630 631 632 633 634 635 636 637
     *
     * 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.
     */
638
    public function getForeignKeyDeclaration(array $definition)
zYne's avatar
zYne committed
639
    {
640
        $sql  = $this->getForeignKeyBaseDeclaration($definition);
zYne's avatar
zYne committed
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
        
        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])) {
                switch ($definition[$v]) {
                    case 'CASCADE':
                    case 'SET NULL':
                    case 'NO ACTION':
                    case 'RESTRICT':
                    case 'SET DEFAULT':
                        $sql .= $keyword . $definition[$v];
                    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
677 678
     * 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
679
     *
680
     * @param array $definition
zYne's avatar
zYne committed
681 682
     * @return string
     */
683
    public function getForeignKeyBaseDeclaration(array $definition)
zYne's avatar
zYne committed
684 685 686
    {
    	$sql = '';
        if (isset($definition['name'])) {
687
            $sql .= 'CONSTRAINT ' . $definition['name'] . ' ';
zYne's avatar
zYne committed
688
        }
689
        $sql .= 'FOREIGN KEY ';
zYne's avatar
zYne committed
690

zYne's avatar
zYne committed
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
        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']))
              . ' REFERENCES '
              . $definition['foreignTable'] . '('
              . implode(', ', array_map(array($this->conn, 'quoteIdentifier'), $definition['foreign'])) . ')';
zYne's avatar
zYne committed
711
        
zYne's avatar
zYne committed
712 713
        return $sql;
    }
zYne's avatar
zYne committed
714 715 716 717 718 719 720 721 722 723
    /**
     * 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';
724 725 726 727 728 729 730 731 732
    }
    /**
     * 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
733 734
    public function getCharsetFieldDeclaration($charset)
    {
735 736 737 738 739 740 741 742 743 744
        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
745 746
    public function getCollationFieldDeclaration($collation)
    {
747
        return '';
748
    }
749 750
    /**
     * export
zYne's avatar
zYne committed
751 752 753
     * method for exporting Doctrine_Record classes to a schema
     *
     * @return void
754
     */
lsmith's avatar
lsmith committed
755 756
    public static function exportAll()
    {
757 758 759 760 761
        $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
762 763

        foreach (get_declared_classes() as $name) {
764 765
            $class = new ReflectionClass($name);

lsmith's avatar
lsmith committed
766
            if ($class->isSubclassOf($parent) && ! $class->isAbstract()) {
767
                $obj = new $class();
lsmith's avatar
lsmith committed
768
            }
769 770 771
        }
        $conn->setAttribute(Doctrine::ATTR_CREATE_TABLES, $old);
    }
lsmith's avatar
lsmith committed
772 773
    public function export($record)
    {
lsmith's avatar
lsmith committed
774
        if ( ! $record instanceof Doctrine_Record)
zYne's avatar
zYne committed
775 776 777
            $record = new $record();

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

zYne's avatar
zYne committed
779 780
        $reporter = new Doctrine_Reporter();

lsmith's avatar
lsmith committed
781
        if ( ! Doctrine::isValidClassname($table->getComponentName())) {
782
            $reporter->add(E_WARNING, 'Badly named class.');
zYne's avatar
zYne committed
783
        }
lsmith's avatar
lsmith committed
784

zYne's avatar
zYne committed
785 786
        try {
            $columns = array();
lsmith's avatar
lsmith committed
787
            foreach ($table->getColumns() as $name => $column) {
zYne's avatar
zYne committed
788 789 790 791
                $definition = $column[2];
                $definition['type'] = $column[0];
                $definition['length'] = $column[1];

lsmith's avatar
lsmith committed
792
                if ($definition['type'] == 'enum' && isset($definition['default'])) {
zYne's avatar
zYne committed
793
                    $definition['default'] = $table->enumIndex($name, $definition['default']);
lsmith's avatar
lsmith committed
794 795
                }
                if ($definition['type'] == 'boolean' && isset($definition['default'])) {
zYne's avatar
zYne committed
796
                    $definition['default'] = (int) $definition['default'];
lsmith's avatar
lsmith committed
797
                }
zYne's avatar
zYne committed
798 799
                $columns[$name] = $definition;
            }
800

zYne's avatar
zYne committed
801 802 803
            $this->createTable($table->getTableName(), $columns);

        } catch(Doctrine_Connection_Exception $e) {
zYne's avatar
zYne committed
804
            $reporter->add(E_ERROR, $e->getMessage());
805
        }
zYne's avatar
zYne committed
806 807 808

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