Table.php 18.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
<?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
Benjamin Eberlei's avatar
Benjamin Eberlei committed
18
 * and is licensed under the MIT license. For more information, see
19 20 21 22 23 24
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL\Schema;

use Doctrine\DBAL\Types\Type;
25
use Doctrine\DBAL\Schema\Visitor\Visitor;
26
use Doctrine\DBAL\DBALException;
27 28 29 30

/**
 * Object Representation of a table
 *
Benjamin Eberlei's avatar
Benjamin Eberlei committed
31
 * 
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
 * @link    www.doctrine-project.org
 * @since   2.0
 * @version $Revision$
 * @author  Benjamin Eberlei <kontakt@beberlei.de>
 */
class Table extends AbstractAsset
{
    /**
     * @var string
     */
    protected $_name = null;

    /**
     * @var array
     */
    protected $_columns = array();

    /**
     * @var array
     */
    protected $_indexes = array();

    /**
     * @var string
     */
    protected $_primaryKeyName = false;

    /**
     * @var array
     */
62
    protected $_fkConstraints = array();
63 64 65 66 67 68

    /**
     * @var array
     */
    protected $_options = array();

69 70 71 72 73
    /**
     * @var SchemaConfig
     */
    protected $_schemaConfig = null;

74 75 76 77 78
    /**
     *
     * @param string $tableName
     * @param array $columns
     * @param array $indexes
79
     * @param array $fkConstraints
80 81 82
     * @param int $idGeneratorType
     * @param array $options
     */
83
    public function __construct($tableName, array $columns=array(), array $indexes=array(), array $fkConstraints=array(), $idGeneratorType = 0, array $options=array())
84
    {
85 86 87 88
        if (strlen($tableName) == 0) {
            throw DBALException::invalidTableName($tableName);
        }

89
        $this->_setName($tableName);
90
        $this->_idGeneratorType = $idGeneratorType;
91

92
        foreach ($columns as $column) {
93 94
            $this->_addColumn($column);
        }
95

96
        foreach ($indexes as $idx) {
97 98 99
            $this->_addIndex($idx);
        }

100
        foreach ($fkConstraints as $constraint) {
101
            $this->_addForeignKeyConstraint($constraint);
102 103 104 105 106
        }

        $this->_options = $options;
    }

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    /**
     * @param SchemaConfig $schemaConfig
     */
    public function setSchemaConfig(SchemaConfig $schemaConfig)
    {
        $this->_schemaConfig = $schemaConfig;
    }

    /**
     * @return int
     */
    protected function _getMaxIdentifierLength()
    {
        if ($this->_schemaConfig instanceof SchemaConfig) {
            return $this->_schemaConfig->getMaxIdentifierLength();
        } else {
            return 63;
        }
    }

127 128 129 130 131 132 133
    /**
     * Set Primary Key
     *
     * @param array $columns
     * @param string $indexName
     * @return Table
     */
134
    public function setPrimaryKey(array $columns, $indexName = false)
135
    {
136 137
        $primaryKey = $this->_createIndex($columns, $indexName ?: "primary", true, true);

138
        foreach ($columns as $columnName) {
139 140 141 142 143
            $column = $this->getColumn($columnName);
            $column->setNotnull(true);
        }

        return $primaryKey;
144 145 146 147 148 149 150
    }

    /**
     * @param array $columnNames
     * @param string $indexName
     * @return Table
     */
151
    public function addIndex(array $columnNames, $indexName = null)
152
    {
153
        if($indexName == null) {
154
            $indexName = $this->_generateIdentifierName(
155
                array_merge(array($this->getName()), $columnNames), "idx", $this->_getMaxIdentifierLength()
156
            );
157 158
        }

159 160 161
        return $this->_createIndex($columnNames, $indexName, false, false);
    }

162 163 164 165 166 167 168 169 170
    /**
     * Drop an index from this table.
     *
     * @param string $indexName
     * @return void
     */
    public function dropPrimaryKey()
    {
        $this->dropIndex($this->_primaryKeyName);
171
        $this->_primaryKeyName = false;
172 173 174 175 176 177 178 179 180 181 182
    }

    /**
     * Drop an index from this table.
     *
     * @param string $indexName
     * @return void
     */
    public function dropIndex($indexName)
    {
        $indexName = strtolower($indexName);
183
        if ( ! $this->hasIndex($indexName)) {
184 185 186 187 188
            throw SchemaException::indexDoesNotExist($indexName, $this->_name);
        }
        unset($this->_indexes[$indexName]);
    }

189 190 191 192 193 194
    /**
     *
     * @param array $columnNames
     * @param string $indexName
     * @return Table
     */
195
    public function addUniqueIndex(array $columnNames, $indexName = null)
196
    {
197
        if ($indexName === null) {
198
            $indexName = $this->_generateIdentifierName(
199
                array_merge(array($this->getName()), $columnNames), "uniq", $this->_getMaxIdentifierLength()
200
            );
201 202
        }

203 204 205
        return $this->_createIndex($columnNames, $indexName, true, false);
    }

206 207 208 209 210 211 212 213
    /**
     * Check if an index begins in the order of the given columns.
     *
     * @param  array $columnsNames
     * @return bool
     */
    public function columnsAreIndexed(array $columnsNames)
    {
214
        foreach ($this->getIndexes() as $index) {
215 216
            /* @var $index Index */
            if ($index->spansColumns($columnsNames)) {
217 218 219 220 221 222
                return true;
            }
        }
        return false;
    }

223 224 225 226 227 228 229 230 231 232 233 234 235 236
    /**
     *
     * @param array $columnNames
     * @param string $indexName
     * @param bool $isUnique
     * @param bool $isPrimary
     * @return Table
     */
    private function _createIndex(array $columnNames, $indexName, $isUnique, $isPrimary)
    {
        if (preg_match('(([^a-zA-Z0-9_]+))', $indexName)) {
            throw SchemaException::indexNameInvalid($indexName);
        }

237
        foreach ($columnNames as $columnName => $indexColOptions) {
beberlei's avatar
beberlei committed
238 239 240 241
            if (is_numeric($columnName) && is_string($indexColOptions)) {
                $columnName = $indexColOptions;
            }

242
            if ( ! $this->hasColumn($columnName)) {
243
                throw SchemaException::columnDoesNotExist($columnName, $this->_name);
244 245 246 247 248 249 250 251 252 253
            }
        }
        $this->_addIndex(new Index($indexName, $columnNames, $isUnique, $isPrimary));
        return $this;
    }

    /**
     * @param string $columnName
     * @param string $columnType
     * @param array $options
254
     * @return Column
255
     */
256
    public function addColumn($columnName, $typeName, array $options=array())
257 258 259 260
    {
        $column = new Column($columnName, Type::getType($typeName), $options);

        $this->_addColumn($column);
261
        return $column;
262 263 264 265 266 267 268 269 270 271 272
    }

    /**
     * Rename Column
     *
     * @param string $oldColumnName
     * @param string $newColumnName
     * @return Table
     */
    public function renameColumn($oldColumnName, $newColumnName)
    {
273 274 275
        throw new DBALException("Table#renameColumn() was removed, because it drops and recreates " .
            "the column instead. There is no fix available, because a schema diff cannot reliably detect if a " .
            "column was renamed or one column was created and another one dropped.");
276 277 278 279
    }

    /**
     * Change Column Details
280
     *
281 282 283 284 285 286 287 288 289 290 291 292 293
     * @param string $columnName
     * @param array $options
     * @return Table
     */
    public function changeColumn($columnName, array $options)
    {
        $column = $this->getColumn($columnName);
        $column->setOptions($options);
        return $this;
    }

    /**
     * Drop Column from Table
294
     *
295 296 297 298 299
     * @param string $columnName
     * @return Table
     */
    public function dropColumn($columnName)
    {
300
        $columnName = strtolower($columnName);
301 302 303 304 305 306 307 308 309
        $column = $this->getColumn($columnName);
        unset($this->_columns[$columnName]);
        return $this;
    }


    /**
     * Add a foreign key constraint
     *
310 311
     * Name is inferred from the local columns
     *
312 313 314 315
     * @param Table $foreignTable
     * @param array $localColumns
     * @param array $foreignColumns
     * @param array $options
316
     * @param string $constraintName
317 318
     * @return Table
     */
319
    public function addForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options=array(), $constraintName = null)
320
    {
321 322
        $constraintName = $constraintName ?: $this->_generateIdentifierName(array_merge((array)$this->getName(), $localColumnNames), "fk", $this->_getMaxIdentifierLength());
        return $this->addNamedForeignKeyConstraint($constraintName, $foreignTable, $localColumnNames, $foreignColumnNames, $options);
323 324
    }

325 326 327 328 329
    /**
     * Add a foreign key constraint
     *
     * Name is to be generated by the database itsself.
     *
330
     * @deprecated Use {@link addForeignKeyConstraint}
331 332 333 334 335 336 337 338
     * @param Table $foreignTable
     * @param array $localColumns
     * @param array $foreignColumns
     * @param array $options
     * @return Table
     */
    public function addUnnamedForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options=array())
    {
339
        return $this->addForeignKeyConstraint($foreignTable, $localColumnNames, $foreignColumnNames, $options);
340 341
    }

342 343 344
    /**
     * Add a foreign key constraint with a given name
     *
345
     * @deprecated Use {@link addForeignKeyConstraint}
346 347 348 349 350 351 352 353
     * @param string $name
     * @param Table $foreignTable
     * @param array $localColumns
     * @param array $foreignColumns
     * @param array $options
     * @return Table
     */
    public function addNamedForeignKeyConstraint($name, $foreignTable, array $localColumnNames, array $foreignColumnNames, array $options=array())
354
    {
355 356 357
        if ($foreignTable instanceof Table) {
            $foreignTableName = $foreignTable->getName();

358
            foreach ($foreignColumnNames as $columnName) {
359
                if ( ! $foreignTable->hasColumn($columnName)) {
360
                    throw SchemaException::columnDoesNotExist($columnName, $foreignTable->getName());
361
                }
362
            }
363 364
        } else {
            $foreignTableName = $foreignTable;
365
        }
366

367
        foreach ($localColumnNames as $columnName) {
368
            if ( ! $this->hasColumn($columnName)) {
369
                throw SchemaException::columnDoesNotExist($columnName, $this->_name);
370 371
            }
        }
372

373
        $constraint = new ForeignKeyConstraint(
374
            $localColumnNames, $foreignTableName, $foreignColumnNames, $name, $options
375
        );
376
        $this->_addForeignKeyConstraint($constraint);
377

378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
        return $this;
    }

    /**
     * @param string $name
     * @param string $value
     * @return Table
     */
    public function addOption($name, $value)
    {
        $this->_options[$name] = $value;
        return $this;
    }

    /**
     * @param Column $column
     */
    protected function _addColumn(Column $column)
    {
397 398 399
        $columnName = $column->getName();
        $columnName = strtolower($columnName);

400
        if (isset($this->_columns[$columnName])) {
401
            throw SchemaException::columnAlreadyExists($this->getName(), $columnName);
402 403 404 405 406 407 408
        }

        $this->_columns[$columnName] = $column;
    }

    /**
     * Add index to table
409
     *
410
     * @param Index $indexCandidate
411 412
     * @return Table
     */
413
    protected function _addIndex(Index $indexCandidate)
414
    {
415
        // check for duplicates
416
        foreach ($this->_indexes as $existingIndex) {
417
            if ($indexCandidate->isFullfilledBy($existingIndex)) {
418 419 420 421
                return $this;
            }
        }

422
        $indexName = $indexCandidate->getName();
423
        $indexName = strtolower($indexName);
424

425
        if (isset($this->_indexes[$indexName]) || ($this->_primaryKeyName != false && $indexCandidate->isPrimary())) {
426
            throw SchemaException::indexAlreadyExists($indexName, $this->_name);
427 428
        }

429
        // remove overruled indexes
430
        foreach ($this->_indexes as $idxKey => $existingIndex) {
431 432 433 434 435 436
            if ($indexCandidate->overrules($existingIndex)) {
                unset($this->_indexes[$idxKey]);
            }
        }

        if ($indexCandidate->isPrimary()) {
437 438 439
            $this->_primaryKeyName = $indexName;
        }

440
        $this->_indexes[$indexName] = $indexCandidate;
441 442 443 444
        return $this;
    }

    /**
445
     * @param ForeignKeyConstraint $constraint
446
     */
447
    protected function _addForeignKeyConstraint(ForeignKeyConstraint $constraint)
448
    {
449
        $constraint->setLocalTable($this);
450

451 452 453 454
        if(strlen($constraint->getName())) {
            $name = $constraint->getName();
        } else {
            $name = $this->_generateIdentifierName(
455
                array_merge((array)$this->getName(), $constraint->getLocalColumns()), "fk", $this->_getMaxIdentifierLength()
456 457
            );
        }
458
        $name = strtolower($name);
459 460

        $this->_fkConstraints[$name] = $constraint;
461 462 463 464
        // add an explicit index on the foreign key columns. If there is already an index that fullfils this requirements drop the request.
        // In the case of __construct calling this method during hydration from schema-details all the explicitly added indexes
        // lead to duplicates. This creates compuation overhead in this case, however no duplicate indexes are ever added (based on columns).
        $this->addIndex($constraint->getColumns());
465 466 467 468 469 470 471 472 473 474
    }

    /**
     * Does Table have a foreign key constraint with the given name?
     *      *
     * @param  string $constraintName
     * @return bool
     */
    public function hasForeignKey($constraintName)
    {
475
        $constraintName = strtolower($constraintName);
476 477 478 479 480 481 482 483 484
        return isset($this->_fkConstraints[$constraintName]);
    }

    /**
     * @param string $constraintName
     * @return ForeignKeyConstraint
     */
    public function getForeignKey($constraintName)
    {
485
        $constraintName = strtolower($constraintName);
486
        if(!$this->hasForeignKey($constraintName)) {
487
            throw SchemaException::foreignKeyDoesNotExist($constraintName, $this->_name);
488 489 490
        }

        return $this->_fkConstraints[$constraintName];
491 492
    }

493 494 495 496 497 498 499 500 501 502
    public function removeForeignKey($constraintName)
    {
        $constraintName = strtolower($constraintName);
        if(!$this->hasForeignKey($constraintName)) {
            throw SchemaException::foreignKeyDoesNotExist($constraintName, $this->_name);
        }

        unset($this->_fkConstraints[$constraintName]);
    }

503 504 505 506 507
    /**
     * @return Column[]
     */
    public function getColumns()
    {
508 509 510 511 512
        $columns = $this->_columns;

        $pkCols = array();
        $fkCols = array();

513
        if ($this->hasPrimaryKey()) {
514 515
            $pkCols = $this->getPrimaryKey()->getColumns();
        }
516
        foreach ($this->getForeignKeys() as $fk) {
517 518 519 520 521 522 523 524 525
            /* @var $fk ForeignKeyConstraint */
            $fkCols = array_merge($fkCols, $fk->getColumns());
        }
        $colNames = array_unique(array_merge($pkCols, $fkCols, array_keys($columns)));

        uksort($columns, function($a, $b) use($colNames) {
            return (array_search($a, $colNames) >= array_search($b, $colNames));
        });
        return $columns;
526 527 528 529 530 531 532 533 534 535 536
    }


    /**
     * Does this table have a column with the given name?
     *
     * @param  string $columnName
     * @return bool
     */
    public function hasColumn($columnName)
    {
537
        $columnName = $this->trimQuotes(strtolower($columnName));
538 539 540 541 542
        return isset($this->_columns[$columnName]);
    }

    /**
     * Get a column instance
543
     *
544 545 546 547 548
     * @param  string $columnName
     * @return Column
     */
    public function getColumn($columnName)
    {
549
        $columnName = strtolower($this->trimQuotes($columnName));
550
        if ( ! $this->hasColumn($columnName)) {
551
            throw SchemaException::columnDoesNotExist($columnName, $this->_name);
552 553 554 555 556 557
        }

        return $this->_columns[$columnName];
    }

    /**
558
     * @return Index|null
559 560 561
     */
    public function getPrimaryKey()
    {
562
        if ( ! $this->hasPrimaryKey()) {
563 564
            return null;
        }
565 566 567
        return $this->getIndex($this->_primaryKeyName);
    }

568 569 570 571 572 573 574 575
    public function getPrimaryKeyColumns()
    {
        if ( ! $this->hasPrimaryKey()) {
            throw new DBALException("Table " . $this->getName() . " has no primary key.");
        }
        return $this->getPrimaryKey()->getColumns();
    }

576 577 578 579 580 581 582 583 584 585
    /**
     * Check if this table has a primary key.
     *
     * @return bool
     */
    public function hasPrimaryKey()
    {
        return ($this->_primaryKeyName && $this->hasIndex($this->_primaryKeyName));
    }

586 587 588 589 590 591
    /**
     * @param  string $indexName
     * @return bool
     */
    public function hasIndex($indexName)
    {
592
        $indexName = strtolower($indexName);
593 594 595 596 597 598 599 600 601
        return (isset($this->_indexes[$indexName]));
    }

    /**
     * @param  string $indexName
     * @return Index
     */
    public function getIndex($indexName)
    {
602
        $indexName = strtolower($indexName);
603
        if ( ! $this->hasIndex($indexName)) {
604
            throw SchemaException::indexDoesNotExist($indexName, $this->_name);
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
        }
        return $this->_indexes[$indexName];
    }

    /**
     * @return array
     */
    public function getIndexes()
    {
        return $this->_indexes;
    }

    /**
     * Get Constraints
     *
     * @return array
     */
622
    public function getForeignKeys()
623
    {
624
        return $this->_fkConstraints;
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
    }

    public function hasOption($name)
    {
        return isset($this->_options[$name]);
    }

    public function getOption($name)
    {
        return $this->_options[$name];
    }

    public function getOptions()
    {
        return $this->_options;
    }

642
    /**
643 644 645 646 647 648
     * @param Visitor $visitor
     */
    public function visit(Visitor $visitor)
    {
        $visitor->acceptTable($this);

649
        foreach ($this->getColumns() as $column) {
650
            $visitor->acceptColumn($this, $column);
651 652
        }

653
        foreach ($this->getIndexes() as $index) {
654 655 656
            $visitor->acceptIndex($this, $index);
        }

657
        foreach ($this->getForeignKeys() as $constraint) {
658
            $visitor->acceptForeignKey($this, $constraint);
659 660
        }
    }
661 662 663 664 665 666

    /**
     * Clone of a Table triggers a deep clone of all affected assets
     */
    public function __clone()
    {
667
        foreach ($this->_columns as $k => $column) {
668 669
            $this->_columns[$k] = clone $column;
        }
670
        foreach ($this->_indexes as $k => $index) {
671 672
            $this->_indexes[$k] = clone $index;
        }
673
        foreach ($this->_fkConstraints as $k => $fk) {
674 675 676 677
            $this->_fkConstraints[$k] = clone $fk;
            $this->_fkConstraints[$k]->setLocalTable($this);
        }
    }
678
}