Table.php 23.8 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|false */
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 108 109 110 111
        if ($indexName === false) {
            $indexName = 'primary';
        }

        $this->_addIndex($this->_createIndex($columnNames, $indexName, true, true));
112

113
        foreach ($columnNames as $columnName) {
114 115 116 117
            $column = $this->getColumn($columnName);
            $column->setNotnull(true);
        }

118
        return $this;
119 120 121
    }

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

139
        return $this->_addIndex($this->_createIndex($columnNames, $indexName, false, false, $flags, $options));
140 141
    }

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

153
        $this->dropIndex($this->_primaryKeyName);
154
        $this->_primaryKeyName = false;
155 156 157
    }

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

175
    /**
176
     * @param string[]    $columnNames
Benjamin Morel's avatar
Benjamin Morel committed
177
     * @param string|null $indexName
178
     * @param mixed[]     $options
179
     *
180
     * @return self
181
     */
182
    public function addUniqueIndex(array $columnNames, $indexName = null, array $options = [])
183
    {
184
        if ($indexName === null) {
185
            $indexName = $this->_generateIdentifierName(
186 187 188
                array_merge([$this->getName()], $columnNames),
                'uniq',
                $this->_getMaxIdentifierLength()
189
            );
190 191
        }

192
        return $this->_addIndex($this->_createIndex($columnNames, $indexName, true, false, [], $options));
193 194
    }

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

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

216
        if (! $this->hasIndex($oldIndexName)) {
217 218 219 220 221 222 223 224 225 226 227 228
            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
229
            return $this->setPrimaryKey($oldIndex->getColumns(), $newIndexName ?? false);
230 231 232 233 234
        }

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

        if ($oldIndex->isUnique()) {
235
            return $this->addUniqueIndex($oldIndex->getColumns(), $newIndexName, $oldIndex->getOptions());
236 237
        }

238
        return $this->addIndex($oldIndex->getColumns(), $newIndexName, $oldIndex->getFlags(), $oldIndex->getOptions());
239 240
    }

241
    /**
Benjamin Morel's avatar
Benjamin Morel committed
242 243
     * Checks if an index begins in the order of the given columns.
     *
244
     * @param string[] $columnNames
245
     *
246
     * @return bool
247
     */
248
    public function columnsAreIndexed(array $columnNames)
249
    {
250
        foreach ($this->getIndexes() as $index) {
251
            /** @var $index Index */
252
            if ($index->spansColumns($columnNames)) {
253 254 255
                return true;
            }
        }
Benjamin Morel's avatar
Benjamin Morel committed
256

257 258 259
        return false;
    }

260
    /**
261 262 263 264 265 266
     * @param string[] $columnNames
     * @param string   $indexName
     * @param bool     $isUnique
     * @param bool     $isPrimary
     * @param string[] $flags
     * @param mixed[]  $options
267
     *
268
     * @return Index
Benjamin Morel's avatar
Benjamin Morel committed
269
     *
270
     * @throws SchemaException
271
     */
272
    private function _createIndex(array $columnNames, $indexName, $isUnique, $isPrimary, array $flags = [], array $options = [])
273
    {
274
        if (preg_match('(([^a-zA-Z0-9_]+))', $this->normalizeIdentifier($indexName)) === 1) {
275 276 277
            throw SchemaException::indexNameInvalid($indexName);
        }

278
        foreach ($columnNames as $columnName) {
279
            if (! $this->hasColumn($columnName)) {
280
                throw SchemaException::columnDoesNotExist($columnName, $this->_name);
281 282
            }
        }
Benjamin Morel's avatar
Benjamin Morel committed
283

284
        return new Index($indexName, $columnNames, $isUnique, $isPrimary, $flags, $options);
285 286 287
    }

    /**
288 289 290
     * @param string  $columnName
     * @param string  $typeName
     * @param mixed[] $options
Benjamin Morel's avatar
Benjamin Morel committed
291
     *
292
     * @return Column
293
     */
294
    public function addColumn($columnName, $typeName, array $options = [])
295 296 297 298
    {
        $column = new Column($columnName, Type::getType($typeName), $options);

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

300
        return $column;
301 302 303
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
304
     * Renames a Column.
305
     *
306 307
     * @deprecated
     *
308 309
     * @param string $oldColumnName
     * @param string $newColumnName
Benjamin Morel's avatar
Benjamin Morel committed
310
     *
311 312
     * @return void
     *
313
     * @throws DBALException
314 315 316
     */
    public function renameColumn($oldColumnName, $newColumnName)
    {
317 318 319
        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.');
320 321 322
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
323
     * Change Column Details.
324
     *
325 326
     * @param string  $columnName
     * @param mixed[] $options
Benjamin Morel's avatar
Benjamin Morel committed
327
     *
328
     * @return self
329 330 331 332 333
     */
    public function changeColumn($columnName, array $options)
    {
        $column = $this->getColumn($columnName);
        $column->setOptions($options);
Benjamin Morel's avatar
Benjamin Morel committed
334

335 336 337 338
        return $this;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
339
     * Drops a Column from the Table.
340
     *
341
     * @param string $columnName
Benjamin Morel's avatar
Benjamin Morel committed
342
     *
343
     * @return self
344 345 346
     */
    public function dropColumn($columnName)
    {
347
        $columnName = $this->normalizeIdentifier($columnName);
348
        unset($this->_columns[$columnName]);
Benjamin Morel's avatar
Benjamin Morel committed
349

350 351 352 353
        return $this;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
354
     * Adds a foreign key constraint.
355
     *
Benjamin Morel's avatar
Benjamin Morel committed
356
     * Name is inferred from the local columns.
357
     *
358
     * @param Table|string $foreignTable       Table schema instance or table name
359 360 361
     * @param string[]     $localColumnNames
     * @param string[]     $foreignColumnNames
     * @param mixed[]      $options
362
     * @param string|null  $constraintName
Benjamin Morel's avatar
Benjamin Morel committed
363
     *
364
     * @return self
365
     */
366
    public function addForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options = [], $constraintName = null)
367
    {
368 369 370
        if ($constraintName === null) {
            $constraintName = $this->_generateIdentifierName(array_merge((array) $this->getName(), $localColumnNames), 'fk', $this->_getMaxIdentifierLength());
        }
Benjamin Morel's avatar
Benjamin Morel committed
371

372
        return $this->addNamedForeignKeyConstraint($constraintName, $foreignTable, $localColumnNames, $foreignColumnNames, $options);
373 374
    }

375
    /**
Benjamin Morel's avatar
Benjamin Morel committed
376
     * Adds a foreign key constraint.
377
     *
Pascal Borreli's avatar
Pascal Borreli committed
378
     * Name is to be generated by the database itself.
379
     *
380
     * @deprecated Use {@link addForeignKeyConstraint}
Benjamin Morel's avatar
Benjamin Morel committed
381
     *
382
     * @param Table|string $foreignTable       Table schema instance or table name
383 384 385
     * @param string[]     $localColumnNames
     * @param string[]     $foreignColumnNames
     * @param mixed[]      $options
Benjamin Morel's avatar
Benjamin Morel committed
386
     *
387
     * @return self
388
     */
389
    public function addUnnamedForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options = [])
390
    {
391
        return $this->addForeignKeyConstraint($foreignTable, $localColumnNames, $foreignColumnNames, $options);
392 393
    }

394
    /**
Benjamin Morel's avatar
Benjamin Morel committed
395
     * Adds a foreign key constraint with a given name.
396
     *
397
     * @deprecated Use {@link addForeignKeyConstraint}
Benjamin Morel's avatar
Benjamin Morel committed
398
     *
399
     * @param string       $name
400
     * @param Table|string $foreignTable       Table schema instance or table name
401 402 403
     * @param string[]     $localColumnNames
     * @param string[]     $foreignColumnNames
     * @param mixed[]      $options
Benjamin Morel's avatar
Benjamin Morel committed
404
     *
405
     * @return self
Benjamin Morel's avatar
Benjamin Morel committed
406
     *
407
     * @throws SchemaException
408
     */
409
    public function addNamedForeignKeyConstraint($name, $foreignTable, array $localColumnNames, array $foreignColumnNames, array $options = [])
410
    {
411
        if ($foreignTable instanceof Table) {
412
            foreach ($foreignColumnNames as $columnName) {
413
                if (! $foreignTable->hasColumn($columnName)) {
414
                    throw SchemaException::columnDoesNotExist($columnName, $foreignTable->getName());
415
                }
416 417
            }
        }
418

419
        foreach ($localColumnNames as $columnName) {
420
            if (! $this->hasColumn($columnName)) {
421
                throw SchemaException::columnDoesNotExist($columnName, $this->_name);
422 423
            }
        }
424

425
        $constraint = new ForeignKeyConstraint(
426 427 428 429 430
            $localColumnNames,
            $foreignTable,
            $foreignColumnNames,
            $name,
            $options
431
        );
432
        $this->_addForeignKeyConstraint($constraint);
433

434 435 436 437 438
        return $this;
    }

    /**
     * @param string $name
Sergei Morozov's avatar
Sergei Morozov committed
439
     * @param mixed  $value
Benjamin Morel's avatar
Benjamin Morel committed
440
     *
441
     * @return self
442 443 444 445
     */
    public function addOption($name, $value)
    {
        $this->_options[$name] = $value;
Benjamin Morel's avatar
Benjamin Morel committed
446

447 448 449 450
        return $this;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
451 452
     * @return void
     *
453
     * @throws SchemaException
454 455 456
     */
    protected function _addColumn(Column $column)
    {
457
        $columnName = $column->getName();
458
        $columnName = $this->normalizeIdentifier($columnName);
459

460
        if (isset($this->_columns[$columnName])) {
461
            throw SchemaException::columnAlreadyExists($this->getName(), $columnName);
462 463 464 465 466 467
        }

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

    /**
Benjamin Morel's avatar
Benjamin Morel committed
468
     * Adds an index to the table.
469
     *
470
     * @return self
Benjamin Morel's avatar
Benjamin Morel committed
471
     *
472
     * @throws SchemaException
473
     */
474
    protected function _addIndex(Index $indexCandidate)
475
    {
476 477
        $indexName               = $indexCandidate->getName();
        $indexName               = $this->normalizeIdentifier($indexName);
478
        $replacedImplicitIndexes = [];
479

480
        foreach ($this->implicitIndexes as $name => $implicitIndex) {
481 482
            if (! $implicitIndex->isFullfilledBy($indexCandidate) || ! isset($this->_indexes[$name])) {
                continue;
483
            }
484 485

            $replacedImplicitIndexes[] = $name;
486 487 488
        }

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

494 495 496 497
        foreach ($replacedImplicitIndexes as $name) {
            unset($this->_indexes[$name], $this->implicitIndexes[$name]);
        }

498
        if ($indexCandidate->isPrimary()) {
499 500 501
            $this->_primaryKeyName = $indexName;
        }

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

504 505 506 507
        return $this;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
508
     * @return void
509
     */
510
    protected function _addForeignKeyConstraint(ForeignKeyConstraint $constraint)
511
    {
512
        $constraint->setLocalTable($this);
513

514
        if (strlen($constraint->getName()) > 0) {
515 516 517
            $name = $constraint->getName();
        } else {
            $name = $this->_generateIdentifierName(
518 519 520
                array_merge((array) $this->getName(), $constraint->getLocalColumns()),
                'fk',
                $this->_getMaxIdentifierLength()
521 522
            );
        }
523
        $name = $this->normalizeIdentifier($name);
524 525

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

Pascal Borreli's avatar
Pascal Borreli committed
527
        // add an explicit index on the foreign key columns. If there is already an index that fulfils this requirements drop the request.
528
        // 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
529
        // lead to duplicates. This creates computation overhead in this case, however no duplicate indexes are ever added (based on columns).
530
        $indexName      = $this->_generateIdentifierName(
531
            array_merge([$this->getName()], $constraint->getColumns()),
532
            'idx',
533 534 535 536 537 538 539 540 541 542
            $this->_getMaxIdentifierLength()
        );
        $indexCandidate = $this->_createIndex($constraint->getColumns(), $indexName, false, false);

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

543 544
        $this->_addIndex($indexCandidate);
        $this->implicitIndexes[$this->normalizeIdentifier($indexName)] = $indexCandidate;
545 546 547
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
548 549 550 551
     * Returns whether this table has a foreign key constraint with the given name.
     *
     * @param string $constraintName
     *
552
     * @return bool
553 554 555
     */
    public function hasForeignKey($constraintName)
    {
556
        $constraintName = $this->normalizeIdentifier($constraintName);
Benjamin Morel's avatar
Benjamin Morel committed
557

558 559 560 561
        return isset($this->_fkConstraints[$constraintName]);
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
562 563 564 565
     * Returns the foreign key constraint with the given name.
     *
     * @param string $constraintName The constraint name.
     *
566
     * @return ForeignKeyConstraint
Benjamin Morel's avatar
Benjamin Morel committed
567
     *
568
     * @throws SchemaException If the foreign key does not exist.
569 570 571
     */
    public function getForeignKey($constraintName)
    {
572
        $constraintName = $this->normalizeIdentifier($constraintName);
573
        if (! $this->hasForeignKey($constraintName)) {
574
            throw SchemaException::foreignKeyDoesNotExist($constraintName, $this->_name);
575 576 577
        }

        return $this->_fkConstraints[$constraintName];
578 579
    }

Benjamin Morel's avatar
Benjamin Morel committed
580 581 582 583 584 585 586
    /**
     * Removes the foreign key constraint with the given name.
     *
     * @param string $constraintName The constraint name.
     *
     * @return void
     *
587
     * @throws SchemaException
Benjamin Morel's avatar
Benjamin Morel committed
588
     */
589 590
    public function removeForeignKey($constraintName)
    {
591
        $constraintName = $this->normalizeIdentifier($constraintName);
592
        if (! $this->hasForeignKey($constraintName)) {
593 594 595 596 597 598
            throw SchemaException::foreignKeyDoesNotExist($constraintName, $this->_name);
        }

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

599
    /**
600
     * Returns ordered list of columns (primary keys are first, then foreign keys, then the rest)
601
     *
602
     * @return Column[]
603 604 605
     */
    public function getColumns()
    {
Sergei Morozov's avatar
Sergei Morozov committed
606
        $primaryKey        = $this->getPrimaryKey();
607
        $primaryKeyColumns = [];
Sergei Morozov's avatar
Sergei Morozov committed
608 609 610

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

613
        return array_merge($primaryKeyColumns, $this->getForeignKeyColumns(), $this->_columns);
614
    }
615

616 617
    /**
     * Returns foreign key columns
618
     *
619 620
     * @return Column[]
     */
621
    private function getForeignKeyColumns()
622
    {
623 624 625
        $foreignKeyColumns = [];
        foreach ($this->getForeignKeys() as $foreignKey) {
            $foreignKeyColumns = array_merge($foreignKeyColumns, $foreignKey->getColumns());
626
        }
627

628
        return $this->filterColumns($foreignKeyColumns);
629
    }
Benjamin Morel's avatar
Benjamin Morel committed
630

631
    /**
632
     * Returns only columns that have specified names
633
     *
634
     * @param string[] $columnNames
635
     *
636
     * @return Column[]
637
     */
638
    private function filterColumns(array $columnNames)
639
    {
640
        return array_filter($this->_columns, static function ($columnName) use ($columnNames) : bool {
641 642
            return in_array($columnName, $columnNames, true);
        }, ARRAY_FILTER_USE_KEY);
643 644 645
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
646
     * Returns whether this table has a Column with the given name.
647
     *
Benjamin Morel's avatar
Benjamin Morel committed
648 649
     * @param string $columnName The column name.
     *
650
     * @return bool
651 652 653
     */
    public function hasColumn($columnName)
    {
654
        $columnName = $this->normalizeIdentifier($columnName);
Benjamin Morel's avatar
Benjamin Morel committed
655

656 657 658 659
        return isset($this->_columns[$columnName]);
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
660 661 662
     * Returns the Column with the given name.
     *
     * @param string $columnName The column name.
663
     *
664
     * @return Column
Benjamin Morel's avatar
Benjamin Morel committed
665
     *
666
     * @throws SchemaException If the column does not exist.
667 668 669
     */
    public function getColumn($columnName)
    {
670
        $columnName = $this->normalizeIdentifier($columnName);
671
        if (! $this->hasColumn($columnName)) {
672
            throw SchemaException::columnDoesNotExist($columnName, $this->_name);
673 674 675 676 677 678
        }

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

    /**
Benjamin Morel's avatar
Benjamin Morel committed
679 680
     * Returns the primary key.
     *
681
     * @return Index|null The primary key, or null if this Table has no primary key.
682 683 684
     */
    public function getPrimaryKey()
    {
685 686
        if ($this->_primaryKeyName !== false) {
            return $this->getIndex($this->_primaryKeyName);
687
        }
Benjamin Morel's avatar
Benjamin Morel committed
688

689
        return null;
690 691
    }

692 693 694
    /**
     * Returns the primary key columns.
     *
695
     * @return string[]
696 697 698 699 700
     *
     * @throws DBALException
     */
    public function getPrimaryKeyColumns()
    {
Sergei Morozov's avatar
Sergei Morozov committed
701 702 703
        $primaryKey = $this->getPrimaryKey();

        if ($primaryKey === null) {
704
            throw new DBALException('Table ' . $this->getName() . ' has no primary key.');
705
        }
Sergei Morozov's avatar
Sergei Morozov committed
706 707

        return $primaryKey->getColumns();
708 709
    }

710
    /**
Benjamin Morel's avatar
Benjamin Morel committed
711
     * Returns whether this table has a primary key.
712
     *
713
     * @return bool
714 715 716
     */
    public function hasPrimaryKey()
    {
717
        return $this->_primaryKeyName !== false && $this->hasIndex($this->_primaryKeyName);
718 719
    }

720
    /**
Benjamin Morel's avatar
Benjamin Morel committed
721 722 723 724
     * Returns whether this table has an Index with the given name.
     *
     * @param string $indexName The index name.
     *
725
     * @return bool
726 727 728
     */
    public function hasIndex($indexName)
    {
729
        $indexName = $this->normalizeIdentifier($indexName);
Benjamin Morel's avatar
Benjamin Morel committed
730

731
        return isset($this->_indexes[$indexName]);
732 733 734
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
735 736 737 738
     * Returns the Index with the given name.
     *
     * @param string $indexName The index name.
     *
739
     * @return Index
Benjamin Morel's avatar
Benjamin Morel committed
740
     *
741
     * @throws SchemaException If the index does not exist.
742 743 744
     */
    public function getIndex($indexName)
    {
745
        $indexName = $this->normalizeIdentifier($indexName);
746
        if (! $this->hasIndex($indexName)) {
747
            throw SchemaException::indexDoesNotExist($indexName, $this->_name);
748
        }
Benjamin Morel's avatar
Benjamin Morel committed
749

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

    /**
754
     * @return Index[]
755 756 757 758 759 760 761
     */
    public function getIndexes()
    {
        return $this->_indexes;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
762
     * Returns the foreign key constraints.
763
     *
764
     * @return ForeignKeyConstraint[]
765
     */
766
    public function getForeignKeys()
767
    {
768
        return $this->_fkConstraints;
769 770
    }

Benjamin Morel's avatar
Benjamin Morel committed
771 772 773
    /**
     * @param string $name
     *
774
     * @return bool
Benjamin Morel's avatar
Benjamin Morel committed
775
     */
776 777 778 779 780
    public function hasOption($name)
    {
        return isset($this->_options[$name]);
    }

Benjamin Morel's avatar
Benjamin Morel committed
781 782 783 784 785
    /**
     * @param string $name
     *
     * @return mixed
     */
786 787 788 789 790
    public function getOption($name)
    {
        return $this->_options[$name];
    }

Benjamin Morel's avatar
Benjamin Morel committed
791
    /**
792
     * @return mixed[]
Benjamin Morel's avatar
Benjamin Morel committed
793
     */
794 795 796 797 798
    public function getOptions()
    {
        return $this->_options;
    }

799
    /**
Benjamin Morel's avatar
Benjamin Morel committed
800
     * @return void
801 802 803 804 805
     */
    public function visit(Visitor $visitor)
    {
        $visitor->acceptTable($this);

806
        foreach ($this->getColumns() as $column) {
807
            $visitor->acceptColumn($this, $column);
808 809
        }

810
        foreach ($this->getIndexes() as $index) {
811 812 813
            $visitor->acceptIndex($this, $index);
        }

814
        foreach ($this->getForeignKeys() as $constraint) {
815
            $visitor->acceptForeignKey($this, $constraint);
816 817
        }
    }
818 819

    /**
Benjamin Morel's avatar
Benjamin Morel committed
820 821 822
     * Clone of a Table triggers a deep clone of all affected assets.
     *
     * @return void
823 824 825
     */
    public function __clone()
    {
826
        foreach ($this->_columns as $k => $column) {
827 828
            $this->_columns[$k] = clone $column;
        }
829
        foreach ($this->_indexes as $k => $index) {
830 831
            $this->_indexes[$k] = clone $index;
        }
832
        foreach ($this->_fkConstraints as $k => $fk) {
833 834 835 836
            $this->_fkConstraints[$k] = clone $fk;
            $this->_fkConstraints[$k]->setLocalTable($this);
        }
    }
837 838 839 840 841 842

    /**
     * Normalizes a given identifier.
     *
     * Trims quotes and lowercases the given identifier.
     *
Sergei Morozov's avatar
Sergei Morozov committed
843
     * @param string|null $identifier The identifier to normalize.
844 845 846 847 848
     *
     * @return string The normalized identifier.
     */
    private function normalizeIdentifier($identifier)
    {
Sergei Morozov's avatar
Sergei Morozov committed
849 850 851 852
        if ($identifier === null) {
            return '';
        }

853 854
        return $this->trimQuotes(strtolower($identifier));
    }
855 856 857 858 859 860 861 862 863 864 865 866 867

    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;
    }
868
}