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

namespace Doctrine\DBAL\Schema;

use Doctrine\DBAL\Types\Type;
23
use Doctrine\DBAL\Schema\Visitor\Visitor;
24
use Doctrine\DBAL\DBALException;
25 26 27 28 29 30 31 32 33
use const ARRAY_FILTER_USE_KEY;
use function array_filter;
use function array_merge;
use function in_array;
use function is_numeric;
use function is_string;
use function preg_match;
use function strlen;
use function strtolower;
34 35

/**
Benjamin Morel's avatar
Benjamin Morel committed
36
 * Object Representation of a table.
37
 *
Benjamin Morel's avatar
Benjamin Morel committed
38 39 40
 * @link   www.doctrine-project.org
 * @since  2.0
 * @author Benjamin Eberlei <kontakt@beberlei.de>
41 42 43 44 45 46 47 48 49
 */
class Table extends AbstractAsset
{
    /**
     * @var string
     */
    protected $_name = null;

    /**
50
     * @var Column[]
51
     */
52
    protected $_columns = [];
53

54 55 56
    /**
     * @var Index[]
     */
57
    private $implicitIndexes = [];
58

59
    /**
60
     * @var Index[]
61
     */
62
    protected $_indexes = [];
63 64 65 66 67 68 69

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

    /**
70
     * @var ForeignKeyConstraint[]
71
     */
72
    protected $_fkConstraints = [];
73 74 75 76

    /**
     * @var array
     */
77
    protected $_options = [];
78

79
    /**
80
     * @var SchemaConfig
81 82 83
     */
    protected $_schemaConfig = null;

84
    /**
85 86 87 88
     * @param string                 $tableName
     * @param Column[]               $columns
     * @param Index[]                $indexes
     * @param ForeignKeyConstraint[] $fkConstraints
89
     * @param int                    $idGeneratorType
90
     * @param array                  $options
91
     *
92
     * @throws DBALException
93
     */
94
    public function __construct($tableName, array $columns=[], array $indexes=[], array $fkConstraints=[], $idGeneratorType = 0, array $options=[])
95
    {
96 97 98 99
        if (strlen($tableName) == 0) {
            throw DBALException::invalidTableName($tableName);
        }

100
        $this->_setName($tableName);
101

102
        foreach ($columns as $column) {
103 104
            $this->_addColumn($column);
        }
105

106
        foreach ($indexes as $idx) {
107 108 109
            $this->_addIndex($idx);
        }

110
        foreach ($fkConstraints as $constraint) {
111
            $this->_addForeignKeyConstraint($constraint);
112 113 114 115 116
        }

        $this->_options = $options;
    }

117
    /**
118
     * @param SchemaConfig $schemaConfig
Benjamin Morel's avatar
Benjamin Morel committed
119 120
     *
     * @return void
121 122 123 124 125 126 127
     */
    public function setSchemaConfig(SchemaConfig $schemaConfig)
    {
        $this->_schemaConfig = $schemaConfig;
    }

    /**
128
     * @return int
129 130 131 132 133 134
     */
    protected function _getMaxIdentifierLength()
    {
        if ($this->_schemaConfig instanceof SchemaConfig) {
            return $this->_schemaConfig->getMaxIdentifierLength();
        }
Gabriel Caruso's avatar
Gabriel Caruso committed
135 136

        return 63;
137 138
    }

139
    /**
Benjamin Morel's avatar
Benjamin Morel committed
140
     * Sets the Primary Key.
141
     *
Benjamin Morel's avatar
Benjamin Morel committed
142 143 144
     * @param array          $columns
     * @param string|boolean $indexName
     *
145
     * @return self
146
     */
147
    public function setPrimaryKey(array $columns, $indexName = false)
148
    {
149
        $this->_addIndex($this->_createIndex($columns, $indexName ?: "primary", true, true));
150

151
        foreach ($columns as $columnName) {
152 153 154 155
            $column = $this->getColumn($columnName);
            $column->setNotnull(true);
        }

156
        return $this;
157 158 159
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
160 161 162
     * @param array       $columnNames
     * @param string|null $indexName
     * @param array       $flags
163
     * @param array       $options
Benjamin Morel's avatar
Benjamin Morel committed
164
     *
165
     * @return self
166
     */
167
    public function addIndex(array $columnNames, $indexName = null, array $flags = [], array $options = [])
168
    {
Steve Müller's avatar
Steve Müller committed
169
        if ($indexName == null) {
170
            $indexName = $this->_generateIdentifierName(
171
                array_merge([$this->getName()], $columnNames), "idx", $this->_getMaxIdentifierLength()
172
            );
173 174
        }

175
        return $this->_addIndex($this->_createIndex($columnNames, $indexName, false, false, $flags, $options));
176 177
    }

178
    /**
Benjamin Morel's avatar
Benjamin Morel committed
179
     * Drops the primary key from this table.
180 181 182 183 184 185
     *
     * @return void
     */
    public function dropPrimaryKey()
    {
        $this->dropIndex($this->_primaryKeyName);
186
        $this->_primaryKeyName = false;
187 188 189
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
190 191 192
     * Drops an index from this table.
     *
     * @param string $indexName The index name.
193 194
     *
     * @return void
Benjamin Morel's avatar
Benjamin Morel committed
195
     *
196
     * @throws SchemaException If the index does not exist.
197 198 199
     */
    public function dropIndex($indexName)
    {
200
        $indexName = $this->normalizeIdentifier($indexName);
201
        if ( ! $this->hasIndex($indexName)) {
202 203 204 205 206
            throw SchemaException::indexDoesNotExist($indexName, $this->_name);
        }
        unset($this->_indexes[$indexName]);
    }

207
    /**
Benjamin Morel's avatar
Benjamin Morel committed
208 209
     * @param array       $columnNames
     * @param string|null $indexName
210
     * @param array       $options
211
     *
212
     * @return self
213
     */
214
    public function addUniqueIndex(array $columnNames, $indexName = null, array $options = [])
215
    {
216
        if ($indexName === null) {
217
            $indexName = $this->_generateIdentifierName(
218
                array_merge([$this->getName()], $columnNames), "uniq", $this->_getMaxIdentifierLength()
219
            );
220 221
        }

222
        return $this->_addIndex($this->_createIndex($columnNames, $indexName, true, false, [], $options));
223 224
    }

225 226 227 228 229 230 231
    /**
     * Renames an index.
     *
     * @param string      $oldIndexName The name of the index to rename from.
     * @param string|null $newIndexName The name of the index to rename to.
     *                                  If null is given, the index name will be auto-generated.
     *
232
     * @return self This table instance.
233 234 235 236 237 238
     *
     * @throws SchemaException if no index exists for the given current name
     *                         or if an index with the given new name already exists on this table.
     */
    public function renameIndex($oldIndexName, $newIndexName = null)
    {
239 240
        $oldIndexName           = $this->normalizeIdentifier($oldIndexName);
        $normalizedNewIndexName = $this->normalizeIdentifier($newIndexName);
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264

        if ($oldIndexName === $normalizedNewIndexName) {
            return $this;
        }

        if ( ! $this->hasIndex($oldIndexName)) {
            throw SchemaException::indexDoesNotExist($oldIndexName, $this->_name);
        }

        if ($this->hasIndex($normalizedNewIndexName)) {
            throw SchemaException::indexAlreadyExists($normalizedNewIndexName, $this->_name);
        }

        $oldIndex = $this->_indexes[$oldIndexName];

        if ($oldIndex->isPrimary()) {
            $this->dropPrimaryKey();

            return $this->setPrimaryKey($oldIndex->getColumns(), $newIndexName);
        }

        unset($this->_indexes[$oldIndexName]);

        if ($oldIndex->isUnique()) {
265
            return $this->addUniqueIndex($oldIndex->getColumns(), $newIndexName, $oldIndex->getOptions());
266 267
        }

268
        return $this->addIndex($oldIndex->getColumns(), $newIndexName, $oldIndex->getFlags(), $oldIndex->getOptions());
269 270
    }

271
    /**
Benjamin Morel's avatar
Benjamin Morel committed
272 273 274
     * Checks if an index begins in the order of the given columns.
     *
     * @param array $columnsNames
275
     *
276
     * @return bool
277 278 279
     */
    public function columnsAreIndexed(array $columnsNames)
    {
280
        foreach ($this->getIndexes() as $index) {
281 282
            /* @var $index Index */
            if ($index->spansColumns($columnsNames)) {
283 284 285
                return true;
            }
        }
Benjamin Morel's avatar
Benjamin Morel committed
286

287 288 289
        return false;
    }

290
    /**
291 292 293 294 295 296
     * @param array  $columnNames
     * @param string $indexName
     * @param bool   $isUnique
     * @param bool   $isPrimary
     * @param array  $flags
     * @param array  $options
297
     *
298
     * @return Index
Benjamin Morel's avatar
Benjamin Morel committed
299
     *
300
     * @throws SchemaException
301
     */
302
    private function _createIndex(array $columnNames, $indexName, $isUnique, $isPrimary, array $flags = [], array $options = [])
303
    {
304
        if (preg_match('(([^a-zA-Z0-9_]+))', $this->normalizeIdentifier($indexName))) {
305 306 307
            throw SchemaException::indexNameInvalid($indexName);
        }

308
        foreach ($columnNames as $columnName => $indexColOptions) {
beberlei's avatar
beberlei committed
309 310 311 312
            if (is_numeric($columnName) && is_string($indexColOptions)) {
                $columnName = $indexColOptions;
            }

313
            if ( ! $this->hasColumn($columnName)) {
314
                throw SchemaException::columnDoesNotExist($columnName, $this->_name);
315 316
            }
        }
Benjamin Morel's avatar
Benjamin Morel committed
317

318
        return new Index($indexName, $columnNames, $isUnique, $isPrimary, $flags, $options);
319 320 321 322
    }

    /**
     * @param string $columnName
Benjamin Morel's avatar
Benjamin Morel committed
323 324 325
     * @param string $typeName
     * @param array  $options
     *
326
     * @return Column
327
     */
328
    public function addColumn($columnName, $typeName, array $options=[])
329 330 331 332
    {
        $column = new Column($columnName, Type::getType($typeName), $options);

        $this->_addColumn($column);
Benjamin Morel's avatar
Benjamin Morel committed
333

334
        return $column;
335 336 337
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
338
     * Renames a Column.
339 340 341
     *
     * @param string $oldColumnName
     * @param string $newColumnName
Benjamin Morel's avatar
Benjamin Morel committed
342
     *
343
     * @deprecated
Benjamin Morel's avatar
Benjamin Morel committed
344
     *
345
     * @throws DBALException
346 347 348
     */
    public function renameColumn($oldColumnName, $newColumnName)
    {
349 350 351
        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.");
352 353 354
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
355
     * Change Column Details.
356
     *
357
     * @param string $columnName
Benjamin Morel's avatar
Benjamin Morel committed
358 359
     * @param array  $options
     *
360
     * @return self
361 362 363 364 365
     */
    public function changeColumn($columnName, array $options)
    {
        $column = $this->getColumn($columnName);
        $column->setOptions($options);
Benjamin Morel's avatar
Benjamin Morel committed
366

367 368 369 370
        return $this;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
371
     * Drops a Column from the Table.
372
     *
373
     * @param string $columnName
Benjamin Morel's avatar
Benjamin Morel committed
374
     *
375
     * @return self
376 377 378
     */
    public function dropColumn($columnName)
    {
379
        $columnName = $this->normalizeIdentifier($columnName);
380
        unset($this->_columns[$columnName]);
Benjamin Morel's avatar
Benjamin Morel committed
381

382 383 384 385
        return $this;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
386
     * Adds a foreign key constraint.
387
     *
Benjamin Morel's avatar
Benjamin Morel committed
388
     * Name is inferred from the local columns.
389
     *
390
     * @param Table|string $foreignTable       Table schema instance or table name
391 392 393 394
     * @param array        $localColumnNames
     * @param array        $foreignColumnNames
     * @param array        $options
     * @param string|null  $constraintName
Benjamin Morel's avatar
Benjamin Morel committed
395
     *
396
     * @return self
397
     */
398
    public function addForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options=[], $constraintName = null)
399
    {
400
        $constraintName = $constraintName ?: $this->_generateIdentifierName(array_merge((array) $this->getName(), $localColumnNames), "fk", $this->_getMaxIdentifierLength());
Benjamin Morel's avatar
Benjamin Morel committed
401

402
        return $this->addNamedForeignKeyConstraint($constraintName, $foreignTable, $localColumnNames, $foreignColumnNames, $options);
403 404
    }

405
    /**
Benjamin Morel's avatar
Benjamin Morel committed
406
     * Adds a foreign key constraint.
407
     *
Pascal Borreli's avatar
Pascal Borreli committed
408
     * Name is to be generated by the database itself.
409
     *
410
     * @deprecated Use {@link addForeignKeyConstraint}
Benjamin Morel's avatar
Benjamin Morel committed
411
     *
412
     * @param Table|string $foreignTable       Table schema instance or table name
413 414 415
     * @param array        $localColumnNames
     * @param array        $foreignColumnNames
     * @param array        $options
Benjamin Morel's avatar
Benjamin Morel committed
416
     *
417
     * @return self
418
     */
419
    public function addUnnamedForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options=[])
420
    {
421
        return $this->addForeignKeyConstraint($foreignTable, $localColumnNames, $foreignColumnNames, $options);
422 423
    }

424
    /**
Benjamin Morel's avatar
Benjamin Morel committed
425
     * Adds a foreign key constraint with a given name.
426
     *
427
     * @deprecated Use {@link addForeignKeyConstraint}
Benjamin Morel's avatar
Benjamin Morel committed
428
     *
429
     * @param string       $name
430
     * @param Table|string $foreignTable       Table schema instance or table name
431 432 433
     * @param array        $localColumnNames
     * @param array        $foreignColumnNames
     * @param array        $options
Benjamin Morel's avatar
Benjamin Morel committed
434
     *
435
     * @return self
Benjamin Morel's avatar
Benjamin Morel committed
436
     *
437
     * @throws SchemaException
438
     */
439
    public function addNamedForeignKeyConstraint($name, $foreignTable, array $localColumnNames, array $foreignColumnNames, array $options=[])
440
    {
441
        if ($foreignTable instanceof Table) {
442
            foreach ($foreignColumnNames as $columnName) {
443
                if ( ! $foreignTable->hasColumn($columnName)) {
444
                    throw SchemaException::columnDoesNotExist($columnName, $foreignTable->getName());
445
                }
446 447
            }
        }
448

449
        foreach ($localColumnNames as $columnName) {
450
            if ( ! $this->hasColumn($columnName)) {
451
                throw SchemaException::columnDoesNotExist($columnName, $this->_name);
452 453
            }
        }
454

455
        $constraint = new ForeignKeyConstraint(
456
            $localColumnNames, $foreignTable, $foreignColumnNames, $name, $options
457
        );
458
        $this->_addForeignKeyConstraint($constraint);
459

460 461 462 463 464 465
        return $this;
    }

    /**
     * @param string $name
     * @param string $value
Benjamin Morel's avatar
Benjamin Morel committed
466
     *
467
     * @return self
468 469 470 471
     */
    public function addOption($name, $value)
    {
        $this->_options[$name] = $value;
Benjamin Morel's avatar
Benjamin Morel committed
472

473 474 475 476
        return $this;
    }

    /**
477
     * @param Column $column
Benjamin Morel's avatar
Benjamin Morel committed
478 479 480
     *
     * @return void
     *
481
     * @throws SchemaException
482 483 484
     */
    protected function _addColumn(Column $column)
    {
485
        $columnName = $column->getName();
486
        $columnName = $this->normalizeIdentifier($columnName);
487

488
        if (isset($this->_columns[$columnName])) {
489
            throw SchemaException::columnAlreadyExists($this->getName(), $columnName);
490 491 492 493 494 495
        }

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

    /**
Benjamin Morel's avatar
Benjamin Morel committed
496
     * Adds an index to the table.
497
     *
498
     * @param Index $indexCandidate
Benjamin Morel's avatar
Benjamin Morel committed
499
     *
500
     * @return self
Benjamin Morel's avatar
Benjamin Morel committed
501
     *
502
     * @throws SchemaException
503
     */
504
    protected function _addIndex(Index $indexCandidate)
505
    {
506
        $indexName = $indexCandidate->getName();
507
        $indexName = $this->normalizeIdentifier($indexName);
508
        $replacedImplicitIndexes = [];
509

510 511 512 513 514 515 516 517 518
        foreach ($this->implicitIndexes as $name => $implicitIndex) {
            if ($implicitIndex->isFullfilledBy($indexCandidate) && isset($this->_indexes[$name])) {
                $replacedImplicitIndexes[] = $name;
            }
        }

        if ((isset($this->_indexes[$indexName]) && ! in_array($indexName, $replacedImplicitIndexes, true)) ||
            ($this->_primaryKeyName != false && $indexCandidate->isPrimary())
        ) {
519
            throw SchemaException::indexAlreadyExists($indexName, $this->_name);
520 521
        }

522 523 524 525
        foreach ($replacedImplicitIndexes as $name) {
            unset($this->_indexes[$name], $this->implicitIndexes[$name]);
        }

526
        if ($indexCandidate->isPrimary()) {
527 528 529
            $this->_primaryKeyName = $indexName;
        }

530
        $this->_indexes[$indexName] = $indexCandidate;
Benjamin Morel's avatar
Benjamin Morel committed
531

532 533 534 535
        return $this;
    }

    /**
536
     * @param ForeignKeyConstraint $constraint
Benjamin Morel's avatar
Benjamin Morel committed
537 538
     *
     * @return void
539
     */
540
    protected function _addForeignKeyConstraint(ForeignKeyConstraint $constraint)
541
    {
542
        $constraint->setLocalTable($this);
543

Steve Müller's avatar
Steve Müller committed
544
        if (strlen($constraint->getName())) {
545 546 547
            $name = $constraint->getName();
        } else {
            $name = $this->_generateIdentifierName(
548
                array_merge((array) $this->getName(), $constraint->getLocalColumns()), "fk", $this->_getMaxIdentifierLength()
549 550
            );
        }
551
        $name = $this->normalizeIdentifier($name);
552 553

        $this->_fkConstraints[$name] = $constraint;
554

Pascal Borreli's avatar
Pascal Borreli committed
555
        // add an explicit index on the foreign key columns. If there is already an index that fulfils this requirements drop the request.
556
        // In the case of __construct calling this method during hydration from schema-details all the explicitly added indexes
Pascal Borreli's avatar
Pascal Borreli committed
557
        // lead to duplicates. This creates computation overhead in this case, however no duplicate indexes are ever added (based on columns).
558
        $indexName = $this->_generateIdentifierName(
559
            array_merge([$this->getName()], $constraint->getColumns()),
560 561 562 563 564 565 566 567 568 569 570
            "idx",
            $this->_getMaxIdentifierLength()
        );
        $indexCandidate = $this->_createIndex($constraint->getColumns(), $indexName, false, false);

        foreach ($this->_indexes as $existingIndex) {
            if ($indexCandidate->isFullfilledBy($existingIndex)) {
                return;
            }
        }

571 572
        $this->_addIndex($indexCandidate);
        $this->implicitIndexes[$this->normalizeIdentifier($indexName)] = $indexCandidate;
573 574 575
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
576 577 578 579
     * Returns whether this table has a foreign key constraint with the given name.
     *
     * @param string $constraintName
     *
580
     * @return bool
581 582 583
     */
    public function hasForeignKey($constraintName)
    {
584
        $constraintName = $this->normalizeIdentifier($constraintName);
Benjamin Morel's avatar
Benjamin Morel committed
585

586 587 588 589
        return isset($this->_fkConstraints[$constraintName]);
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
590 591 592 593
     * Returns the foreign key constraint with the given name.
     *
     * @param string $constraintName The constraint name.
     *
594
     * @return ForeignKeyConstraint
Benjamin Morel's avatar
Benjamin Morel committed
595
     *
596
     * @throws SchemaException If the foreign key does not exist.
597 598 599
     */
    public function getForeignKey($constraintName)
    {
600
        $constraintName = $this->normalizeIdentifier($constraintName);
Steve Müller's avatar
Steve Müller committed
601
        if (!$this->hasForeignKey($constraintName)) {
602
            throw SchemaException::foreignKeyDoesNotExist($constraintName, $this->_name);
603 604 605
        }

        return $this->_fkConstraints[$constraintName];
606 607
    }

Benjamin Morel's avatar
Benjamin Morel committed
608 609 610 611 612 613 614
    /**
     * Removes the foreign key constraint with the given name.
     *
     * @param string $constraintName The constraint name.
     *
     * @return void
     *
615
     * @throws SchemaException
Benjamin Morel's avatar
Benjamin Morel committed
616
     */
617 618
    public function removeForeignKey($constraintName)
    {
619
        $constraintName = $this->normalizeIdentifier($constraintName);
Steve Müller's avatar
Steve Müller committed
620
        if (!$this->hasForeignKey($constraintName)) {
621 622 623 624 625 626
            throw SchemaException::foreignKeyDoesNotExist($constraintName, $this->_name);
        }

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

627
    /**
628
     * Returns ordered list of columns (primary keys are first, then foreign keys, then the rest)
629
     * @return Column[]
630 631 632
     */
    public function getColumns()
    {
633 634 635 636
        $primaryKeyColumns = [];
        if ($this->hasPrimaryKey()) {
            $primaryKeyColumns = $this->filterColumns($this->getPrimaryKey()->getColumns());
        }
637

638
        return array_merge($primaryKeyColumns, $this->getForeignKeyColumns(), $this->_columns);
639
    }
640

641 642 643 644
    /**
     * Returns foreign key columns
     * @return Column[]
     */
645
    private function getForeignKeyColumns()
646
    {
647 648 649 650
        $foreignKeyColumns = [];
        foreach ($this->getForeignKeys() as $foreignKey) {
            /* @var $foreignKey ForeignKeyConstraint */
            $foreignKeyColumns = array_merge($foreignKeyColumns, $foreignKey->getColumns());
651
        }
652
        return $this->filterColumns($foreignKeyColumns);
653
    }
Benjamin Morel's avatar
Benjamin Morel committed
654

655
    /**
656 657 658
     * Returns only columns that have specified names
     * @param array $columnNames
     * @return Column[]
659
     */
660
    private function filterColumns(array $columnNames)
661
    {
662 663 664
        return array_filter($this->_columns, function ($columnName) use ($columnNames) {
            return in_array($columnName, $columnNames, true);
        }, ARRAY_FILTER_USE_KEY);
665 666 667
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
668
     * Returns whether this table has a Column with the given name.
669
     *
Benjamin Morel's avatar
Benjamin Morel committed
670 671
     * @param string $columnName The column name.
     *
672
     * @return bool
673 674 675
     */
    public function hasColumn($columnName)
    {
676
        $columnName = $this->normalizeIdentifier($columnName);
Benjamin Morel's avatar
Benjamin Morel committed
677

678 679 680 681
        return isset($this->_columns[$columnName]);
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
682 683 684
     * Returns the Column with the given name.
     *
     * @param string $columnName The column name.
685
     *
686
     * @return Column
Benjamin Morel's avatar
Benjamin Morel committed
687
     *
688
     * @throws SchemaException If the column does not exist.
689 690 691
     */
    public function getColumn($columnName)
    {
692
        $columnName = $this->normalizeIdentifier($columnName);
693
        if ( ! $this->hasColumn($columnName)) {
694
            throw SchemaException::columnDoesNotExist($columnName, $this->_name);
695 696 697 698 699 700
        }

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

    /**
Benjamin Morel's avatar
Benjamin Morel committed
701 702
     * Returns the primary key.
     *
703
     * @return Index|null The primary key, or null if this Table has no primary key.
704 705 706
     */
    public function getPrimaryKey()
    {
707
        if ( ! $this->hasPrimaryKey()) {
708 709
            return null;
        }
Benjamin Morel's avatar
Benjamin Morel committed
710

711 712 713
        return $this->getIndex($this->_primaryKeyName);
    }

714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
    /**
     * Returns the primary key columns.
     *
     * @return array
     *
     * @throws DBALException
     */
    public function getPrimaryKeyColumns()
    {
        if ( ! $this->hasPrimaryKey()) {
            throw new DBALException("Table " . $this->getName() . " has no primary key.");
        }
        return $this->getPrimaryKey()->getColumns();
    }

729
    /**
Benjamin Morel's avatar
Benjamin Morel committed
730
     * Returns whether this table has a primary key.
731
     *
732
     * @return bool
733 734 735 736 737 738
     */
    public function hasPrimaryKey()
    {
        return ($this->_primaryKeyName && $this->hasIndex($this->_primaryKeyName));
    }

739
    /**
Benjamin Morel's avatar
Benjamin Morel committed
740 741 742 743
     * Returns whether this table has an Index with the given name.
     *
     * @param string $indexName The index name.
     *
744
     * @return bool
745 746 747
     */
    public function hasIndex($indexName)
    {
748
        $indexName = $this->normalizeIdentifier($indexName);
Benjamin Morel's avatar
Benjamin Morel committed
749

750 751 752 753
        return (isset($this->_indexes[$indexName]));
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
754 755 756 757
     * Returns the Index with the given name.
     *
     * @param string $indexName The index name.
     *
758
     * @return Index
Benjamin Morel's avatar
Benjamin Morel committed
759
     *
760
     * @throws SchemaException If the index does not exist.
761 762 763
     */
    public function getIndex($indexName)
    {
764
        $indexName = $this->normalizeIdentifier($indexName);
765
        if ( ! $this->hasIndex($indexName)) {
766
            throw SchemaException::indexDoesNotExist($indexName, $this->_name);
767
        }
Benjamin Morel's avatar
Benjamin Morel committed
768

769 770 771 772
        return $this->_indexes[$indexName];
    }

    /**
773
     * @return Index[]
774 775 776 777 778 779 780
     */
    public function getIndexes()
    {
        return $this->_indexes;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
781
     * Returns the foreign key constraints.
782
     *
783
     * @return ForeignKeyConstraint[]
784
     */
785
    public function getForeignKeys()
786
    {
787
        return $this->_fkConstraints;
788 789
    }

Benjamin Morel's avatar
Benjamin Morel committed
790 791 792
    /**
     * @param string $name
     *
793
     * @return bool
Benjamin Morel's avatar
Benjamin Morel committed
794
     */
795 796 797 798 799
    public function hasOption($name)
    {
        return isset($this->_options[$name]);
    }

Benjamin Morel's avatar
Benjamin Morel committed
800 801 802 803 804
    /**
     * @param string $name
     *
     * @return mixed
     */
805 806 807 808 809
    public function getOption($name)
    {
        return $this->_options[$name];
    }

Benjamin Morel's avatar
Benjamin Morel committed
810 811 812
    /**
     * @return array
     */
813 814 815 816 817
    public function getOptions()
    {
        return $this->_options;
    }

818
    /**
819
     * @param Visitor $visitor
Benjamin Morel's avatar
Benjamin Morel committed
820 821
     *
     * @return void
822 823 824 825 826
     */
    public function visit(Visitor $visitor)
    {
        $visitor->acceptTable($this);

827
        foreach ($this->getColumns() as $column) {
828
            $visitor->acceptColumn($this, $column);
829 830
        }

831
        foreach ($this->getIndexes() as $index) {
832 833 834
            $visitor->acceptIndex($this, $index);
        }

835
        foreach ($this->getForeignKeys() as $constraint) {
836
            $visitor->acceptForeignKey($this, $constraint);
837 838
        }
    }
839 840

    /**
Benjamin Morel's avatar
Benjamin Morel committed
841 842 843
     * Clone of a Table triggers a deep clone of all affected assets.
     *
     * @return void
844 845 846
     */
    public function __clone()
    {
847
        foreach ($this->_columns as $k => $column) {
848 849
            $this->_columns[$k] = clone $column;
        }
850
        foreach ($this->_indexes as $k => $index) {
851 852
            $this->_indexes[$k] = clone $index;
        }
853
        foreach ($this->_fkConstraints as $k => $fk) {
854 855 856 857
            $this->_fkConstraints[$k] = clone $fk;
            $this->_fkConstraints[$k]->setLocalTable($this);
        }
    }
858 859 860 861 862 863 864 865 866 867 868 869 870 871

    /**
     * Normalizes a given identifier.
     *
     * Trims quotes and lowercases the given identifier.
     *
     * @param string $identifier The identifier to normalize.
     *
     * @return string The normalized identifier.
     */
    private function normalizeIdentifier($identifier)
    {
        return $this->trimQuotes(strtolower($identifier));
    }
872
}