Passed
Pull Request — master (#3070)
by Sergei
07:45
created

Comparator::detectIndexRenamings()   B

Complexity

Conditions 7
Paths 16

Size

Total Lines 37
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 7.0084

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 37
ccs 17
cts 18
cp 0.9444
rs 8.8333
c 0
b 0
f 0
cc 7
nc 16
nop 1
crap 7.0084
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\DBAL\Schema;
6
7
use Doctrine\DBAL\Types;
8
use function array_intersect_key;
9
use function array_key_exists;
10
use function array_keys;
11
use function array_map;
12
use function array_merge;
13
use function array_unique;
14
use function assert;
15
use function count;
16
use function get_class;
17
use function strtolower;
18
19
/**
20
 * Compares two Schemas and return an instance of SchemaDiff.
21
 */
22
class Comparator
23
{
24 459
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema) : SchemaDiff
25
    {
26 459
        $c = new self();
27
28 459
        return $c->compare($fromSchema, $toSchema);
29
    }
30
31
    /**
32
     * Returns a SchemaDiff object containing the differences between the schemas $fromSchema and $toSchema.
33
     *
34
     * The returned differences are returned in such a way that they contain the
35
     * operations to change the schema stored in $fromSchema to the schema that is
36
     * stored in $toSchema.
37
     */
38 757
    public function compare(Schema $fromSchema, Schema $toSchema) : SchemaDiff
39
    {
40 757
        $diff             = new SchemaDiff();
41 757
        $diff->fromSchema = $fromSchema;
42
43 757
        $foreignKeysToTable = [];
44
45 757
        foreach ($toSchema->getNamespaces() as $namespace) {
46 54
            if ($fromSchema->hasNamespace($namespace)) {
47 54
                continue;
48
            }
49
50 54
            $diff->newNamespaces[$namespace] = $namespace;
51
        }
52
53 757
        foreach ($fromSchema->getNamespaces() as $namespace) {
54 54
            if ($toSchema->hasNamespace($namespace)) {
55 54
                continue;
56
            }
57
58 27
            $diff->removedNamespaces[$namespace] = $namespace;
59
        }
60
61 757
        foreach ($toSchema->getTables() as $table) {
62 595
            $tableName = $table->getShortestName($toSchema->getName());
63 595
            if (! $fromSchema->hasTable($tableName)) {
64 135
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
65
            } else {
66 541
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
67 541
                if ($tableDifferences !== null) {
68 298
                    $diff->changedTables[$tableName] = $tableDifferences;
69
                }
70
            }
71
        }
72
73
        /* Check if there are tables removed */
74 757
        foreach ($fromSchema->getTables() as $table) {
75 568
            $tableName = $table->getShortestName($fromSchema->getName());
76
77 568
            $table = $fromSchema->getTable($tableName);
78 568
            if (! $toSchema->hasTable($tableName)) {
79 135
                $diff->removedTables[$tableName] = $table;
80
            }
81
82
            // also remember all foreign keys that point to a specific table
83 568
            foreach ($table->getForeignKeys() as $foreignKey) {
84 54
                $foreignTable = strtolower($foreignKey->getForeignTableName());
85 54
                if (! isset($foreignKeysToTable[$foreignTable])) {
86 54
                    $foreignKeysToTable[$foreignTable] = [];
87
                }
88
89 54
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
90
            }
91
        }
92
93 757
        foreach ($diff->removedTables as $tableName => $table) {
94 135
            if (! isset($foreignKeysToTable[$tableName])) {
95 81
                continue;
96
            }
97
98 54
            $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
99
100
            // deleting duplicated foreign keys present on both on the orphanedForeignKey
101
            // and the removedForeignKeys from changedTables
102 54
            foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
103
                // strtolower the table name to make if compatible with getShortestName
104 54
                $localTableName = strtolower($foreignKey->getLocalTableName());
105 54
                if (! isset($diff->changedTables[$localTableName])) {
106
                    continue;
107
                }
108
109 54
                foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
110 54
                    assert($removedForeignKey instanceof ForeignKeyConstraint);
111
112
                    // We check if the key is from the removed table if not we skip.
113 54
                    if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
114 27
                        continue;
115
                    }
116
117 54
                    unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
118
                }
119
            }
120
        }
121
122 757
        foreach ($toSchema->getSequences() as $sequence) {
123 108
            $sequenceName = $sequence->getShortestName($toSchema->getName());
124 108
            if (! $fromSchema->hasSequence($sequenceName)) {
125 81
                if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
126 81
                    $diff->newSequences[] = $sequence;
127
                }
128
            } else {
129 54
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
130 27
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
131
                }
132
            }
133
        }
134
135 757
        foreach ($fromSchema->getSequences() as $sequence) {
136 108
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
137 27
                continue;
138
            }
139
140 81
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
141
142 81
            if ($toSchema->hasSequence($sequenceName)) {
143 54
                continue;
144
            }
145
146 54
            $diff->removedSequences[] = $sequence;
147
        }
148
149 757
        return $diff;
150
    }
151
152 162
    private function isAutoIncrementSequenceInSchema(Schema $schema, Sequence $sequence) : bool
153
    {
154 162
        foreach ($schema->getTables() as $table) {
155 54
            if ($sequence->isAutoIncrementsFor($table)) {
156 54
                return true;
157
            }
158
        }
159
160 108
        return false;
161
    }
162
163 93
    public function diffSequence(Sequence $sequence1, Sequence $sequence2) : bool
164
    {
165 93
        if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
166 54
            return true;
167
        }
168
169 66
        return $sequence1->getInitialValue() !== $sequence2->getInitialValue();
170
    }
171
172
    /**
173
     * Returns the difference between the tables $table1 and $table2.
174
     *
175
     * If there are no differences this method returns null.
176
     */
177 2962
    public function diffTable(Table $table1, Table $table2) : ?TableDiff
178
    {
179 2962
        $changes                     = 0;
180 2962
        $tableDifferences            = new TableDiff($table1->getName());
181 2962
        $tableDifferences->fromTable = $table1;
182
183 2962
        $table1Columns = $table1->getColumns();
184 2962
        $table2Columns = $table2->getColumns();
185
186
        /* See if all the fields in table 1 exist in table 2 */
187 2962
        foreach ($table2Columns as $columnName => $column) {
188 2827
            if ($table1->hasColumn($columnName)) {
189 2476
                continue;
190
            }
191
192 634
            $tableDifferences->addedColumns[$columnName] = $column;
193 634
            $changes++;
194
        }
195
196
        /* See if there are any removed fields in table 2 */
197 2962
        foreach ($table1Columns as $columnName => $column) {
198
            // See if column is removed in table 2.
199 2827
            if (! $table2->hasColumn($columnName)) {
200 539
                $tableDifferences->removedColumns[$columnName] = $column;
201 539
                $changes++;
202 539
                continue;
203
            }
204
205
            // See if column has changed properties in table 2.
206 2476
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));
207
208 2476
            if (empty($changedProperties)) {
209 1863
                continue;
210
            }
211
212 858
            $columnDiff                                           = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
213 858
            $columnDiff->fromColumn                               = $column;
214 858
            $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
215 858
            $changes++;
216
        }
217
218 2962
        $this->detectColumnRenamings($tableDifferences);
219
220 2962
        $table1Indexes = $table1->getIndexes();
221 2962
        $table2Indexes = $table2->getIndexes();
222
223
        /* See if all the indexes in table 1 exist in table 2 */
224 2962
        foreach ($table2Indexes as $indexName => $index) {
225 1231
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
226 745
                continue;
227
            }
228
229 486
            $tableDifferences->addedIndexes[$indexName] = $index;
230 486
            $changes++;
231
        }
232
233
        /* See if there are any removed indexes in table 2 */
234 2962
        foreach ($table1Indexes as $indexName => $index) {
235
            // See if index is removed in table 2.
236 1150
            if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
237 1150
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
238
            ) {
239 459
                $tableDifferences->removedIndexes[$indexName] = $index;
240 459
                $changes++;
241 459
                continue;
242
            }
243
244
            // See if index has changed in table 2.
245 745
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
246 745
            assert($table2Index instanceof Index);
247
248 745
            if (! $this->diffIndex($index, $table2Index)) {
249 340
                continue;
250
            }
251
252 445
            $tableDifferences->changedIndexes[$indexName] = $table2Index;
253 445
            $changes++;
254
        }
255
256 2962
        $this->detectIndexRenamings($tableDifferences);
257
258 2962
        $fromFkeys = $table1->getForeignKeys();
259 2962
        $toFkeys   = $table2->getForeignKeys();
260
261 2962
        foreach ($fromFkeys as $key1 => $constraint1) {
262 276
            foreach ($toFkeys as $key2 => $constraint2) {
263 168
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
264 61
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
265
                } else {
266 107
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
267 54
                        $tableDifferences->changedForeignKeys[] = $constraint2;
268 54
                        $changes++;
269 54
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
270
                    }
271
                }
272
            }
273
        }
274
275 2962
        foreach ($fromFkeys as $constraint1) {
276 161
            $tableDifferences->removedForeignKeys[] = $constraint1;
277 161
            $changes++;
278
        }
279
280 2962
        foreach ($toFkeys as $constraint2) {
281 80
            $tableDifferences->addedForeignKeys[] = $constraint2;
282 80
            $changes++;
283
        }
284
285 2962
        return $changes ? $tableDifferences : null;
286
    }
287
288
    /**
289
     * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
290
     * however ambiguities between different possibilities should not lead to renaming at all.
291
     */
292 2962
    private function detectColumnRenamings(TableDiff $tableDifferences) : void
293
    {
294 2962
        $renameCandidates = [];
295 2962
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
296 634
            foreach ($tableDifferences->removedColumns as $removedColumn) {
297 431
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
298 297
                    continue;
299
                }
300
301 431
                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
302
            }
303
        }
304
305 2962
        foreach ($renameCandidates as $candidateColumns) {
306 431
            if (count($candidateColumns) !== 1) {
307 27
                continue;
308
            }
309
310 404
            [$removedColumn, $addedColumn] = $candidateColumns[0];
311 404
            $removedColumnName             = strtolower($removedColumn->getName());
312 404
            $addedColumnName               = strtolower($addedColumn->getName());
313
314 404
            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
315 27
                continue;
316
            }
317
318 404
            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
319
            unset(
320 404
                $tableDifferences->addedColumns[$addedColumnName],
321 404
                $tableDifferences->removedColumns[$removedColumnName]
322
            );
323
        }
324 2962
    }
325
326
    /**
327
     * Try to find indexes that only changed their name, rename operations maybe cheaper than add/drop
328
     * however ambiguities between different possibilities should not lead to renaming at all.
329
     */
330 2962
    private function detectIndexRenamings(TableDiff $tableDifferences) : void
331
    {
332 2962
        $renameCandidates = [];
333
334
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
335 2962
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
336 486
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
337 229
                if ($this->diffIndex($addedIndex, $removedIndex)) {
338 122
                    continue;
339
                }
340
341 107
                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
342
            }
343
        }
344
345 2962
        foreach ($renameCandidates as $candidateIndexes) {
346
            // If the current rename candidate contains exactly one semantically equal index,
347
            // we can safely rename it.
348
            // Otherwise it is unclear if a rename action is really intended,
349
            // therefore we let those ambiguous indexes be added/dropped.
350 107
            if (count($candidateIndexes) !== 1) {
351 27
                continue;
352
            }
353
354 80
            [$removedIndex, $addedIndex] = $candidateIndexes[0];
355
356 80
            $removedIndexName = strtolower($removedIndex->getName());
357 80
            $addedIndexName   = strtolower($addedIndex->getName());
358
359 80
            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
360
                continue;
361
            }
362
363 80
            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
364
            unset(
365 80
                $tableDifferences->addedIndexes[$addedIndexName],
366 80
                $tableDifferences->removedIndexes[$removedIndexName]
367
            );
368
        }
369 2962
    }
370
371 249
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2) : bool
372
    {
373 249
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
374 53
            return true;
375
        }
376
377 196
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
378
            return true;
379
        }
380
381 196
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
382 27
            return true;
383
        }
384
385 169
        if ($key1->onUpdate() !== $key2->onUpdate()) {
386 27
            return true;
387
        }
388
389 142
        return $key1->onDelete() !== $key2->onDelete();
390
    }
391
392
    /**
393
     * Returns the difference between the fields $field1 and $field2.
394
     *
395
     * If there are differences this method returns $field2, otherwise the
396
     * boolean false.
397
     *
398
     * @return array<int, string>
399
     */
400 3475
    public function diffColumn(Column $column1, Column $column2) : array
401
    {
402 3475
        $properties1 = $column1->toArray();
403 3475
        $properties2 = $column2->toArray();
404
405 3475
        $changedProperties = [];
406
407 3475
        if (get_class($properties1['type']) !== get_class($properties2['type'])) {
408 209
            $changedProperties[] = 'type';
409
        }
410
411 3475
        foreach (['notnull', 'unsigned', 'autoincrement'] as $property) {
412 3475
            if ($properties1[$property] === $properties2[$property]) {
413 3475
                continue;
414
            }
415
416 75
            $changedProperties[] = $property;
417
        }
418
419
        // Null values need to be checked additionally as they tell whether to create or drop a default value.
420
        // null != 0, null != false, null != '' etc. This affects platform's table alteration SQL generation.
421 3475
        if (($properties1['default'] === null) !== ($properties2['default'] === null)
422 3475
            || $properties1['default'] != $properties2['default']) {
423 116
            $changedProperties[] = 'default';
424
        }
425
426 3475
        if (($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
427 3475
            $properties1['type'] instanceof Types\BinaryType
428
        ) {
429 692
            if ((isset($properties1['length']) !== isset($properties2['length']))
430 665
                || (isset($properties1['length']) && isset($properties2['length'])
431 692
                    && $properties1['length'] !== $properties2['length'])
432
            ) {
433 245
                $changedProperties[] = 'length';
434
            }
435
436 692
            if ($properties1['fixed'] !== $properties2['fixed']) {
437 692
                $changedProperties[] = 'fixed';
438
            }
439 3056
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
440 52
            if (($properties1['precision'] ?: 10) !== ($properties2['precision'] ?: 10)) {
441
                $changedProperties[] = 'precision';
442
            }
443
444 52
            if ($properties1['scale'] !== $properties2['scale']) {
445
                $changedProperties[] = 'scale';
446
            }
447
        }
448
449
        // A null value and an empty string are actually equal for a comment so they should not trigger a change.
450 3475
        if ($properties1['comment'] !== $properties2['comment'] &&
451 3475
            ! ($properties1['comment'] === null && $properties2['comment'] === '') &&
452 3475
            ! ($properties2['comment'] === null && $properties1['comment'] === '')
453
        ) {
454 891
            $changedProperties[] = 'comment';
455
        }
456
457 3475
        $customOptions1 = $column1->getCustomSchemaOptions();
458 3475
        $customOptions2 = $column2->getCustomSchemaOptions();
459
460 3475
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
461 54
            if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
462 27
                $changedProperties[] = $key;
463 54
            } elseif ($properties1[$key] !== $properties2[$key]) {
464
                $changedProperties[] = $key;
465
            }
466
        }
467
468 3475
        $platformOptions1 = $column1->getPlatformOptions();
469 3475
        $platformOptions2 = $column2->getPlatformOptions();
470
471 3475
        foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
472 96
            if ($properties1[$key] === $properties2[$key]) {
473 68
                continue;
474
            }
475
476 55
            $changedProperties[] = $key;
477
        }
478
479 3475
        return array_unique($changedProperties);
480
    }
481
482
    /**
483
     * Finds the difference between the indexes $index1 and $index2.
484
     *
485
     * Compares $index1 with $index2 and returns $index2 if there are any
486
     * differences or false in case there are no differences.
487
     */
488 974
    public function diffIndex(Index $index1, Index $index2) : bool
489
    {
490 974
        return ! ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1));
491
    }
492
}
493