Completed
Push — 2.11.x ( 0a2e2f...a8544c )
by Grégoire
23s queued 16s
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
namespace Doctrine\DBAL\Schema;
4
5
use Doctrine\DBAL\Types;
6
use function array_intersect_key;
7
use function array_key_exists;
8
use function array_keys;
9
use function array_map;
10
use function array_merge;
11
use function array_shift;
12
use function array_unique;
13
use function assert;
14
use function count;
15
use function get_class;
16
use function strtolower;
17
18
/**
19
 * Compares two Schemas and return an instance of SchemaDiff.
20
 */
21
class Comparator
22
{
23
    /**
24
     * @return SchemaDiff
25
     */
26 3222
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema)
27
    {
28 3222
        $c = new self();
29
30 3222
        return $c->compare($fromSchema, $toSchema);
31
    }
32
33
    /**
34
     * Returns a SchemaDiff object containing the differences between the schemas $fromSchema and $toSchema.
35
     *
36
     * The returned differences are returned in such a way that they contain the
37
     * operations to change the schema stored in $fromSchema to the schema that is
38
     * stored in $toSchema.
39
     *
40
     * @return SchemaDiff
41
     */
42 3557
    public function compare(Schema $fromSchema, Schema $toSchema)
43
    {
44 3557
        $diff             = new SchemaDiff();
45 3557
        $diff->fromSchema = $fromSchema;
46
47 3557
        $foreignKeysToTable = [];
48
49 3557
        foreach ($toSchema->getNamespaces() as $namespace) {
50 485
            if ($fromSchema->hasNamespace($namespace)) {
51 485
                continue;
52
            }
53
54 485
            $diff->newNamespaces[$namespace] = $namespace;
55
        }
56
57 3557
        foreach ($fromSchema->getNamespaces() as $namespace) {
58 485
            if ($toSchema->hasNamespace($namespace)) {
59 485
                continue;
60
            }
61
62 231
            $diff->removedNamespaces[$namespace] = $namespace;
63
        }
64
65 3557
        foreach ($toSchema->getTables() as $table) {
66 3551
            $tableName = $table->getShortestName($toSchema->getName());
67 3551
            if (! $fromSchema->hasTable($tableName)) {
68 1293
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
69
            } else {
70 3549
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
71 3549
                if ($tableDifferences !== false) {
72 2598
                    $diff->changedTables[$tableName] = $tableDifferences;
73
                }
74
            }
75
        }
76
77
        /* Check if there are tables removed */
78 3557
        foreach ($fromSchema->getTables() as $table) {
79 3550
            $tableName = $table->getShortestName($fromSchema->getName());
80
81 3550
            $table = $fromSchema->getTable($tableName);
82 3550
            if (! $toSchema->hasTable($tableName)) {
83 1316
                $diff->removedTables[$tableName] = $table;
84
            }
85
86
            // also remember all foreign keys that point to a specific table
87 3550
            foreach ($table->getForeignKeys() as $foreignKey) {
88 3207
                $foreignTable = strtolower($foreignKey->getForeignTableName());
89 3207
                if (! isset($foreignKeysToTable[$foreignTable])) {
90 3207
                    $foreignKeysToTable[$foreignTable] = [];
91
                }
92
93 3207
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
94
            }
95
        }
96
97 3557
        foreach ($diff->removedTables as $tableName => $table) {
98 1316
            if (! isset($foreignKeysToTable[$tableName])) {
99 1314
                continue;
100
            }
101
102 370
            $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
103
104
            // deleting duplicated foreign keys present on both on the orphanedForeignKey
105
            // and the removedForeignKeys from changedTables
106 370
            foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
107
                // strtolower the table name to make if compatible with getShortestName
108 370
                $localTableName = strtolower($foreignKey->getLocalTableName());
109 370
                if (! isset($diff->changedTables[$localTableName])) {
110
                    continue;
111
                }
112
113 370
                foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
114 370
                    assert($removedForeignKey instanceof ForeignKeyConstraint);
115
116
                    // We check if the key is from the removed table if not we skip.
117 370
                    if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
118 369
                        continue;
119
                    }
120
121 370
                    unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
122
                }
123
            }
124
        }
125
126 3557
        foreach ($toSchema->getSequences() as $sequence) {
127 947
            $sequenceName = $sequence->getShortestName($toSchema->getName());
128 947
            if (! $fromSchema->hasSequence($sequenceName)) {
129 946
                if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
130 946
                    $diff->newSequences[] = $sequence;
131
                }
132
            } else {
133 807
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
134 553
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
135
                }
136
            }
137
        }
138
139 3557
        foreach ($fromSchema->getSequences() as $sequence) {
140 970
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
141 415
                continue;
142
            }
143
144 969
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
145
146 969
            if ($toSchema->hasSequence($sequenceName)) {
147 807
                continue;
148
            }
149
150 968
            $diff->removedSequences[] = $sequence;
151
        }
152
153 3557
        return $diff;
154
    }
155
156
    /**
157
     * @param Schema   $schema
158
     * @param Sequence $sequence
159
     *
160
     * @return bool
161
     */
162 972
    private function isAutoIncrementSequenceInSchema($schema, $sequence)
163
    {
164 972
        foreach ($schema->getTables() as $table) {
165 416
            if ($sequence->isAutoIncrementsFor($table)) {
166 416
                return true;
167
            }
168
        }
169
170 970
        return false;
171
    }
172
173
    /**
174
     * @return bool
175
     */
176 1873
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
177
    {
178 1873
        if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
179 991
            return true;
180
        }
181
182 1872
        return $sequence1->getInitialValue() !== $sequence2->getInitialValue();
183
    }
184
185
    /**
186
     * Returns the difference between the tables $table1 and $table2.
187
     *
188
     * If there are no differences this method returns the boolean false.
189
     *
190
     * @return TableDiff|false
191
     */
192 3934
    public function diffTable(Table $table1, Table $table2)
193
    {
194 3934
        $changes                     = 0;
195 3934
        $tableDifferences            = new TableDiff($table1->getName());
196 3934
        $tableDifferences->fromTable = $table1;
197
198 3934
        $table1Columns = $table1->getColumns();
199 3934
        $table2Columns = $table2->getColumns();
200
201
        /* See if all the fields in table 1 exist in table 2 */
202 3934
        foreach ($table2Columns as $columnName => $column) {
203 3929
            if ($table1->hasColumn($columnName)) {
204 3908
                continue;
205
            }
206
207 3739
            $tableDifferences->addedColumns[$columnName] = $column;
208 3739
            $changes++;
209
        }
210
211
        /* See if there are any removed fields in table 2 */
212 3934
        foreach ($table1Columns as $columnName => $column) {
213
            // See if column is removed in table 2.
214 3929
            if (! $table2->hasColumn($columnName)) {
215 3583
                $tableDifferences->removedColumns[$columnName] = $column;
216 3583
                $changes++;
217 3583
                continue;
218
            }
219
220
            // See if column has changed properties in table 2.
221 3908
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));
222
223 3908
            if (empty($changedProperties)) {
224 3875
                continue;
225
            }
226
227 3735
            $columnDiff                                           = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
228 3735
            $columnDiff->fromColumn                               = $column;
229 3735
            $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
230 3735
            $changes++;
231
        }
232
233 3934
        $this->detectColumnRenamings($tableDifferences);
234
235 3934
        $table1Indexes = $table1->getIndexes();
236 3934
        $table2Indexes = $table2->getIndexes();
237
238
        /* See if all the indexes in table 1 exist in table 2 */
239 3934
        foreach ($table2Indexes as $indexName => $index) {
240 3807
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
241 3790
                continue;
242
            }
243
244 3678
            $tableDifferences->addedIndexes[$indexName] = $index;
245 3678
            $changes++;
246
        }
247
248
        /* See if there are any removed indexes in table 2 */
249 3934
        foreach ($table1Indexes as $indexName => $index) {
250
            // See if index is removed in table 2.
251 3804
            if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
252 3804
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
253
            ) {
254 3656
                $tableDifferences->removedIndexes[$indexName] = $index;
255 3656
                $changes++;
256 3656
                continue;
257
            }
258
259
            // See if index has changed in table 2.
260 3790
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
261 3790
            assert($table2Index instanceof Index);
262
263 3790
            if (! $this->diffIndex($index, $table2Index)) {
264 3775
                continue;
265
            }
266
267 3724
            $tableDifferences->changedIndexes[$indexName] = $table2Index;
268 3724
            $changes++;
269
        }
270
271 3934
        $this->detectIndexRenamings($tableDifferences);
272
273 3934
        $fromFkeys = $table1->getForeignKeys();
274 3934
        $toFkeys   = $table2->getForeignKeys();
275
276 3934
        foreach ($fromFkeys as $key1 => $constraint1) {
277 3608
            foreach ($toFkeys as $key2 => $constraint2) {
278 3601
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
279 3581
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
280
                } else {
281 3556
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
282 876
                        $tableDifferences->changedForeignKeys[] = $constraint2;
283 876
                        $changes++;
284 876
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
285
                    }
286
                }
287
            }
288
        }
289
290 3934
        foreach ($fromFkeys as $constraint1) {
291 3561
            $tableDifferences->removedForeignKeys[] = $constraint1;
292 3561
            $changes++;
293
        }
294
295 3934
        foreach ($toFkeys as $constraint2) {
296 3555
            $tableDifferences->addedForeignKeys[] = $constraint2;
297 3555
            $changes++;
298
        }
299
300 3934
        return $changes ? $tableDifferences : false;
301
    }
302
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
     *
307
     * @return void
308
     */
309 3934
    private function detectColumnRenamings(TableDiff $tableDifferences)
310
    {
311 3934
        $renameCandidates = [];
312 3934
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
313 3739
            foreach ($tableDifferences->removedColumns as $removedColumn) {
314 3576
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
315 3193
                    continue;
316
                }
317
318 3576
                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
319
            }
320
        }
321
322 3934
        foreach ($renameCandidates as $candidateColumns) {
323 3576
            if (count($candidateColumns) !== 1) {
324 645
                continue;
325
            }
326
327 3575
            [$removedColumn, $addedColumn] = $candidateColumns[0];
328 3575
            $removedColumnName             = strtolower($removedColumn->getName());
329 3575
            $addedColumnName               = strtolower($addedColumn->getName());
330
331 3575
            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
332 1105
                continue;
333
            }
334
335 3575
            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
336
            unset(
337 3575
                $tableDifferences->addedColumns[$addedColumnName],
338 3575
                $tableDifferences->removedColumns[$removedColumnName]
339
            );
340
        }
341 3934
    }
342
343
    /**
344
     * Try to find indexes that only changed their name, rename operations maybe cheaper than add/drop
345
     * however ambiguities between different possibilities should not lead to renaming at all.
346
     *
347
     * @return void
348
     */
349 3934
    private function detectIndexRenamings(TableDiff $tableDifferences)
350
    {
351 3934
        $renameCandidates = [];
352
353
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
354 3934
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
355 3678
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
356 3645
                if ($this->diffIndex($addedIndex, $removedIndex)) {
357 3433
                    continue;
358
                }
359
360 3533
                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
361
            }
362
        }
363
364 3934
        foreach ($renameCandidates as $candidateIndexes) {
365
            // If the current rename candidate contains exactly one semantically equal index,
366
            // we can safely rename it.
367
            // Otherwise it is unclear if a rename action is really intended,
368
            // therefore we let those ambiguous indexes be added/dropped.
369 3533
            if (count($candidateIndexes) !== 1) {
370 599
                continue;
371
            }
372
373 3532
            [$removedIndex, $addedIndex] = $candidateIndexes[0];
374
375 3532
            $removedIndexName = strtolower($removedIndex->getName());
376 3532
            $addedIndexName   = strtolower($addedIndex->getName());
377
378 3532
            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
379
                continue;
380
            }
381
382 3532
            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
383
            unset(
384 3532
                $tableDifferences->addedIndexes[$addedIndexName],
385 3532
                $tableDifferences->removedIndexes[$removedIndexName]
386
            );
387
        }
388 3934
    }
389
390
    /**
391
     * @return bool
392
     */
393 3604
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
394
    {
395 3604
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
396 3554
            return true;
397
        }
398
399 3586
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
400
            return true;
401
        }
402
403 3586
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
404 852
            return true;
405
        }
406
407 3585
        if ($key1->onUpdate() !== $key2->onUpdate()) {
408 875
            return true;
409
        }
410
411 3584
        return $key1->onDelete() !== $key2->onDelete();
412
    }
413
414
    /**
415
     * Returns the difference between the fields $field1 and $field2.
416
     *
417
     * If there are differences this method returns $field2, otherwise the
418
     * boolean false.
419
     *
420
     * @return string[]
421
     */
422 3953
    public function diffColumn(Column $column1, Column $column2)
423
    {
424 3953
        $properties1 = $column1->toArray();
425 3953
        $properties2 = $column2->toArray();
426
427 3953
        $changedProperties = [];
428
429 3953
        if (get_class($properties1['type']) !== get_class($properties2['type'])) {
430 3409
            $changedProperties[] = 'type';
431
        }
432
433 3953
        foreach (['notnull', 'unsigned', 'autoincrement'] as $property) {
434 3953
            if ($properties1[$property] === $properties2[$property]) {
435 3953
                continue;
436
            }
437
438 2499
            $changedProperties[] = $property;
439
        }
440
441
        // This is a very nasty hack to make comparator work with the legacy json_array type, which should be killed in v3
442 3953
        if ($this->isALegacyJsonComparison($properties1['type'], $properties2['type'])) {
0 ignored issues
show
Deprecated Code introduced by
The function Doctrine\DBAL\Schema\Com...ALegacyJsonComparison() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

442
        if (/** @scrutinizer ignore-deprecated */ $this->isALegacyJsonComparison($properties1['type'], $properties2['type'])) {
Loading history...
443 3268
            array_shift($changedProperties);
444
445 3268
            $changedProperties[] = 'comment';
446
        }
447
448
        // Null values need to be checked additionally as they tell whether to create or drop a default value.
449
        // null != 0, null != false, null != '' etc. This affects platform's table alteration SQL generation.
450 3953
        if (($properties1['default'] === null) !== ($properties2['default'] === null)
451 3953
            || $properties1['default'] != $properties2['default']) {
452 3574
            $changedProperties[] = 'default';
453
        }
454
455 3953
        if (($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
456 3953
            $properties1['type'] instanceof Types\BinaryType
457
        ) {
458
            // check if value of length is set at all, default value assumed otherwise.
459 3784
            $length1 = $properties1['length'] ?: 255;
460 3784
            $length2 = $properties2['length'] ?: 255;
461 3784
            if ($length1 !== $length2) {
462 2960
                $changedProperties[] = 'length';
463
            }
464
465 3784
            if ($properties1['fixed'] !== $properties2['fixed']) {
466 3784
                $changedProperties[] = 'fixed';
467
            }
468 3935
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
469 3576
            if (($properties1['precision'] ?: 10) !== ($properties2['precision'] ?: 10)) {
470
                $changedProperties[] = 'precision';
471
            }
472
473 3576
            if ($properties1['scale'] !== $properties2['scale']) {
474
                $changedProperties[] = 'scale';
475
            }
476
        }
477
478
        // A null value and an empty string are actually equal for a comment so they should not trigger a change.
479 3953
        if ($properties1['comment'] !== $properties2['comment'] &&
480 3953
            ! ($properties1['comment'] === null && $properties2['comment'] === '') &&
481 3953
            ! ($properties2['comment'] === null && $properties1['comment'] === '')
482
        ) {
483 3530
            $changedProperties[] = 'comment';
484
        }
485
486 3953
        $customOptions1 = $column1->getCustomSchemaOptions();
487 3953
        $customOptions2 = $column2->getCustomSchemaOptions();
488
489 3953
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
490 1129
            if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
491 1128
                $changedProperties[] = $key;
492 1129
            } elseif ($properties1[$key] !== $properties2[$key]) {
493
                $changedProperties[] = $key;
494
            }
495
        }
496
497 3953
        $platformOptions1 = $column1->getPlatformOptions();
498 3953
        $platformOptions2 = $column2->getPlatformOptions();
499
500 3953
        foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
501 2127
            if ($properties1[$key] === $properties2[$key]) {
502 2127
                continue;
503
            }
504
505 2034
            $changedProperties[] = $key;
506
        }
507
508 3953
        return array_unique($changedProperties);
509
    }
510
511
    /**
512
     * TODO: kill with fire on v3.0
513
     *
514
     * @deprecated
515
     */
516 3953
    private function isALegacyJsonComparison(Types\Type $one, Types\Type $other) : bool
517
    {
518 3953
        if (! $one instanceof Types\JsonType || ! $other instanceof Types\JsonType) {
519 3951
            return false;
520
        }
521
522 3292
        return ( ! $one instanceof Types\JsonArrayType && $other instanceof Types\JsonArrayType)
523 3292
            || ( ! $other instanceof Types\JsonArrayType && $one instanceof Types\JsonArrayType);
524
    }
525
526
    /**
527
     * Finds the difference between the indexes $index1 and $index2.
528
     *
529
     * Compares $index1 with $index2 and returns $index2 if there are any
530
     * differences or false in case there are no differences.
531
     *
532
     * @return bool
533
     */
534 3798
    public function diffIndex(Index $index1, Index $index2)
535
    {
536 3798
        return ! ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1));
537
    }
538
}
539