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

namespace Doctrine\DBAL\Schema;

5
use Doctrine\DBAL\Types;
6 7 8 9 10 11 12
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
13
use function assert;
14
use function count;
15
use function get_class;
16
use function strtolower;
17

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

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

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

47
        $foreignKeysToTable = [];
48

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

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

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

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

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

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

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

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

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

97
        foreach ($diff->removedTables as $tableName => $table) {
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
            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
114 115
                    assert($removedForeignKey instanceof ForeignKeyConstraint);

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

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

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

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

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

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

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

        return $diff;
    }

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

        return false;
    }

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

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

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

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

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

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

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

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

223 224
            if (empty($changedProperties)) {
                continue;
225
            }
226 227 228 229 230

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

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

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

238 239 240 241
        /* 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;
242
            }
243

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

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

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

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

            $tableDifferences->changedIndexes[$indexName] = $table2Index;
            $changes++;
269 270
        }

271 272
        $this->detectIndexRenamings($tableDifferences);

273
        $fromFkeys = $table1->getForeignKeys();
274
        $toFkeys   = $table2->getForeignKeys();
275

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

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

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

        return $changes ? $tableDifferences : false;
    }

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

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

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

            [$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]
            );
340 341 342
        }
    }

343 344 345 346 347 348 349 350
    /**
     * 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)
    {
351
        $renameCandidates = [];
352 353 354 355

        // 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) {
356 357
                if ($this->diffIndex($addedIndex, $removedIndex)) {
                    continue;
358
                }
359 360

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

        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.
369 370 371 372 373 374 375 376 377 378 379
            if (count($candidateIndexes) !== 1) {
                continue;
            }

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

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

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

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

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

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

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

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

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

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

427
        $changedProperties = [];
428

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

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

            $changedProperties[] = $property;
439
        }
440

441 442 443 444 445 446 447
        // 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';
        }

448 449 450
        // 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.
        if (($properties1['default'] === null) !== ($properties2['default'] === null)
451
            || $properties1['default'] != $properties2['default']) {
452
            $changedProperties[] = 'default';
453 454
        }

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

465
            if ($properties1['fixed'] !== $properties2['fixed']) {
466
                $changedProperties[] = 'fixed';
467
            }
468
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
469
            if (($properties1['precision'] ?: 10) !== ($properties2['precision'] ?: 10)) {
470
                $changedProperties[] = 'precision';
471
            }
Grégoire Paris's avatar
Grégoire Paris committed
472

473
            if ($properties1['scale'] !== $properties2['scale']) {
474
                $changedProperties[] = 'scale';
475 476 477
            }
        }

478 479
        // A null value and an empty string are actually equal for a comment so they should not trigger a change.
        if ($properties1['comment'] !== $properties2['comment'] &&
480 481
            ! ($properties1['comment'] === null && $properties2['comment'] === '') &&
            ! ($properties2['comment'] === null && $properties1['comment'] === '')
482
        ) {
483 484 485
            $changedProperties[] = 'comment';
        }

486 487
        $customOptions1 = $column1->getCustomSchemaOptions();
        $customOptions2 = $column2->getCustomSchemaOptions();
488

489
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
490
            if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
491 492
                $changedProperties[] = $key;
            } elseif ($properties1[$key] !== $properties2[$key]) {
493 494 495 496
                $changedProperties[] = $key;
            }
        }

497 498 499 500
        $platformOptions1 = $column1->getPlatformOptions();
        $platformOptions2 = $column2->getPlatformOptions();

        foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
501 502
            if ($properties1[$key] === $properties2[$key]) {
                continue;
503
            }
504 505

            $changedProperties[] = $key;
506 507 508
        }

        return array_unique($changedProperties);
509 510
    }

511 512 513 514 515 516 517
    /**
     * TODO: kill with fire on v3.0
     *
     * @deprecated
     */
    private function isALegacyJsonComparison(Types\Type $one, Types\Type $other) : bool
    {
518
        if (! $one instanceof Types\JsonType || ! $other instanceof Types\JsonType) {
519 520 521 522 523 524 525
            return false;
        }

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

526 527 528 529 530 531
    /**
     * 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.
     *
532
     * @return bool
533
     */
534
    public function diffIndex(Index $index1, Index $index2)
535
    {
Gabriel Caruso's avatar
Gabriel Caruso committed
536
        return ! ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1));
537
    }
beberlei's avatar
beberlei committed
538
}