Table.php 14.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<?php
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL\Schema;

use Doctrine\DBAL\Types\Type;
25
use Doctrine\DBAL\Schema\Visitor\Visitor;
26 27 28 29 30 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 62 63 64 65 66 67 68 69 70 71 72 73 74 75

/**
 * Object Representation of a table
 *
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link    www.doctrine-project.org
 * @since   2.0
 * @version $Revision$
 * @author  Benjamin Eberlei <kontakt@beberlei.de>
 */
class Table extends AbstractAsset
{
    /**
     * @var int
     */
    const ID_NONE = 0;

    /**
     * @var int
     */
    const ID_SEQUENCE = 1;

    /**
     * @var int
     */
    const ID_IDENTITY = 2;

    /**
     * @var string
     */
    protected $_name = null;

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

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

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

    /**
     * @var array
     */
76
    protected $_fkConstraints = array();
77 78 79 80 81 82 83 84 85 86 87

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

    /**
     * @var bool
     */
    protected $_idGeneratorType = self::ID_NONE;

88 89 90 91 92
    /**
     * @var SchemaConfig
     */
    protected $_schemaConfig = null;

93 94 95 96 97
    /**
     *
     * @param string $tableName
     * @param array $columns
     * @param array $indexes
98
     * @param array $fkConstraints
99 100 101
     * @param int $idGeneratorType
     * @param array $options
     */
102
    public function __construct($tableName, array $columns=array(), array $indexes=array(), array $fkConstraints=array(), $idGeneratorType=self::ID_NONE, array $options=array())
103
    {
104
        $this->_setName($tableName);
105 106 107 108 109 110 111 112 113 114
        $this->_idGeneratorType = $idGeneratorType;
        
        foreach ($columns AS $column) {
            $this->_addColumn($column);
        }
        
        foreach ($indexes AS $idx) {
            $this->_addIndex($idx);
        }

115 116
        foreach ($fkConstraints AS $constraint) {
            $this->_addForeignKeyConstraint($constraint);
117 118 119 120 121
        }

        $this->_options = $options;
    }

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
    /**
     * @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;
        }
    }

142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    /**
     * Set Primary Key
     *
     * @param array $columns
     * @param string $indexName
     * @return Table
     */
    public function setPrimaryKey(array $columns, $indexName=false)
    {
        return $this->_createIndex($columns, $indexName?:"primary", true, true);
    }

    /**
     * @param string $type
     * @return Table
     */
    public function setIdGeneratorType($type)
    {
        $this->_idGeneratorType = $type;
        return $this;
    }

    /**
     * @param array $columnNames
     * @param string $indexName
     * @return Table
     */
    public function addIndex(array $columnNames, $indexName=null)
    {
171
        if($indexName == null) {
172
            $indexName = $this->_generateIdentifierName(
173
                array_merge(array($this->getName()), $columnNames), "idx", $this->_getMaxIdentifierLength()
174
            );
175 176
        }

177 178 179 180 181 182 183 184 185 186 187
        return $this->_createIndex($columnNames, $indexName, false, false);
    }

    /**
     *
     * @param array $columnNames
     * @param string $indexName
     * @return Table
     */
    public function addUniqueIndex(array $columnNames, $indexName=null)
    {
188
        if ($indexName == null) {
189
            $indexName = $this->_generateIdentifierName(
190
                array_merge(array($this->getName()), $columnNames), "uniq", $this->_getMaxIdentifierLength()
191
            );
192 193
        }

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
        return $this->_createIndex($columnNames, $indexName, true, false);
    }

    /**
     *
     * @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);
        }

beberlei's avatar
beberlei committed
211 212 213 214 215
        foreach ($columnNames AS $columnName => $indexColOptions) {
            if (is_numeric($columnName) && is_string($indexColOptions)) {
                $columnName = $indexColOptions;
            }

216
            if ( ! $this->hasColumn($columnName)) {
217 218 219 220 221 222 223 224 225 226 227
                throw SchemaException::columnDoesNotExist($columnName);
            }
        }
        $this->_addIndex(new Index($indexName, $columnNames, $isUnique, $isPrimary));
        return $this;
    }

    /**
     * @param string $columnName
     * @param string $columnType
     * @param array $options
228
     * @return Column
229 230 231 232 233 234
     */
    public function createColumn($columnName, $typeName, array $options=array())
    {
        $column = new Column($columnName, Type::getType($typeName), $options);

        $this->_addColumn($column);
235
        return $column;
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 267 268 269 270 271 272 273 274 275
    }

    /**
     * Rename Column
     *
     * @param string $oldColumnName
     * @param string $newColumnName
     * @return Table
     */
    public function renameColumn($oldColumnName, $newColumnName)
    {
        $column = $this->getColumn($oldColumnName);
        $this->dropColumn($oldColumnName);

        $column->_setName($newColumnName);
        return $this;
    }

    /**
     * Change Column Details
     * 
     * @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
     * 
     * @param string $columnName
     * @return Table
     */
    public function dropColumn($columnName)
    {
276
        $columnName = strtolower($columnName);
277 278 279 280 281 282 283 284 285
        $column = $this->getColumn($columnName);
        unset($this->_columns[$columnName]);
        return $this;
    }


    /**
     * Add a foreign key constraint
     *
286 287
     * Name is inferred from the local columns
     *
288 289 290 291 292 293
     * @param Table $foreignTable
     * @param array $localColumns
     * @param array $foreignColumns
     * @param array $options
     * @return Table
     */
294 295
    public function addForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options=array())
    {
296
        $name = $this->_generateIdentifierName(array_merge((array)$this->getName(), $localColumnNames), "fk", $this->_getMaxIdentifierLength());
297 298 299
        return $this->addNamedForeignKeyConstraint($name, $foreignTable, $localColumnNames, $foreignColumnNames, $options);
    }

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    /**
     * Add a foreign key constraint
     *
     * Name is to be generated by the database itsself.
     *
     * @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())
    {
        return $this->addNamedForeignKeyConstraint(null, $foreignTable, $localColumnNames, $foreignColumnNames, $options);
    }

316 317 318 319 320 321 322 323 324 325 326
    /**
     * Add a foreign key constraint with a given name
     *
     * @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())
327
    {
328 329 330 331
        if ($foreignTable instanceof Table) {
            $foreignTableName = $foreignTable->getName();

            foreach ($foreignColumnNames AS $columnName) {
332
                if ( ! $foreignTable->hasColumn($columnName)) {
333 334
                    throw SchemaException::columnDoesNotExist($columnName);
                }
335
            }
336 337
        } else {
            $foreignTableName = $foreignTable;
338
        }
339 340

        foreach ($localColumnNames AS $columnName) {
341
            if ( ! $this->hasColumn($columnName)) {
342 343 344
                throw SchemaException::columnDoesNotExist($columnName);
            }
        }
345
        
346
        $constraint = new ForeignKeyConstraint(
347
            $localColumnNames, $foreignTableName, $foreignColumnNames, $name, $options
348
        );
349
        $this->_addForeignKeyConstraint($constraint);
350

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
        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)
    {
370 371 372
        $columnName = $column->getName();
        $columnName = strtolower($columnName);

373
        if (isset($this->_columns[$columnName])) {
374
            throw SchemaException::columnAlreadyExists($this->getName(), $columnName);
375 376 377 378 379 380 381 382 383 384 385 386 387
        }

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

    /**
     * Add index to table
     * 
     * @param Index $index
     * @return Table
     */
    protected function _addIndex(Index $index)
    {
388 389 390 391 392 393 394 395
        // check for duplicates
        $c = new Comparator();
        foreach ($this->_indexes AS $existingIndex) {
            if ($c->diffIndex($index, $existingIndex) == false) {
                return $this;
            }
        }

396
        $indexName = $index->getName();
397
        $indexName = strtolower($indexName);
398 399 400 401 402 403 404 405 406 407 408 409 410 411

        if (isset($this->_indexes[$indexName]) || ($this->_primaryKeyName != false && $index->isPrimary())) {
            throw SchemaException::indexAlreadyExists($indexName);
        }

        if ($index->isPrimary()) {
            $this->_primaryKeyName = $indexName;
        }

        $this->_indexes[$indexName] = $index;
        return $this;
    }

    /**
412
     * @param ForeignKeyConstraint $constraint
413
     */
414
    protected function _addForeignKeyConstraint(ForeignKeyConstraint $constraint)
415
    {
416 417
        $constraint->setLocalTable($this);
        
418 419 420 421
        if(strlen($constraint->getName())) {
            $name = $constraint->getName();
        } else {
            $name = $this->_generateIdentifierName(
422
                array_merge((array)$this->getName(), $constraint->getLocalColumns()), "fk", $this->_getMaxIdentifierLength()
423 424
            );
        }
425
        $name = strtolower($name);
426 427

        $this->_fkConstraints[$name] = $constraint;
428 429 430 431 432 433 434 435 436 437
    }

    /**
     * Does Table have a foreign key constraint with the given name?
     *      *
     * @param  string $constraintName
     * @return bool
     */
    public function hasForeignKey($constraintName)
    {
438
        $constraintName = strtolower($constraintName);
439 440 441 442 443 444 445 446 447
        return isset($this->_fkConstraints[$constraintName]);
    }

    /**
     * @param string $constraintName
     * @return ForeignKeyConstraint
     */
    public function getForeignKey($constraintName)
    {
448
        $constraintName = strtolower($constraintName);
449 450 451 452 453
        if(!$this->hasForeignKey($constraintName)) {
            throw SchemaException::foreignKeyDoesNotExist($constraintName);
        }

        return $this->_fkConstraints[$constraintName];
454 455 456 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 488
    }

    /**
     * @return bool
     */
    public function isIdGeneratorIdentity()
    {
        return ($this->_idGeneratorType==self::ID_IDENTITY);
    }

    /**
     * @return array
     */
    public function isIdGeneratorSequence()
    {
        return ($this->_idGeneratorType==self::ID_SEQUENCE);
    }

    /**
     * @return Column[]
     */
    public function getColumns()
    {
        return $this->_columns;
    }


    /**
     * Does this table have a column with the given name?
     *
     * @param  string $columnName
     * @return bool
     */
    public function hasColumn($columnName)
    {
489
        $columnName = strtolower($columnName);
490 491 492 493 494 495 496 497 498 499 500
        return isset($this->_columns[$columnName]);
    }

    /**
     * Get a column instance
     * 
     * @param  string $columnName
     * @return Column
     */
    public function getColumn($columnName)
    {
501
        $columnName = strtolower($columnName);
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
        if (!$this->hasColumn($columnName)) {
            throw SchemaException::columnDoesNotExist($columnName);
        }

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

    /**
     * @return Index
     */
    public function getPrimaryKey()
    {
        return $this->getIndex($this->_primaryKeyName);
    }

    /**
     * @param  string $indexName
     * @return bool
     */
    public function hasIndex($indexName)
    {
523
        $indexName = strtolower($indexName);
524 525 526 527 528 529 530 531 532
        return (isset($this->_indexes[$indexName]));
    }

    /**
     * @param  string $indexName
     * @return Index
     */
    public function getIndex($indexName)
    {
533
        $indexName = strtolower($indexName);
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
        if (!$this->hasIndex($indexName)) {
            throw SchemaException::indexDoesNotExist($indexName);
        }
        return $this->_indexes[$indexName];
    }

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

    /**
     * Get Constraints
     *
     * @return array
     */
553
    public function getForeignKeys()
554
    {
555
        return $this->_fkConstraints;
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
    }

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

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

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

    /**
     * @param Visitor $visitor
     */
    public function visit(Visitor $visitor)
    {
        $visitor->acceptTable($this);

580
        foreach ($this->getColumns() AS $column) {
581 582 583
            $visitor->acceptColunn($this, $column);
        }

584
        foreach ($this->getIndexes() AS $index) {
585 586 587
            $visitor->acceptIndex($this, $index);
        }

588 589
        foreach ($this->getForeignKeys() AS $constraint) {
            $visitor->acceptForeignKey($this, $constraint);
590 591 592
        }
    }
}