Completed
Pull Request — master (#3885)
by Grégoire
37:52 queued 34:57
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 408
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema) : SchemaDiff
25
    {
26 408
        $c = new self();
27
28 408
        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 674
    public function compare(Schema $fromSchema, Schema $toSchema) : SchemaDiff
39
    {
40 674
        $diff             = new SchemaDiff();
41 674
        $diff->fromSchema = $fromSchema;
42
43 674
        $foreignKeysToTable = [];
44
45 674
        foreach ($toSchema->getNamespaces() as $namespace) {
46 48
            if ($fromSchema->hasNamespace($namespace)) {
47 48
                continue;
48
            }
49
50 48
            $diff->newNamespaces[$namespace] = $namespace;
51
        }
52
53 674
        foreach ($fromSchema->getNamespaces() as $namespace) {
54 48
            if ($toSchema->hasNamespace($namespace)) {
55 48
                continue;
56
            }
57
58 24
            $diff->removedNamespaces[$namespace] = $namespace;
59
        }
60
61 674
        foreach ($toSchema->getTables() as $table) {
62 530
            $tableName = $table->getShortestName($toSchema->getName());
63 530
            if (! $fromSchema->hasTable($tableName)) {
64 120
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
65
            } else {
66 482
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
67 482
                if ($tableDifferences !== null) {
68 266
                    $diff->changedTables[$tableName] = $tableDifferences;
69
                }
70
            }
71
        }
72
73
        /* Check if there are tables removed */
74 674
        foreach ($fromSchema->getTables() as $table) {
75 506
            $tableName = $table->getShortestName($fromSchema->getName());
76
77 506
            $table = $fromSchema->getTable($tableName);
78 506
            if (! $toSchema->hasTable($tableName)) {
79 120
                $diff->removedTables[$tableName] = $table;
80
            }
81
82
            // also remember all foreign keys that point to a specific table
83 506
            foreach ($table->getForeignKeys() as $foreignKey) {
84 48
                $foreignTable = strtolower($foreignKey->getForeignTableName());
85 48
                if (! isset($foreignKeysToTable[$foreignTable])) {
86 48
                    $foreignKeysToTable[$foreignTable] = [];
87
                }
88
89 48
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
90
            }
91
        }
92
93 674
        foreach ($diff->removedTables as $tableName => $table) {
94 120
            if (! isset($foreignKeysToTable[$tableName])) {
95 72
                continue;
96
            }
97
98 48
            $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 48
            foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
103
                // strtolower the table name to make if compatible with getShortestName
104 48
                $localTableName = strtolower($foreignKey->getLocalTableName());
105 48
                if (! isset($diff->changedTables[$localTableName])) {
106
                    continue;
107
                }
108
109 48
                foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
110 48
                    assert($removedForeignKey instanceof ForeignKeyConstraint);
111
112
                    // We check if the key is from the removed table if not we skip.
113 48
                    if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
114 24
                        continue;
115
                    }
116
117 48
                    unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
118
                }
119
            }
120
        }
121
122 674
        foreach ($toSchema->getSequences() as $sequence) {
123 96
            $sequenceName = $sequence->getShortestName($toSchema->getName());
124 96
            if (! $fromSchema->hasSequence($sequenceName)) {
125 72
                if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
126 72
                    $diff->newSequences[] = $sequence;
127
                }
128
            } else {
129 48
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
130 24
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
131
                }
132
            }
133
        }
134
135 674
        foreach ($fromSchema->getSequences() as $sequence) {
136 96
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
137 24
                continue;
138
            }
139
140 72
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
141
142 72
            if ($toSchema->hasSequence($sequenceName)) {
143 48
                continue;
144
            }
145
146 48
            $diff->removedSequences[] = $sequence;
147
        }
148
149 674
        return $diff;
150
    }
151
152 144
    private function isAutoIncrementSequenceInSchema(Schema $schema, Sequence $sequence) : bool
153
    {
154 144
        foreach ($schema->getTables() as $table) {
155 48
            if ($sequence->isAutoIncrementsFor($table)) {
156 48
                return true;
157
            }
158
        }
159
160 96
        return false;
161
    }
162
163 81
    public function diffSequence(Sequence $sequence1, Sequence $sequence2) : bool
164
    {
165 81
        if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
166 48
            return true;
167
        }
168
169 57
        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 2620
    public function diffTable(Table $table1, Table $table2) : ?TableDiff
178
    {
179 2620
        $changes                     = 0;
180 2620
        $tableDifferences            = new TableDiff($table1->getName());
181 2620
        $tableDifferences->fromTable = $table1;
182
183 2620
        $table1Columns = $table1->getColumns();
184 2620
        $table2Columns = $table2->getColumns();
185
186
        /* See if all the fields in table 1 exist in table 2 */
187 2620
        foreach ($table2Columns as $columnName => $column) {
188 2500
            if ($table1->hasColumn($columnName)) {
189 2188
                continue;
190
            }
191
192 564
            $tableDifferences->addedColumns[$columnName] = $column;
193 564
            $changes++;
194
        }
195
196
        /* See if there are any removed fields in table 2 */
197 2620
        foreach ($table1Columns as $columnName => $column) {
198
            // See if column is removed in table 2.
199 2500
            if (! $table2->hasColumn($columnName)) {
200 479
                $tableDifferences->removedColumns[$columnName] = $column;
201 479
                $changes++;
202 479
                continue;
203
            }
204
205
            // See if column has changed properties in table 2.
206 2188
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));
207
208 2188
            if (empty($changedProperties)) {
209 1648
                continue;
210
            }
211
212 758
            $columnDiff                                           = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
213 758
            $columnDiff->fromColumn                               = $column;
214 758
            $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
215 758
            $changes++;
216
        }
217
218 2620
        $this->detectColumnRenamings($tableDifferences);
219
220 2620
        $table1Indexes = $table1->getIndexes();
221 2620
        $table2Indexes = $table2->getIndexes();
222
223
        /* See if all the indexes in table 1 exist in table 2 */
224 2620
        foreach ($table2Indexes as $indexName => $index) {
225 1090
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
226 657
                continue;
227
            }
228
229 433
            $tableDifferences->addedIndexes[$indexName] = $index;
230 433
            $changes++;
231
        }
232
233
        /* See if there are any removed indexes in table 2 */
234 2620
        foreach ($table1Indexes as $indexName => $index) {
235
            // See if index is removed in table 2.
236 1018
            if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
237 1018
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
238
            ) {
239 409
                $tableDifferences->removedIndexes[$indexName] = $index;
240 409
                $changes++;
241 409
                continue;
242
            }
243
244
            // See if index has changed in table 2.
245 657
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
246 657
            assert($table2Index instanceof Index);
247
248 657
            if (! $this->diffIndex($index, $table2Index)) {
249 297
                continue;
250
            }
251
252 396
            $tableDifferences->changedIndexes[$indexName] = $table2Index;
253 396
            $changes++;
254
        }
255
256 2620
        $this->detectIndexRenamings($tableDifferences);
257
258 2620
        $fromFkeys = $table1->getForeignKeys();
259 2620
        $toFkeys   = $table2->getForeignKeys();
260
261 2620
        foreach ($fromFkeys as $key1 => $constraint1) {
262 243
            foreach ($toFkeys as $key2 => $constraint2) {
263 147
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
264 52
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
265
                } else {
266 95
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
267 48
                        $tableDifferences->changedForeignKeys[] = $constraint2;
268 48
                        $changes++;
269 48
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
270
                    }
271
                }
272
            }
273
        }
274
275 2620
        foreach ($fromFkeys as $constraint1) {
276 143
            $tableDifferences->removedForeignKeys[] = $constraint1;
277 143
            $changes++;
278
        }
279
280 2620
        foreach ($toFkeys as $constraint2) {
281 71
            $tableDifferences->addedForeignKeys[] = $constraint2;
282 71
            $changes++;
283
        }
284
285 2620
        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 2620
    private function detectColumnRenamings(TableDiff $tableDifferences) : void
293
    {
294 2620
        $renameCandidates = [];
295 2620
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
296 564
            foreach ($tableDifferences->removedColumns as $removedColumn) {
297 383
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
298 264
                    continue;
299
                }
300
301 383
                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
302
            }
303
        }
304
305 2620
        foreach ($renameCandidates as $candidateColumns) {
306 383
            if (count($candidateColumns) !== 1) {
307 24
                continue;
308
            }
309
310 359
            [$removedColumn, $addedColumn] = $candidateColumns[0];
311 359
            $removedColumnName             = strtolower($removedColumn->getName());
312 359
            $addedColumnName               = strtolower($addedColumn->getName());
313
314 359
            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
315 24
                continue;
316
            }
317
318 359
            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
319
            unset(
320 359
                $tableDifferences->addedColumns[$addedColumnName],
321 359
                $tableDifferences->removedColumns[$removedColumnName]
322
            );
323
        }
324 2620
    }
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 2620
    private function detectIndexRenamings(TableDiff $tableDifferences) : void
331
    {
332 2620
        $renameCandidates = [];
333
334
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
335 2620
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
336 433
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
337 204
                if ($this->diffIndex($addedIndex, $removedIndex)) {
338 109
                    continue;
339
                }
340
341 95
                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
342
            }
343
        }
344
345 2620
        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 95
            if (count($candidateIndexes) !== 1) {
351 24
                continue;
352
            }
353
354 71
            [$removedIndex, $addedIndex] = $candidateIndexes[0];
355
356 71
            $removedIndexName = strtolower($removedIndex->getName());
357 71
            $addedIndexName   = strtolower($addedIndex->getName());
358
359 71
            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
360
                continue;
361
            }
362
363 71
            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
364
            unset(
365 71
                $tableDifferences->addedIndexes[$addedIndexName],
366 71
                $tableDifferences->removedIndexes[$removedIndexName]
367
            );
368
        }
369 2620
    }
370
371 219
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2) : bool
372
    {
373 219
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
374 47
            return true;
375
        }
376
377 172
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
378
            return true;
379
        }
380
381 172
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
382 24
            return true;
383
        }
384
385 148
        if ($key1->onUpdate() !== $key2->onUpdate()) {
386 24
            return true;
387
        }
388
389 124
        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 3076
    public function diffColumn(Column $column1, Column $column2) : array
401
    {
402 3076
        $properties1 = $column1->toArray();
403 3076
        $properties2 = $column2->toArray();
404
405 3076
        $changedProperties = [];
406
407 3076
        if (get_class($properties1['type']) !== get_class($properties2['type'])) {
408 182
            $changedProperties[] = 'type';
409
        }
410
411 3076
        foreach (['notnull', 'unsigned', 'autoincrement'] as $property) {
412 3076
            if ($properties1[$property] === $properties2[$property]) {
413 3076
                continue;
414
            }
415
416 63
            $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 3076
        if (($properties1['default'] === null) !== ($properties2['default'] === null)
422 3076
            || $properties1['default'] != $properties2['default']) {
423 105
            $changedProperties[] = 'default';
424
        }
425
426 3076
        if (($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
427 3076
            $properties1['type'] instanceof Types\BinaryType
428
        ) {
429 612
            if ((isset($properties1['length']) !== isset($properties2['length']))
430 588
                || (isset($properties1['length']) && isset($properties2['length'])
431 612
                    && $properties1['length'] !== $properties2['length'])
432
            ) {
433 218
                $changedProperties[] = 'length';
434
            }
435
436 612
            if ($properties1['fixed'] !== $properties2['fixed']) {
437 612
                $changedProperties[] = 'fixed';
438
            }
439 2703
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
440 46
            if (($properties1['precision'] ?: 10) !== ($properties2['precision'] ?: 10)) {
441
                $changedProperties[] = 'precision';
442
            }
443
444 46
            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 3076
        if ($properties1['comment'] !== $properties2['comment'] &&
451 3076
            ! ($properties1['comment'] === null && $properties2['comment'] === '') &&
452 3076
            ! ($properties2['comment'] === null && $properties1['comment'] === '')
453
        ) {
454 792
            $changedProperties[] = 'comment';
455
        }
456
457 3076
        $customOptions1 = $column1->getCustomSchemaOptions();
458 3076
        $customOptions2 = $column2->getCustomSchemaOptions();
459
460 3076
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
461 48
            if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
462 24
                $changedProperties[] = $key;
463 48
            } elseif ($properties1[$key] !== $properties2[$key]) {
464
                $changedProperties[] = $key;
465
            }
466
        }
467
468 3076
        $platformOptions1 = $column1->getPlatformOptions();
469 3076
        $platformOptions2 = $column2->getPlatformOptions();
470
471 3076
        foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
472 87
            if ($properties1[$key] === $properties2[$key]) {
473 61
                continue;
474
            }
475
476 50
            $changedProperties[] = $key;
477
        }
478
479 3076
        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 861
    public function diffIndex(Index $index1, Index $index2) : bool
489
    {
490 861
        return ! ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1));
491
    }
492
}
493