Comparator.php 19.2 KB
Newer Older
1 2 3 4
<?php

namespace Doctrine\DBAL\Schema;

5
use Doctrine\DBAL\Types;
6

7 8 9 10 11 12 13
use function array_intersect_key;
use function array_key_exists;
use function array_keys;
use function array_map;
use function array_merge;
use function array_shift;
use function array_unique;
Sergei Morozov's avatar
Sergei Morozov committed
14
use function assert;
15
use function count;
16
use function get_class;
17
use function strtolower;
18

19
/**
Benjamin Morel's avatar
Benjamin Morel committed
20
 * Compares two Schemas and return an instance of SchemaDiff.
21 22 23 24
 */
class Comparator
{
    /**
25
     * @return SchemaDiff
26
     */
27
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema)
28 29
    {
        $c = new self();
Benjamin Morel's avatar
Benjamin Morel committed
30

31 32 33 34 35 36
        return $c->compare($fromSchema, $toSchema);
    }

    /**
     * Returns a SchemaDiff object containing the differences between the schemas $fromSchema and $toSchema.
     *
37
     * The returned differences are returned in such a way that they contain the
38 39 40
     * operations to change the schema stored in $fromSchema to the schema that is
     * stored in $toSchema.
     *
41
     * @return SchemaDiff
42
     */
43
    public function compare(Schema $fromSchema, Schema $toSchema)
44
    {
45
        $diff             = new SchemaDiff();
46
        $diff->fromSchema = $fromSchema;
47

48
        $foreignKeysToTable = [];
49

50
        foreach ($toSchema->getNamespaces() as $namespace) {
51 52
            if ($fromSchema->hasNamespace($namespace)) {
                continue;
Marco Pivetta's avatar
Marco Pivetta committed
53
            }
54 55

            $diff->newNamespaces[$namespace] = $namespace;
56 57 58
        }

        foreach ($fromSchema->getNamespaces() as $namespace) {
59 60
            if ($toSchema->hasNamespace($namespace)) {
                continue;
61
            }
62 63

            $diff->removedNamespaces[$namespace] = $namespace;
64
        }
Marco Pivetta's avatar
Marco Pivetta committed
65

66
        foreach ($toSchema->getTables() as $table) {
67
            $tableName = $table->getShortestName($toSchema->getName());
68
            if (! $fromSchema->hasTable($tableName)) {
69
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
70
            } else {
71 72
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
                if ($tableDifferences !== false) {
73 74 75 76 77 78
                    $diff->changedTables[$tableName] = $tableDifferences;
                }
            }
        }

        /* Check if there are tables removed */
79
        foreach ($fromSchema->getTables() as $table) {
80 81 82
            $tableName = $table->getShortestName($fromSchema->getName());

            $table = $fromSchema->getTable($tableName);
83
            if (! $toSchema->hasTable($tableName)) {
84 85
                $diff->removedTables[$tableName] = $table;
            }
86 87

            // also remember all foreign keys that point to a specific table
88
            foreach ($table->getForeignKeys() as $foreignKey) {
89
                $foreignTable = strtolower($foreignKey->getForeignTableName());
90
                if (! isset($foreignKeysToTable[$foreignTable])) {
91
                    $foreignKeysToTable[$foreignTable] = [];
92
                }
Grégoire Paris's avatar
Grégoire Paris committed
93

94 95 96 97
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
            }
        }

98
        foreach ($diff->removedTables as $tableName => $table) {
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
            if (! isset($foreignKeysToTable[$tableName])) {
                continue;
            }

            $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);

            // deleting duplicated foreign keys present on both on the orphanedForeignKey
            // and the removedForeignKeys from changedTables
            foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
                // strtolower the table name to make if compatible with getShortestName
                $localTableName = strtolower($foreignKey->getLocalTableName());
                if (! isset($diff->changedTables[$localTableName])) {
                    continue;
                }

                foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
Sergei Morozov's avatar
Sergei Morozov committed
115 116
                    assert($removedForeignKey instanceof ForeignKeyConstraint);

117 118 119
                    // We check if the key is from the removed table if not we skip.
                    if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
                        continue;
120
                    }
Grégoire Paris's avatar
Grégoire Paris committed
121

122
                    unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
123
                }
124
            }
125 126
        }

127
        foreach ($toSchema->getSequences() as $sequence) {
128
            $sequenceName = $sequence->getShortestName($toSchema->getName());
129 130
            if (! $fromSchema->hasSequence($sequenceName)) {
                if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
131 132
                    $diff->newSequences[] = $sequence;
                }
133 134
            } else {
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
135
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
136 137 138 139
                }
            }
        }

140
        foreach ($fromSchema->getSequences() as $sequence) {
141 142 143 144
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
                continue;
            }

145
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
146

147 148
            if ($toSchema->hasSequence($sequenceName)) {
                continue;
149
            }
150 151

            $diff->removedSequences[] = $sequence;
152
        }
153 154 155 156

        return $diff;
    }

Benjamin Morel's avatar
Benjamin Morel committed
157
    /**
158 159
     * @param Schema   $schema
     * @param Sequence $sequence
Benjamin Morel's avatar
Benjamin Morel committed
160
     *
161
     * @return bool
Benjamin Morel's avatar
Benjamin Morel committed
162
     */
163 164 165 166 167 168 169 170 171 172 173
    private function isAutoIncrementSequenceInSchema($schema, $sequence)
    {
        foreach ($schema->getTables() as $table) {
            if ($sequence->isAutoIncrementsFor($table)) {
                return true;
            }
        }

        return false;
    }

174
    /**
175
     * @return bool
176
     */
177
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
178
    {
179
        if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
180 181 182
            return true;
        }

Gabriel Caruso's avatar
Gabriel Caruso committed
183
        return $sequence1->getInitialValue() !== $sequence2->getInitialValue();
184 185
    }

186 187 188 189 190
    /**
     * Returns the difference between the tables $table1 and $table2.
     *
     * If there are no differences this method returns the boolean false.
     *
191
     * @return TableDiff|false
192
     */
193
    public function diffTable(Table $table1, Table $table2)
194
    {
195 196
        $changes                     = 0;
        $tableDifferences            = new TableDiff($table1->getName());
197
        $tableDifferences->fromTable = $table1;
198

199 200 201
        $table1Columns = $table1->getColumns();
        $table2Columns = $table2->getColumns();

Steve Müller's avatar
Steve Müller committed
202
        /* See if all the fields in table 1 exist in table 2 */
203
        foreach ($table2Columns as $columnName => $column) {
204 205
            if ($table1->hasColumn($columnName)) {
                continue;
206
            }
207 208 209

            $tableDifferences->addedColumns[$columnName] = $column;
            $changes++;
210
        }
Grégoire Paris's avatar
Grégoire Paris committed
211

212
        /* See if there are any removed fields in table 2 */
213 214
        foreach ($table1Columns as $columnName => $column) {
            // See if column is removed in table 2.
215
            if (! $table2->hasColumn($columnName)) {
216
                $tableDifferences->removedColumns[$columnName] = $column;
217
                $changes++;
218
                continue;
219
            }
220

221 222 223
            // See if column has changed properties in table 2.
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));

224
            if (count($changedProperties) === 0) {
225
                continue;
226
            }
227 228 229 230 231

            $columnDiff                                           = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
            $columnDiff->fromColumn                               = $column;
            $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
            $changes++;
232 233
        }

234
        $this->detectColumnRenamings($tableDifferences);
235

236 237 238
        $table1Indexes = $table1->getIndexes();
        $table2Indexes = $table2->getIndexes();

239 240 241 242
        /* See if all the indexes in table 1 exist in table 2 */
        foreach ($table2Indexes as $indexName => $index) {
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
                continue;
243
            }
244

245
            $tableDifferences->addedIndexes[$indexName] = $index;
246
            $changes++;
247
        }
Grégoire Paris's avatar
Grégoire Paris committed
248

249 250 251
        /* See if there are any removed indexes in table 2 */
        foreach ($table1Indexes as $indexName => $index) {
            // See if index is removed in table 2.
252 253
            if (
                ($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
254 255 256 257 258 259
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
            ) {
                $tableDifferences->removedIndexes[$indexName] = $index;
                $changes++;
                continue;
            }
260

261 262
            // See if index has changed in table 2.
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
Sergei Morozov's avatar
Sergei Morozov committed
263
            assert($table2Index instanceof Index);
264

265 266
            if (! $this->diffIndex($index, $table2Index)) {
                continue;
267
            }
268 269 270

            $tableDifferences->changedIndexes[$indexName] = $table2Index;
            $changes++;
271 272
        }

273 274
        $this->detectIndexRenamings($tableDifferences);

275
        $fromFkeys = $table1->getForeignKeys();
276
        $toFkeys   = $table2->getForeignKeys();
277

278 279
        foreach ($fromFkeys as $key1 => $constraint1) {
            foreach ($toFkeys as $key2 => $constraint2) {
Steve Müller's avatar
Steve Müller committed
280
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
281
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
282
                } else {
283
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
284 285
                        $tableDifferences->changedForeignKeys[] = $constraint2;
                        $changes++;
286
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
287
                    }
288 289 290 291
                }
            }
        }

Benjamin Morel's avatar
Benjamin Morel committed
292
        foreach ($fromFkeys as $constraint1) {
293 294 295 296
            $tableDifferences->removedForeignKeys[] = $constraint1;
            $changes++;
        }

Benjamin Morel's avatar
Benjamin Morel committed
297
        foreach ($toFkeys as $constraint2) {
298 299
            $tableDifferences->addedForeignKeys[] = $constraint2;
            $changes++;
300
        }
301

302
        return $changes > 0 ? $tableDifferences : false;
303 304
    }

305 306
    /**
     * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
307
     * however ambiguities between different possibilities should not lead to renaming at all.
308
     *
Benjamin Morel's avatar
Benjamin Morel committed
309
     * @return void
310 311 312
     */
    private function detectColumnRenamings(TableDiff $tableDifferences)
    {
313
        $renameCandidates = [];
314
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
Benjamin Morel's avatar
Benjamin Morel committed
315
            foreach ($tableDifferences->removedColumns as $removedColumn) {
316 317
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
                    continue;
318
                }
319 320

                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
321 322 323
            }
        }

324
        foreach ($renameCandidates as $candidateColumns) {
325 326
            if (count($candidateColumns) !== 1) {
                continue;
327
            }
328 329 330 331 332 333 334 335 336 337 338 339 340 341

            [$removedColumn, $addedColumn] = $candidateColumns[0];
            $removedColumnName             = strtolower($removedColumn->getName());
            $addedColumnName               = strtolower($addedColumn->getName());

            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
                continue;
            }

            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
            unset(
                $tableDifferences->addedColumns[$addedColumnName],
                $tableDifferences->removedColumns[$removedColumnName]
            );
342 343 344
        }
    }

345 346 347 348 349 350 351 352
    /**
     * Try to find indexes that only changed their name, rename operations maybe cheaper than add/drop
     * however ambiguities between different possibilities should not lead to renaming at all.
     *
     * @return void
     */
    private function detectIndexRenamings(TableDiff $tableDifferences)
    {
353
        $renameCandidates = [];
354 355 356 357

        // Gather possible rename candidates by comparing each added and removed index based on semantics.
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
358 359
                if ($this->diffIndex($addedIndex, $removedIndex)) {
                    continue;
360
                }
361 362

                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
363 364 365 366 367 368 369 370
            }
        }

        foreach ($renameCandidates as $candidateIndexes) {
            // If the current rename candidate contains exactly one semantically equal index,
            // we can safely rename it.
            // Otherwise it is unclear if a rename action is really intended,
            // therefore we let those ambiguous indexes be added/dropped.
371 372 373 374 375 376 377 378 379 380 381
            if (count($candidateIndexes) !== 1) {
                continue;
            }

            [$removedIndex, $addedIndex] = $candidateIndexes[0];

            $removedIndexName = strtolower($removedIndex->getName());
            $addedIndexName   = strtolower($addedIndex->getName());

            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
                continue;
382
            }
383 384 385 386 387 388

            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
            unset(
                $tableDifferences->addedIndexes[$addedIndexName],
                $tableDifferences->removedIndexes[$removedIndexName]
            );
389 390 391
        }
    }

392
    /**
393
     * @return bool
394
     */
395
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
396
    {
397
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
398 399
            return true;
        }
400

401
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
402 403 404
            return true;
        }

405
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
406 407 408
            return true;
        }

409
        if ($key1->onUpdate() !== $key2->onUpdate()) {
410 411 412
            return true;
        }

Gabriel Caruso's avatar
Gabriel Caruso committed
413
        return $key1->onDelete() !== $key2->onDelete();
414 415
    }

416 417 418 419 420 421
    /**
     * Returns the difference between the fields $field1 and $field2.
     *
     * If there are differences this method returns $field2, otherwise the
     * boolean false.
     *
422
     * @return string[]
423
     */
424
    public function diffColumn(Column $column1, Column $column2)
425
    {
426 427 428
        $properties1 = $column1->toArray();
        $properties2 = $column2->toArray();

429
        $changedProperties = [];
430

431 432 433 434 435
        if (get_class($properties1['type']) !== get_class($properties2['type'])) {
            $changedProperties[] = 'type';
        }

        foreach (['notnull', 'unsigned', 'autoincrement'] as $property) {
436 437
            if ($properties1[$property] === $properties2[$property]) {
                continue;
438
            }
439 440

            $changedProperties[] = $property;
441
        }
442

443 444 445 446 447 448 449
        // This is a very nasty hack to make comparator work with the legacy json_array type, which should be killed in v3
        if ($this->isALegacyJsonComparison($properties1['type'], $properties2['type'])) {
            array_shift($changedProperties);

            $changedProperties[] = 'comment';
        }

450 451
        // Null values need to be checked additionally as they tell whether to create or drop a default value.
        // null != 0, null != false, null != '' etc. This affects platform's table alteration SQL generation.
452 453 454 455
        if (
            ($properties1['default'] === null) !== ($properties2['default'] === null)
            || $properties1['default'] != $properties2['default']
        ) {
456
            $changedProperties[] = 'default';
457 458
        }

459 460
        if (
            ($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
461 462
            $properties1['type'] instanceof Types\BinaryType
        ) {
463
            // check if value of length is set at all, default value assumed otherwise.
464 465
            $length1 = $properties1['length'] ?? 255;
            $length2 = $properties2['length'] ?? 255;
466
            if ($length1 !== $length2) {
467
                $changedProperties[] = 'length';
468 469
            }

470
            if ($properties1['fixed'] !== $properties2['fixed']) {
471
                $changedProperties[] = 'fixed';
472
            }
473
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
474
            if (($properties1['precision'] ?? 10) !== ($properties2['precision'] ?? 10)) {
475
                $changedProperties[] = 'precision';
476
            }
Grégoire Paris's avatar
Grégoire Paris committed
477

478
            if ($properties1['scale'] !== $properties2['scale']) {
479
                $changedProperties[] = 'scale';
480 481 482
            }
        }

483
        // A null value and an empty string are actually equal for a comment so they should not trigger a change.
484 485
        if (
            $properties1['comment'] !== $properties2['comment'] &&
486 487
            ! ($properties1['comment'] === null && $properties2['comment'] === '') &&
            ! ($properties2['comment'] === null && $properties1['comment'] === '')
488
        ) {
489 490 491
            $changedProperties[] = 'comment';
        }

492 493
        $customOptions1 = $column1->getCustomSchemaOptions();
        $customOptions2 = $column2->getCustomSchemaOptions();
494

495
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
496
            if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
497 498
                $changedProperties[] = $key;
            } elseif ($properties1[$key] !== $properties2[$key]) {
499 500 501 502
                $changedProperties[] = $key;
            }
        }

503 504 505 506
        $platformOptions1 = $column1->getPlatformOptions();
        $platformOptions2 = $column2->getPlatformOptions();

        foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
507 508
            if ($properties1[$key] === $properties2[$key]) {
                continue;
509
            }
510 511

            $changedProperties[] = $key;
512 513 514
        }

        return array_unique($changedProperties);
515 516
    }

517 518 519 520 521
    /**
     * TODO: kill with fire on v3.0
     *
     * @deprecated
     */
522
    private function isALegacyJsonComparison(Types\Type $one, Types\Type $other): bool
523
    {
524
        if (! $one instanceof Types\JsonType || ! $other instanceof Types\JsonType) {
525 526 527 528 529 530 531
            return false;
        }

        return ( ! $one instanceof Types\JsonArrayType && $other instanceof Types\JsonArrayType)
            || ( ! $other instanceof Types\JsonArrayType && $one instanceof Types\JsonArrayType);
    }

532 533 534 535 536 537
    /**
     * Finds the difference between the indexes $index1 and $index2.
     *
     * Compares $index1 with $index2 and returns $index2 if there are any
     * differences or false in case there are no differences.
     *
538
     * @return bool
539
     */
540
    public function diffIndex(Index $index1, Index $index2)
541
    {
Gabriel Caruso's avatar
Gabriel Caruso committed
542
        return ! ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1));
543
    }
beberlei's avatar
beberlei committed
544
}