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 function array_filter;
use function array_merge;
use function in_array;
use function preg_match;
use function strlen;
use function strtolower;
15

Grégoire Paris's avatar
Grégoire Paris committed
16
use const ARRAY_FILTER_USE_KEY;
17 18

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

26
    /** @var Index[] */
27
    private $implicitIndexes = [];
28

29
    /** @var Index[] */
30
    protected $_indexes = [];
31

32
    /** @var string */
33 34
    protected $_primaryKeyName = false;

35
    /** @var ForeignKeyConstraint[] */
36
    protected $_fkConstraints = [];
37

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

43
    /** @var SchemaConfig|null */
44 45
    protected $_schemaConfig = null;

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

62
        $this->_setName($tableName);
63

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

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

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

76
        $this->_options = array_merge($this->_options, $options);
77 78
    }

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

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

        return 63;
97 98
    }

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

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

116
        return $this;
117 118 119
    }

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

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

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

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

167 168 169
        unset($this->_indexes[$indexName]);
    }

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

187
        return $this->_addIndex($this->_createIndex($columnNames, $indexName, true, false, [], $options));
188 189
    }

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

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

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

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

        if ($oldIndex->isUnique()) {
230
            return $this->addUniqueIndex($oldIndex->getColumns(), $newIndexName, $oldIndex->getOptions());
231 232
        }

233
        return $this->addIndex($oldIndex->getColumns(), $newIndexName, $oldIndex->getFlags(), $oldIndex->getOptions());
234 235
    }

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

251 252 253
        return false;
    }

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

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

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

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

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

294
        return $column;
295 296 297
    }

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

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

329 330 331 332
        return $this;
    }

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

344 345 346 347
        return $this;
    }

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

364
        return $this->addNamedForeignKeyConstraint($constraintName, $foreignTable, $localColumnNames, $foreignColumnNames, $options);
365 366
    }

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

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

411
        foreach ($localColumnNames as $columnName) {
412
            if (! $this->hasColumn($columnName)) {
413
                throw SchemaException::columnDoesNotExist($columnName, $this->_name);
414 415
            }
        }
416

417
        $constraint = new ForeignKeyConstraint(
418 419 420 421 422
            $localColumnNames,
            $foreignTable,
            $foreignColumnNames,
            $name,
            $options
423
        );
424
        $this->_addForeignKeyConstraint($constraint);
425

426 427 428 429 430
        return $this;
    }

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

439 440 441 442
        return $this;
    }

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

452
        if (isset($this->_columns[$columnName])) {
453
            throw SchemaException::columnAlreadyExists($this->getName(), $columnName);
454 455 456 457 458 459
        }

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

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

472
        foreach ($this->implicitIndexes as $name => $implicitIndex) {
473 474
            if (! $implicitIndex->isFullfilledBy($indexCandidate) || ! isset($this->_indexes[$name])) {
                continue;
475
            }
476 477

            $replacedImplicitIndexes[] = $name;
478 479
        }

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

487 488 489 490
        foreach ($replacedImplicitIndexes as $name) {
            unset($this->_indexes[$name], $this->implicitIndexes[$name]);
        }

491
        if ($indexCandidate->isPrimary()) {
492 493 494
            $this->_primaryKeyName = $indexName;
        }

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

497 498 499 500
        return $this;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
501
     * @return void
502
     */
503
    protected function _addForeignKeyConstraint(ForeignKeyConstraint $constraint)
504
    {
505
        $constraint->setLocalTable($this);
506

Steve Müller's avatar
Steve Müller committed
507
        if (strlen($constraint->getName())) {
508 509 510
            $name = $constraint->getName();
        } else {
            $name = $this->_generateIdentifierName(
511 512 513
                array_merge((array) $this->getName(), $constraint->getLocalColumns()),
                'fk',
                $this->_getMaxIdentifierLength()
514 515
            );
        }
Grégoire Paris's avatar
Grégoire Paris committed
516

517
        $name = $this->normalizeIdentifier($name);
518 519

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

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

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

537 538
        $this->_addIndex($indexCandidate);
        $this->implicitIndexes[$this->normalizeIdentifier($indexName)] = $indexCandidate;
539 540 541
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
542 543 544 545
     * Returns whether this table has a foreign key constraint with the given name.
     *
     * @param string $constraintName
     *
546
     * @return bool
547 548 549
     */
    public function hasForeignKey($constraintName)
    {
550
        $constraintName = $this->normalizeIdentifier($constraintName);
Benjamin Morel's avatar
Benjamin Morel committed
551

552 553 554 555
        return isset($this->_fkConstraints[$constraintName]);
    }

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

        return $this->_fkConstraints[$constraintName];
572 573
    }

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

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

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

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

607
        return array_merge($primaryKeyColumns, $this->getForeignKeyColumns(), $this->_columns);
608
    }
609

610 611
    /**
     * Returns foreign key columns
612
     *
613 614
     * @return Column[]
     */
615
    private function getForeignKeyColumns()
616
    {
617 618 619
        $foreignKeyColumns = [];
        foreach ($this->getForeignKeys() as $foreignKey) {
            $foreignKeyColumns = array_merge($foreignKeyColumns, $foreignKey->getColumns());
620
        }
621

622
        return $this->filterColumns($foreignKeyColumns);
623
    }
Benjamin Morel's avatar
Benjamin Morel committed
624

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

    /**
Benjamin Morel's avatar
Benjamin Morel committed
640
     * Returns whether this table has a Column with the given name.
641
     *
Benjamin Morel's avatar
Benjamin Morel committed
642 643
     * @param string $columnName The column name.
     *
644
     * @return bool
645 646 647
     */
    public function hasColumn($columnName)
    {
648
        $columnName = $this->normalizeIdentifier($columnName);
Benjamin Morel's avatar
Benjamin Morel committed
649

650 651 652 653
        return isset($this->_columns[$columnName]);
    }

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

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

    /**
Benjamin Morel's avatar
Benjamin Morel committed
673 674
     * Returns the primary key.
     *
675
     * @return Index|null The primary key, or null if this Table has no primary key.
676 677 678
     */
    public function getPrimaryKey()
    {
679
        if (! $this->hasPrimaryKey()) {
680 681
            return null;
        }
Benjamin Morel's avatar
Benjamin Morel committed
682

683 684 685
        return $this->getIndex($this->_primaryKeyName);
    }

686 687 688
    /**
     * Returns the primary key columns.
     *
689
     * @return string[]
690 691 692 693 694
     *
     * @throws DBALException
     */
    public function getPrimaryKeyColumns()
    {
Sergei Morozov's avatar
Sergei Morozov committed
695 696 697
        $primaryKey = $this->getPrimaryKey();

        if ($primaryKey === null) {
698
            throw new DBALException('Table ' . $this->getName() . ' has no primary key.');
699
        }
Sergei Morozov's avatar
Sergei Morozov committed
700 701

        return $primaryKey->getColumns();
702 703
    }

704
    /**
Benjamin Morel's avatar
Benjamin Morel committed
705
     * Returns whether this table has a primary key.
706
     *
707
     * @return bool
708 709 710
     */
    public function hasPrimaryKey()
    {
711
        return $this->_primaryKeyName && $this->hasIndex($this->_primaryKeyName);
712 713
    }

714
    /**
Benjamin Morel's avatar
Benjamin Morel committed
715 716 717 718
     * Returns whether this table has an Index with the given name.
     *
     * @param string $indexName The index name.
     *
719
     * @return bool
720 721 722
     */
    public function hasIndex($indexName)
    {
723
        $indexName = $this->normalizeIdentifier($indexName);
Benjamin Morel's avatar
Benjamin Morel committed
724

725
        return isset($this->_indexes[$indexName]);
726 727 728
    }

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

744 745 746 747
        return $this->_indexes[$indexName];
    }

    /**
748
     * @return Index[]
749 750 751 752 753 754 755
     */
    public function getIndexes()
    {
        return $this->_indexes;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
756
     * Returns the foreign key constraints.
757
     *
758
     * @return ForeignKeyConstraint[]
759
     */
760
    public function getForeignKeys()
761
    {
762
        return $this->_fkConstraints;
763 764
    }

Benjamin Morel's avatar
Benjamin Morel committed
765 766 767
    /**
     * @param string $name
     *
768
     * @return bool
Benjamin Morel's avatar
Benjamin Morel committed
769
     */
770 771 772 773 774
    public function hasOption($name)
    {
        return isset($this->_options[$name]);
    }

Benjamin Morel's avatar
Benjamin Morel committed
775 776 777 778 779
    /**
     * @param string $name
     *
     * @return mixed
     */
780 781 782 783 784
    public function getOption($name)
    {
        return $this->_options[$name];
    }

Benjamin Morel's avatar
Benjamin Morel committed
785
    /**
786
     * @return mixed[]
Benjamin Morel's avatar
Benjamin Morel committed
787
     */
788 789 790 791 792
    public function getOptions()
    {
        return $this->_options;
    }

793
    /**
Benjamin Morel's avatar
Benjamin Morel committed
794
     * @return void
795 796 797 798 799
     */
    public function visit(Visitor $visitor)
    {
        $visitor->acceptTable($this);

800
        foreach ($this->getColumns() as $column) {
801
            $visitor->acceptColumn($this, $column);
802 803
        }

804
        foreach ($this->getIndexes() as $index) {
805 806 807
            $visitor->acceptIndex($this, $index);
        }

808
        foreach ($this->getForeignKeys() as $constraint) {
809
            $visitor->acceptForeignKey($this, $constraint);
810 811
        }
    }
812 813

    /**
Benjamin Morel's avatar
Benjamin Morel committed
814 815 816
     * Clone of a Table triggers a deep clone of all affected assets.
     *
     * @return void
817 818 819
     */
    public function __clone()
    {
820
        foreach ($this->_columns as $k => $column) {
821 822
            $this->_columns[$k] = clone $column;
        }
Grégoire Paris's avatar
Grégoire Paris committed
823

824
        foreach ($this->_indexes as $k => $index) {
825 826
            $this->_indexes[$k] = clone $index;
        }
Grégoire Paris's avatar
Grégoire Paris committed
827

828
        foreach ($this->_fkConstraints as $k => $fk) {
829 830 831 832
            $this->_fkConstraints[$k] = clone $fk;
            $this->_fkConstraints[$k]->setLocalTable($this);
        }
    }
833 834 835 836 837 838

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

849 850
        return $this->trimQuotes(strtolower($identifier));
    }
851

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

        return $this;
    }

860
    public function getComment(): ?string
861 862 863
    {
        return $this->_options['comment'] ?? null;
    }
864
}