Table.php 23.5 KB
Newer Older
1 2 3 4
<?php

namespace Doctrine\DBAL\Schema;

5
use Doctrine\DBAL\DBALException;
6 7
use Doctrine\DBAL\Schema\Visitor\Visitor;
use Doctrine\DBAL\Types\Type;
8 9 10 11 12 13 14
use const ARRAY_FILTER_USE_KEY;
use function array_filter;
use function array_merge;
use function in_array;
use function preg_match;
use function strlen;
use function strtolower;
15 16

/**
Benjamin Morel's avatar
Benjamin Morel committed
17
 * Object Representation of a table.
18 19 20
 */
class Table extends AbstractAsset
{
21
    /** @var Column[] */
22
    protected $_columns = [];
23

24
    /** @var Index[] */
25
    private $implicitIndexes = [];
26

27
    /** @var Index[] */
28
    protected $_indexes = [];
29

30
    /** @var string */
31 32
    protected $_primaryKeyName = false;

33
    /** @var ForeignKeyConstraint[] */
34
    protected $_fkConstraints = [];
35

36
    /** @var mixed[] */
37 38 39
    protected $_options = [
        'create_options' => [],
    ];
40

41
    /** @var SchemaConfig|null */
42 43
    protected $_schemaConfig = null;

44
    /**
45 46 47 48
     * @param string                 $tableName
     * @param Column[]               $columns
     * @param Index[]                $indexes
     * @param ForeignKeyConstraint[] $fkConstraints
49
     * @param int                    $idGeneratorType
50
     * @param mixed[]                $options
51
     *
52
     * @throws DBALException
53
     */
54
    public function __construct($tableName, array $columns = [], array $indexes = [], array $fkConstraints = [], $idGeneratorType = 0, array $options = [])
55
    {
56
        if (strlen($tableName) === 0) {
57 58 59
            throw DBALException::invalidTableName($tableName);
        }

60
        $this->_setName($tableName);
61

62
        foreach ($columns as $column) {
63 64
            $this->_addColumn($column);
        }
65

66
        foreach ($indexes as $idx) {
67 68 69
            $this->_addIndex($idx);
        }

70
        foreach ($fkConstraints as $constraint) {
71
            $this->_addForeignKeyConstraint($constraint);
72 73
        }

74
        $this->_options = array_merge($this->_options, $options);
75 76
    }

77
    /**
Benjamin Morel's avatar
Benjamin Morel committed
78
     * @return void
79 80 81 82 83 84 85
     */
    public function setSchemaConfig(SchemaConfig $schemaConfig)
    {
        $this->_schemaConfig = $schemaConfig;
    }

    /**
86
     * @return int
87 88 89 90 91 92
     */
    protected function _getMaxIdentifierLength()
    {
        if ($this->_schemaConfig instanceof SchemaConfig) {
            return $this->_schemaConfig->getMaxIdentifierLength();
        }
Gabriel Caruso's avatar
Gabriel Caruso committed
93 94

        return 63;
95 96
    }

97
    /**
Benjamin Morel's avatar
Benjamin Morel committed
98
     * Sets the Primary Key.
99
     *
Sergei Morozov's avatar
Sergei Morozov committed
100 101
     * @param string[]     $columnNames
     * @param string|false $indexName
Benjamin Morel's avatar
Benjamin Morel committed
102
     *
103
     * @return self
104
     */
105
    public function setPrimaryKey(array $columnNames, $indexName = false)
106
    {
107
        $this->_addIndex($this->_createIndex($columnNames, $indexName ?: 'primary', true, true));
108

109
        foreach ($columnNames as $columnName) {
110 111 112 113
            $column = $this->getColumn($columnName);
            $column->setNotnull(true);
        }

114
        return $this;
115 116 117
    }

    /**
118
     * @param string[]    $columnNames
Benjamin Morel's avatar
Benjamin Morel committed
119
     * @param string|null $indexName
120 121
     * @param string[]    $flags
     * @param mixed[]     $options
Benjamin Morel's avatar
Benjamin Morel committed
122
     *
123
     * @return self
124
     */
125
    public function addIndex(array $columnNames, $indexName = null, array $flags = [], array $options = [])
126
    {
127
        if ($indexName === null) {
128
            $indexName = $this->_generateIdentifierName(
129 130 131
                array_merge([$this->getName()], $columnNames),
                'idx',
                $this->_getMaxIdentifierLength()
132
            );
133 134
        }

135
        return $this->_addIndex($this->_createIndex($columnNames, $indexName, false, false, $flags, $options));
136 137
    }

138
    /**
Benjamin Morel's avatar
Benjamin Morel committed
139
     * Drops the primary key from this table.
140 141 142 143 144 145
     *
     * @return void
     */
    public function dropPrimaryKey()
    {
        $this->dropIndex($this->_primaryKeyName);
146
        $this->_primaryKeyName = false;
147 148 149
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
150 151 152
     * Drops an index from this table.
     *
     * @param string $indexName The index name.
153 154
     *
     * @return void
Benjamin Morel's avatar
Benjamin Morel committed
155
     *
156
     * @throws SchemaException If the index does not exist.
157 158 159
     */
    public function dropIndex($indexName)
    {
160
        $indexName = $this->normalizeIdentifier($indexName);
161
        if (! $this->hasIndex($indexName)) {
162 163 164 165 166
            throw SchemaException::indexDoesNotExist($indexName, $this->_name);
        }
        unset($this->_indexes[$indexName]);
    }

167
    /**
168
     * @param string[]    $columnNames
Benjamin Morel's avatar
Benjamin Morel committed
169
     * @param string|null $indexName
170
     * @param mixed[]     $options
171
     *
172
     * @return self
173
     */
174
    public function addUniqueIndex(array $columnNames, $indexName = null, array $options = [])
175
    {
176
        if ($indexName === null) {
177
            $indexName = $this->_generateIdentifierName(
178 179 180
                array_merge([$this->getName()], $columnNames),
                'uniq',
                $this->_getMaxIdentifierLength()
181
            );
182 183
        }

184
        return $this->_addIndex($this->_createIndex($columnNames, $indexName, true, false, [], $options));
185 186
    }

187 188 189 190 191 192 193
    /**
     * 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.
     *
194
     * @return self This table instance.
195
     *
196
     * @throws SchemaException If no index exists for the given current name
197 198 199 200
     *                         or if an index with the given new name already exists on this table.
     */
    public function renameIndex($oldIndexName, $newIndexName = null)
    {
201 202
        $oldIndexName           = $this->normalizeIdentifier($oldIndexName);
        $normalizedNewIndexName = $this->normalizeIdentifier($newIndexName);
203 204 205 206 207

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

208
        if (! $this->hasIndex($oldIndexName)) {
209 210 211 212 213 214 215 216 217 218 219 220
            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();

Sergei Morozov's avatar
Sergei Morozov committed
221
            return $this->setPrimaryKey($oldIndex->getColumns(), $newIndexName ?? false);
222 223 224 225 226
        }

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

        if ($oldIndex->isUnique()) {
227
            return $this->addUniqueIndex($oldIndex->getColumns(), $newIndexName, $oldIndex->getOptions());
228 229
        }

230
        return $this->addIndex($oldIndex->getColumns(), $newIndexName, $oldIndex->getFlags(), $oldIndex->getOptions());
231 232
    }

233
    /**
Benjamin Morel's avatar
Benjamin Morel committed
234 235
     * Checks if an index begins in the order of the given columns.
     *
236
     * @param string[] $columnNames
237
     *
238
     * @return bool
239
     */
240
    public function columnsAreIndexed(array $columnNames)
241
    {
242
        foreach ($this->getIndexes() as $index) {
243
            /** @var $index Index */
244
            if ($index->spansColumns($columnNames)) {
245 246 247
                return true;
            }
        }
Benjamin Morel's avatar
Benjamin Morel committed
248

249 250 251
        return false;
    }

252
    /**
253 254 255 256 257 258
     * @param string[] $columnNames
     * @param string   $indexName
     * @param bool     $isUnique
     * @param bool     $isPrimary
     * @param string[] $flags
     * @param mixed[]  $options
259
     *
260
     * @return Index
Benjamin Morel's avatar
Benjamin Morel committed
261
     *
262
     * @throws SchemaException
263
     */
264
    private function _createIndex(array $columnNames, $indexName, $isUnique, $isPrimary, array $flags = [], array $options = [])
265
    {
266
        if (preg_match('(([^a-zA-Z0-9_]+))', $this->normalizeIdentifier($indexName))) {
267 268 269
            throw SchemaException::indexNameInvalid($indexName);
        }

270
        foreach ($columnNames as $columnName) {
271
            if (! $this->hasColumn($columnName)) {
272
                throw SchemaException::columnDoesNotExist($columnName, $this->_name);
273 274
            }
        }
Benjamin Morel's avatar
Benjamin Morel committed
275

276
        return new Index($indexName, $columnNames, $isUnique, $isPrimary, $flags, $options);
277 278 279
    }

    /**
280 281 282
     * @param string  $columnName
     * @param string  $typeName
     * @param mixed[] $options
Benjamin Morel's avatar
Benjamin Morel committed
283
     *
284
     * @return Column
285
     */
286
    public function addColumn($columnName, $typeName, array $options = [])
287 288 289 290
    {
        $column = new Column($columnName, Type::getType($typeName), $options);

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

292
        return $column;
293 294 295
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
296
     * Renames a Column.
297
     *
298 299
     * @deprecated
     *
300 301
     * @param string $oldColumnName
     * @param string $newColumnName
Benjamin Morel's avatar
Benjamin Morel committed
302
     *
303
     * @throws DBALException
304 305 306
     */
    public function renameColumn($oldColumnName, $newColumnName)
    {
307 308 309
        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.');
310 311 312
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
313
     * Change Column Details.
314
     *
315 316
     * @param string  $columnName
     * @param mixed[] $options
Benjamin Morel's avatar
Benjamin Morel committed
317
     *
318
     * @return self
319 320 321 322 323
     */
    public function changeColumn($columnName, array $options)
    {
        $column = $this->getColumn($columnName);
        $column->setOptions($options);
Benjamin Morel's avatar
Benjamin Morel committed
324

325 326 327 328
        return $this;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
329
     * Drops a Column from the Table.
330
     *
331
     * @param string $columnName
Benjamin Morel's avatar
Benjamin Morel committed
332
     *
333
     * @return self
334 335 336
     */
    public function dropColumn($columnName)
    {
337
        $columnName = $this->normalizeIdentifier($columnName);
338
        unset($this->_columns[$columnName]);
Benjamin Morel's avatar
Benjamin Morel committed
339

340 341 342 343
        return $this;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
344
     * Adds a foreign key constraint.
345
     *
Benjamin Morel's avatar
Benjamin Morel committed
346
     * Name is inferred from the local columns.
347
     *
348
     * @param Table|string $foreignTable       Table schema instance or table name
349 350 351
     * @param string[]     $localColumnNames
     * @param string[]     $foreignColumnNames
     * @param mixed[]      $options
352
     * @param string|null  $constraintName
Benjamin Morel's avatar
Benjamin Morel committed
353
     *
354
     * @return self
355
     */
356
    public function addForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options = [], $constraintName = null)
357
    {
358
        $constraintName = $constraintName ?: $this->_generateIdentifierName(array_merge((array) $this->getName(), $localColumnNames), 'fk', $this->_getMaxIdentifierLength());
Benjamin Morel's avatar
Benjamin Morel committed
359

360
        return $this->addNamedForeignKeyConstraint($constraintName, $foreignTable, $localColumnNames, $foreignColumnNames, $options);
361 362
    }

363
    /**
Benjamin Morel's avatar
Benjamin Morel committed
364
     * Adds a foreign key constraint.
365
     *
Pascal Borreli's avatar
Pascal Borreli committed
366
     * Name is to be generated by the database itself.
367
     *
368
     * @deprecated Use {@link addForeignKeyConstraint}
Benjamin Morel's avatar
Benjamin Morel committed
369
     *
370
     * @param Table|string $foreignTable       Table schema instance or table name
371 372 373
     * @param string[]     $localColumnNames
     * @param string[]     $foreignColumnNames
     * @param mixed[]      $options
Benjamin Morel's avatar
Benjamin Morel committed
374
     *
375
     * @return self
376
     */
377
    public function addUnnamedForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options = [])
378
    {
379
        return $this->addForeignKeyConstraint($foreignTable, $localColumnNames, $foreignColumnNames, $options);
380 381
    }

382
    /**
Benjamin Morel's avatar
Benjamin Morel committed
383
     * Adds a foreign key constraint with a given name.
384
     *
385
     * @deprecated Use {@link addForeignKeyConstraint}
Benjamin Morel's avatar
Benjamin Morel committed
386
     *
387
     * @param string       $name
388
     * @param Table|string $foreignTable       Table schema instance or table name
389 390 391
     * @param string[]     $localColumnNames
     * @param string[]     $foreignColumnNames
     * @param mixed[]      $options
Benjamin Morel's avatar
Benjamin Morel committed
392
     *
393
     * @return self
Benjamin Morel's avatar
Benjamin Morel committed
394
     *
395
     * @throws SchemaException
396
     */
397
    public function addNamedForeignKeyConstraint($name, $foreignTable, array $localColumnNames, array $foreignColumnNames, array $options = [])
398
    {
399
        if ($foreignTable instanceof Table) {
400
            foreach ($foreignColumnNames as $columnName) {
401
                if (! $foreignTable->hasColumn($columnName)) {
402
                    throw SchemaException::columnDoesNotExist($columnName, $foreignTable->getName());
403
                }
404 405
            }
        }
406

407
        foreach ($localColumnNames as $columnName) {
408
            if (! $this->hasColumn($columnName)) {
409
                throw SchemaException::columnDoesNotExist($columnName, $this->_name);
410 411
            }
        }
412

413
        $constraint = new ForeignKeyConstraint(
414 415 416 417 418
            $localColumnNames,
            $foreignTable,
            $foreignColumnNames,
            $name,
            $options
419
        );
420
        $this->_addForeignKeyConstraint($constraint);
421

422 423 424 425 426
        return $this;
    }

    /**
     * @param string $name
Sergei Morozov's avatar
Sergei Morozov committed
427
     * @param mixed  $value
Benjamin Morel's avatar
Benjamin Morel committed
428
     *
429
     * @return self
430 431 432 433
     */
    public function addOption($name, $value)
    {
        $this->_options[$name] = $value;
Benjamin Morel's avatar
Benjamin Morel committed
434

435 436 437 438
        return $this;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
439 440
     * @return void
     *
441
     * @throws SchemaException
442 443 444
     */
    protected function _addColumn(Column $column)
    {
445
        $columnName = $column->getName();
446
        $columnName = $this->normalizeIdentifier($columnName);
447

448
        if (isset($this->_columns[$columnName])) {
449
            throw SchemaException::columnAlreadyExists($this->getName(), $columnName);
450 451 452 453 454 455
        }

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

    /**
Benjamin Morel's avatar
Benjamin Morel committed
456
     * Adds an index to the table.
457
     *
458
     * @return self
Benjamin Morel's avatar
Benjamin Morel committed
459
     *
460
     * @throws SchemaException
461
     */
462
    protected function _addIndex(Index $indexCandidate)
463
    {
464 465
        $indexName               = $indexCandidate->getName();
        $indexName               = $this->normalizeIdentifier($indexName);
466
        $replacedImplicitIndexes = [];
467

468
        foreach ($this->implicitIndexes as $name => $implicitIndex) {
469 470
            if (! $implicitIndex->isFullfilledBy($indexCandidate) || ! isset($this->_indexes[$name])) {
                continue;
471
            }
472 473

            $replacedImplicitIndexes[] = $name;
474 475 476
        }

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

482 483 484 485
        foreach ($replacedImplicitIndexes as $name) {
            unset($this->_indexes[$name], $this->implicitIndexes[$name]);
        }

486
        if ($indexCandidate->isPrimary()) {
487 488 489
            $this->_primaryKeyName = $indexName;
        }

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

492 493 494 495
        return $this;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
496
     * @return void
497
     */
498
    protected function _addForeignKeyConstraint(ForeignKeyConstraint $constraint)
499
    {
500
        $constraint->setLocalTable($this);
501

Steve Müller's avatar
Steve Müller committed
502
        if (strlen($constraint->getName())) {
503 504 505
            $name = $constraint->getName();
        } else {
            $name = $this->_generateIdentifierName(
506 507 508
                array_merge((array) $this->getName(), $constraint->getLocalColumns()),
                'fk',
                $this->_getMaxIdentifierLength()
509 510
            );
        }
511
        $name = $this->normalizeIdentifier($name);
512 513

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

Pascal Borreli's avatar
Pascal Borreli committed
515
        // add an explicit index on the foreign key columns. If there is already an index that fulfils this requirements drop the request.
516
        // 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
517
        // lead to duplicates. This creates computation overhead in this case, however no duplicate indexes are ever added (based on columns).
518
        $indexName      = $this->_generateIdentifierName(
519
            array_merge([$this->getName()], $constraint->getColumns()),
520
            'idx',
521 522 523 524 525 526 527 528 529 530
            $this->_getMaxIdentifierLength()
        );
        $indexCandidate = $this->_createIndex($constraint->getColumns(), $indexName, false, false);

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

531 532
        $this->_addIndex($indexCandidate);
        $this->implicitIndexes[$this->normalizeIdentifier($indexName)] = $indexCandidate;
533 534 535
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
536 537 538 539
     * Returns whether this table has a foreign key constraint with the given name.
     *
     * @param string $constraintName
     *
540
     * @return bool
541 542 543
     */
    public function hasForeignKey($constraintName)
    {
544
        $constraintName = $this->normalizeIdentifier($constraintName);
Benjamin Morel's avatar
Benjamin Morel committed
545

546 547 548 549
        return isset($this->_fkConstraints[$constraintName]);
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
550 551 552 553
     * Returns the foreign key constraint with the given name.
     *
     * @param string $constraintName The constraint name.
     *
554
     * @return ForeignKeyConstraint
Benjamin Morel's avatar
Benjamin Morel committed
555
     *
556
     * @throws SchemaException If the foreign key does not exist.
557 558 559
     */
    public function getForeignKey($constraintName)
    {
560
        $constraintName = $this->normalizeIdentifier($constraintName);
561
        if (! $this->hasForeignKey($constraintName)) {
562
            throw SchemaException::foreignKeyDoesNotExist($constraintName, $this->_name);
563 564 565
        }

        return $this->_fkConstraints[$constraintName];
566 567
    }

Benjamin Morel's avatar
Benjamin Morel committed
568 569 570 571 572 573 574
    /**
     * Removes the foreign key constraint with the given name.
     *
     * @param string $constraintName The constraint name.
     *
     * @return void
     *
575
     * @throws SchemaException
Benjamin Morel's avatar
Benjamin Morel committed
576
     */
577 578
    public function removeForeignKey($constraintName)
    {
579
        $constraintName = $this->normalizeIdentifier($constraintName);
580
        if (! $this->hasForeignKey($constraintName)) {
581 582 583 584 585 586
            throw SchemaException::foreignKeyDoesNotExist($constraintName, $this->_name);
        }

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

587
    /**
588
     * Returns ordered list of columns (primary keys are first, then foreign keys, then the rest)
589
     *
590
     * @return Column[]
591 592 593
     */
    public function getColumns()
    {
Sergei Morozov's avatar
Sergei Morozov committed
594
        $primaryKey        = $this->getPrimaryKey();
595
        $primaryKeyColumns = [];
Sergei Morozov's avatar
Sergei Morozov committed
596 597 598

        if ($primaryKey !== null) {
            $primaryKeyColumns = $this->filterColumns($primaryKey->getColumns());
599
        }
600

601
        return array_merge($primaryKeyColumns, $this->getForeignKeyColumns(), $this->_columns);
602
    }
603

604 605
    /**
     * Returns foreign key columns
606
     *
607 608
     * @return Column[]
     */
609
    private function getForeignKeyColumns()
610
    {
611 612 613
        $foreignKeyColumns = [];
        foreach ($this->getForeignKeys() as $foreignKey) {
            $foreignKeyColumns = array_merge($foreignKeyColumns, $foreignKey->getColumns());
614
        }
615

616
        return $this->filterColumns($foreignKeyColumns);
617
    }
Benjamin Morel's avatar
Benjamin Morel committed
618

619
    /**
620
     * Returns only columns that have specified names
621
     *
622
     * @param string[] $columnNames
623
     *
624
     * @return Column[]
625
     */
626
    private function filterColumns(array $columnNames)
627
    {
628
        return array_filter($this->_columns, static function ($columnName) use ($columnNames) {
629 630
            return in_array($columnName, $columnNames, true);
        }, ARRAY_FILTER_USE_KEY);
631 632 633
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
634
     * Returns whether this table has a Column with the given name.
635
     *
Benjamin Morel's avatar
Benjamin Morel committed
636 637
     * @param string $columnName The column name.
     *
638
     * @return bool
639 640 641
     */
    public function hasColumn($columnName)
    {
642
        $columnName = $this->normalizeIdentifier($columnName);
Benjamin Morel's avatar
Benjamin Morel committed
643

644 645 646 647
        return isset($this->_columns[$columnName]);
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
648 649 650
     * Returns the Column with the given name.
     *
     * @param string $columnName The column name.
651
     *
652
     * @return Column
Benjamin Morel's avatar
Benjamin Morel committed
653
     *
654
     * @throws SchemaException If the column does not exist.
655 656 657
     */
    public function getColumn($columnName)
    {
658
        $columnName = $this->normalizeIdentifier($columnName);
659
        if (! $this->hasColumn($columnName)) {
660
            throw SchemaException::columnDoesNotExist($columnName, $this->_name);
661 662 663 664 665 666
        }

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

    /**
Benjamin Morel's avatar
Benjamin Morel committed
667 668
     * Returns the primary key.
     *
669
     * @return Index|null The primary key, or null if this Table has no primary key.
670 671 672
     */
    public function getPrimaryKey()
    {
673
        if (! $this->hasPrimaryKey()) {
674 675
            return null;
        }
Benjamin Morel's avatar
Benjamin Morel committed
676

677 678 679
        return $this->getIndex($this->_primaryKeyName);
    }

680 681 682
    /**
     * Returns the primary key columns.
     *
683
     * @return string[]
684 685 686 687 688
     *
     * @throws DBALException
     */
    public function getPrimaryKeyColumns()
    {
Sergei Morozov's avatar
Sergei Morozov committed
689 690 691
        $primaryKey = $this->getPrimaryKey();

        if ($primaryKey === null) {
692
            throw new DBALException('Table ' . $this->getName() . ' has no primary key.');
693
        }
Sergei Morozov's avatar
Sergei Morozov committed
694 695

        return $primaryKey->getColumns();
696 697
    }

698
    /**
Benjamin Morel's avatar
Benjamin Morel committed
699
     * Returns whether this table has a primary key.
700
     *
701
     * @return bool
702 703 704
     */
    public function hasPrimaryKey()
    {
705
        return $this->_primaryKeyName && $this->hasIndex($this->_primaryKeyName);
706 707
    }

708
    /**
Benjamin Morel's avatar
Benjamin Morel committed
709 710 711 712
     * Returns whether this table has an Index with the given name.
     *
     * @param string $indexName The index name.
     *
713
     * @return bool
714 715 716
     */
    public function hasIndex($indexName)
    {
717
        $indexName = $this->normalizeIdentifier($indexName);
Benjamin Morel's avatar
Benjamin Morel committed
718

719
        return isset($this->_indexes[$indexName]);
720 721 722
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
723 724 725 726
     * Returns the Index with the given name.
     *
     * @param string $indexName The index name.
     *
727
     * @return Index
Benjamin Morel's avatar
Benjamin Morel committed
728
     *
729
     * @throws SchemaException If the index does not exist.
730 731 732
     */
    public function getIndex($indexName)
    {
733
        $indexName = $this->normalizeIdentifier($indexName);
734
        if (! $this->hasIndex($indexName)) {
735
            throw SchemaException::indexDoesNotExist($indexName, $this->_name);
736
        }
Benjamin Morel's avatar
Benjamin Morel committed
737

738 739 740 741
        return $this->_indexes[$indexName];
    }

    /**
742
     * @return Index[]
743 744 745 746 747 748 749
     */
    public function getIndexes()
    {
        return $this->_indexes;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
750
     * Returns the foreign key constraints.
751
     *
752
     * @return ForeignKeyConstraint[]
753
     */
754
    public function getForeignKeys()
755
    {
756
        return $this->_fkConstraints;
757 758
    }

Benjamin Morel's avatar
Benjamin Morel committed
759 760 761
    /**
     * @param string $name
     *
762
     * @return bool
Benjamin Morel's avatar
Benjamin Morel committed
763
     */
764 765 766 767 768
    public function hasOption($name)
    {
        return isset($this->_options[$name]);
    }

Benjamin Morel's avatar
Benjamin Morel committed
769 770 771 772 773
    /**
     * @param string $name
     *
     * @return mixed
     */
774 775 776 777 778
    public function getOption($name)
    {
        return $this->_options[$name];
    }

Benjamin Morel's avatar
Benjamin Morel committed
779
    /**
780
     * @return mixed[]
Benjamin Morel's avatar
Benjamin Morel committed
781
     */
782 783 784 785 786
    public function getOptions()
    {
        return $this->_options;
    }

787
    /**
Benjamin Morel's avatar
Benjamin Morel committed
788
     * @return void
789 790 791 792 793
     */
    public function visit(Visitor $visitor)
    {
        $visitor->acceptTable($this);

794
        foreach ($this->getColumns() as $column) {
795
            $visitor->acceptColumn($this, $column);
796 797
        }

798
        foreach ($this->getIndexes() as $index) {
799 800 801
            $visitor->acceptIndex($this, $index);
        }

802
        foreach ($this->getForeignKeys() as $constraint) {
803
            $visitor->acceptForeignKey($this, $constraint);
804 805
        }
    }
806 807

    /**
Benjamin Morel's avatar
Benjamin Morel committed
808 809 810
     * Clone of a Table triggers a deep clone of all affected assets.
     *
     * @return void
811 812 813
     */
    public function __clone()
    {
814
        foreach ($this->_columns as $k => $column) {
815 816
            $this->_columns[$k] = clone $column;
        }
817
        foreach ($this->_indexes as $k => $index) {
818 819
            $this->_indexes[$k] = clone $index;
        }
820
        foreach ($this->_fkConstraints as $k => $fk) {
821 822 823 824
            $this->_fkConstraints[$k] = clone $fk;
            $this->_fkConstraints[$k]->setLocalTable($this);
        }
    }
825 826 827 828 829 830

    /**
     * Normalizes a given identifier.
     *
     * Trims quotes and lowercases the given identifier.
     *
Sergei Morozov's avatar
Sergei Morozov committed
831
     * @param string|null $identifier The identifier to normalize.
832 833 834 835 836
     *
     * @return string The normalized identifier.
     */
    private function normalizeIdentifier($identifier)
    {
Sergei Morozov's avatar
Sergei Morozov committed
837 838 839 840
        if ($identifier === null) {
            return '';
        }

841 842
        return $this->trimQuotes(strtolower($identifier));
    }
843 844 845 846 847 848 849 850 851 852 853 854 855

    public function setComment(?string $comment) : self
    {
        // For keeping backward compatibility with MySQL in previous releases, table comments are stored as options.
        $this->addOption('comment', $comment);

        return $this;
    }

    public function getComment() : ?string
    {
        return $this->_options['comment'] ?? null;
    }
856
}