Comparator::diffTable()   F
last analyzed

Complexity

Conditions 24
Paths 8640

Size

Total Lines 101

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 24
nc 8640
nop 2
dl 0
loc 101
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\DBAL\Schema;
21
22
use Doctrine\DBAL\Types;
23
use function array_intersect_key;
24
use function array_key_exists;
25
use function array_keys;
26
use function array_map;
27
use function array_merge;
28
use function array_shift;
29
use function array_unique;
30
use function count;
31
use function strtolower;
32
33
/**
34
 * Compares two Schemas and return an instance of SchemaDiff.
35
 *
36
 * @link   www.doctrine-project.org
37
 * @since  2.0
38
 * @author Benjamin Eberlei <[email protected]>
39
 */
40
class Comparator
41
{
42
    /**
43
     * @param \Doctrine\DBAL\Schema\Schema $fromSchema
44
     * @param \Doctrine\DBAL\Schema\Schema $toSchema
45
     *
46
     * @return \Doctrine\DBAL\Schema\SchemaDiff
47
     */
48
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema)
49
    {
50
        $c = new self();
51
52
        return $c->compare($fromSchema, $toSchema);
53
    }
54
55
    /**
56
     * Returns a SchemaDiff object containing the differences between the schemas $fromSchema and $toSchema.
57
     *
58
     * The returned differences are returned in such a way that they contain the
59
     * operations to change the schema stored in $fromSchema to the schema that is
60
     * stored in $toSchema.
61
     *
62
     * @param \Doctrine\DBAL\Schema\Schema $fromSchema
63
     * @param \Doctrine\DBAL\Schema\Schema $toSchema
64
     *
65
     * @return \Doctrine\DBAL\Schema\SchemaDiff
66
     */
67
    public function compare(Schema $fromSchema, Schema $toSchema)
68
    {
69
        $diff = new SchemaDiff();
70
        $diff->fromSchema = $fromSchema;
71
72
        $foreignKeysToTable = [];
73
74
        foreach ($toSchema->getNamespaces() as $namespace) {
75
            if ( ! $fromSchema->hasNamespace($namespace)) {
76
                $diff->newNamespaces[$namespace] = $namespace;
77
            }
78
        }
79
80
        foreach ($fromSchema->getNamespaces() as $namespace) {
81
            if ( ! $toSchema->hasNamespace($namespace)) {
82
                $diff->removedNamespaces[$namespace] = $namespace;
83
            }
84
        }
85
86
        foreach ($toSchema->getTables() as $table) {
87
            $tableName = $table->getShortestName($toSchema->getName());
88
            if ( ! $fromSchema->hasTable($tableName)) {
89
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
90
            } else {
91
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
92
                if ($tableDifferences !== false) {
93
                    $diff->changedTables[$tableName] = $tableDifferences;
94
                }
95
            }
96
        }
97
98
        /* Check if there are tables removed */
99
        foreach ($fromSchema->getTables() as $table) {
100
            $tableName = $table->getShortestName($fromSchema->getName());
101
102
            $table = $fromSchema->getTable($tableName);
103
            if ( ! $toSchema->hasTable($tableName)) {
104
                $diff->removedTables[$tableName] = $table;
105
            }
106
107
            // also remember all foreign keys that point to a specific table
108
            foreach ($table->getForeignKeys() as $foreignKey) {
109
                $foreignTable = strtolower($foreignKey->getForeignTableName());
110
                if (!isset($foreignKeysToTable[$foreignTable])) {
111
                    $foreignKeysToTable[$foreignTable] = [];
112
                }
113
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
114
            }
115
        }
116
117
        foreach ($diff->removedTables as $tableName => $table) {
118
            if (isset($foreignKeysToTable[$tableName])) {
119
                $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
120
121
                // deleting duplicated foreign keys present on both on the orphanedForeignKey
122
                // and the removedForeignKeys from changedTables
123
                foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
124
                    // strtolower the table name to make if compatible with getShortestName
125
                    $localTableName = strtolower($foreignKey->getLocalTableName());
126
                    if (isset($diff->changedTables[$localTableName])) {
127
                        foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
128
                            // We check if the key is from the removed table if not we skip.
129
                            if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
130
                                continue;
131
                            }
132
                            unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
133
                        }
134
                    }
135
                }
136
            }
137
        }
138
139
        foreach ($toSchema->getSequences() as $sequence) {
140
            $sequenceName = $sequence->getShortestName($toSchema->getName());
141
            if ( ! $fromSchema->hasSequence($sequenceName)) {
142
                if ( ! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
143
                    $diff->newSequences[] = $sequence;
144
                }
145
            } else {
146
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
147
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
148
                }
149
            }
150
        }
151
152
        foreach ($fromSchema->getSequences() as $sequence) {
153
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
154
                continue;
155
            }
156
157
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
158
159
            if ( ! $toSchema->hasSequence($sequenceName)) {
160
                $diff->removedSequences[] = $sequence;
161
            }
162
        }
163
164
        return $diff;
165
    }
166
167
    /**
168
     * @param \Doctrine\DBAL\Schema\Schema   $schema
169
     * @param \Doctrine\DBAL\Schema\Sequence $sequence
170
     *
171
     * @return bool
172
     */
173
    private function isAutoIncrementSequenceInSchema($schema, $sequence)
174
    {
175
        foreach ($schema->getTables() as $table) {
176
            if ($sequence->isAutoIncrementsFor($table)) {
177
                return true;
178
            }
179
        }
180
181
        return false;
182
    }
183
184
    /**
185
     * @param \Doctrine\DBAL\Schema\Sequence $sequence1
186
     * @param \Doctrine\DBAL\Schema\Sequence $sequence2
187
     *
188
     * @return bool
189
     */
190
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
191
    {
192
        if ($sequence1->getAllocationSize() != $sequence2->getAllocationSize()) {
193
            return true;
194
        }
195
196
        return $sequence1->getInitialValue() !== $sequence2->getInitialValue();
197
    }
198
199
    /**
200
     * Returns the difference between the tables $table1 and $table2.
201
     *
202
     * If there are no differences this method returns the boolean false.
203
     *
204
     * @param \Doctrine\DBAL\Schema\Table $table1
205
     * @param \Doctrine\DBAL\Schema\Table $table2
206
     *
207
     * @return TableDiff|false
208
     */
209
    public function diffTable(Table $table1, Table $table2)
210
    {
211
        $changes = 0;
212
        $tableDifferences = new TableDiff($table1->getName());
213
        $tableDifferences->fromTable = $table1;
214
215
        $table1Columns = $table1->getColumns();
216
        $table2Columns = $table2->getColumns();
217
218
        /* See if all the fields in table 1 exist in table 2 */
219
        foreach ($table2Columns as $columnName => $column) {
220
            if ( !$table1->hasColumn($columnName)) {
221
                $tableDifferences->addedColumns[$columnName] = $column;
222
                $changes++;
223
            }
224
        }
225
        /* See if there are any removed fields in table 2 */
226
        foreach ($table1Columns as $columnName => $column) {
227
            // See if column is removed in table 2.
228
            if ( ! $table2->hasColumn($columnName)) {
229
                $tableDifferences->removedColumns[$columnName] = $column;
230
                $changes++;
231
                continue;
232
            }
233
234
            // See if column has changed properties in table 2.
235
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));
236
237
            if ( ! empty($changedProperties)) {
238
                $columnDiff = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
239
                $columnDiff->fromColumn = $column;
240
                $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
241
                $changes++;
242
            }
243
        }
244
245
        $this->detectColumnRenamings($tableDifferences);
246
247
        $table1Indexes = $table1->getIndexes();
248
        $table2Indexes = $table2->getIndexes();
249
250
        /* See if all the indexes in table 1 exist in table 2 */
251
        foreach ($table2Indexes as $indexName => $index) {
252
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
253
                continue;
254
            }
255
256
            $tableDifferences->addedIndexes[$indexName] = $index;
257
            $changes++;
258
        }
259
        /* See if there are any removed indexes in table 2 */
260
        foreach ($table1Indexes as $indexName => $index) {
261
            // See if index is removed in table 2.
262
            if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
263
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
264
            ) {
265
                $tableDifferences->removedIndexes[$indexName] = $index;
266
                $changes++;
267
                continue;
268
            }
269
270
            // See if index has changed in table 2.
271
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
272
273
            if ($this->diffIndex($index, $table2Index)) {
274
                $tableDifferences->changedIndexes[$indexName] = $table2Index;
275
                $changes++;
276
            }
277
        }
278
279
        $this->detectIndexRenamings($tableDifferences);
280
281
        $fromFkeys = $table1->getForeignKeys();
282
        $toFkeys = $table2->getForeignKeys();
283
284
        foreach ($fromFkeys as $key1 => $constraint1) {
285
            foreach ($toFkeys as $key2 => $constraint2) {
286
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
287
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
288
                } else {
289
                    if (strtolower($constraint1->getName()) == strtolower($constraint2->getName())) {
290
                        $tableDifferences->changedForeignKeys[] = $constraint2;
291
                        $changes++;
292
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
293
                    }
294
                }
295
            }
296
        }
297
298
        foreach ($fromFkeys as $constraint1) {
299
            $tableDifferences->removedForeignKeys[] = $constraint1;
300
            $changes++;
301
        }
302
303
        foreach ($toFkeys as $constraint2) {
304
            $tableDifferences->addedForeignKeys[] = $constraint2;
305
            $changes++;
306
        }
307
308
        return $changes ? $tableDifferences : false;
309
    }
310
311
    /**
312
     * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
313
     * however ambiguities between different possibilities should not lead to renaming at all.
314
     *
315
     * @return void
316
     */
317 View Code Duplication
    private function detectColumnRenamings(TableDiff $tableDifferences)
318
    {
319
        $renameCandidates = [];
320
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
321
            foreach ($tableDifferences->removedColumns as $removedColumn) {
322
                if (count($this->diffColumn($addedColumn, $removedColumn)) == 0) {
323
                    $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
324
                }
325
            }
326
        }
327
328
        foreach ($renameCandidates as $candidateColumns) {
329
            if (count($candidateColumns) == 1) {
330
                list($removedColumn, $addedColumn) = $candidateColumns[0];
331
                $removedColumnName = strtolower($removedColumn->getName());
332
                $addedColumnName = strtolower($addedColumn->getName());
333
334
                if ( ! isset($tableDifferences->renamedColumns[$removedColumnName])) {
335
                    $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
336
                    unset(
337
                        $tableDifferences->addedColumns[$addedColumnName],
338
                        $tableDifferences->removedColumns[$removedColumnName]
339
                    );
340
                }
341
            }
342
        }
343
    }
344
345
    /**
346
     * Try to find indexes that only changed their name, rename operations maybe cheaper than add/drop
347
     * however ambiguities between different possibilities should not lead to renaming at all.
348
     *
349
     * @return void
350
     */
351 View Code Duplication
    private function detectIndexRenamings(TableDiff $tableDifferences)
352
    {
353
        $renameCandidates = [];
354
355
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
356
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
357
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
358
                if (! $this->diffIndex($addedIndex, $removedIndex)) {
359
                    $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
360
                }
361
            }
362
        }
363
364
        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
            if (count($candidateIndexes) === 1) {
370
                list($removedIndex, $addedIndex) = $candidateIndexes[0];
371
372
                $removedIndexName = strtolower($removedIndex->getName());
373
                $addedIndexName = strtolower($addedIndex->getName());
374
375
                if (! isset($tableDifferences->renamedIndexes[$removedIndexName])) {
376
                    $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
377
                    unset(
378
                        $tableDifferences->addedIndexes[$addedIndexName],
379
                        $tableDifferences->removedIndexes[$removedIndexName]
380
                    );
381
                }
382
            }
383
        }
384
    }
385
386
    /**
387
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $key1
388
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $key2
389
     *
390
     * @return bool
391
     */
392
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
393
    {
394
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) != array_map('strtolower', $key2->getUnquotedLocalColumns())) {
395
            return true;
396
        }
397
398
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) != array_map('strtolower', $key2->getUnquotedForeignColumns())) {
399
            return true;
400
        }
401
402
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
403
            return true;
404
        }
405
406
        if ($key1->onUpdate() != $key2->onUpdate()) {
407
            return true;
408
        }
409
410
        return $key1->onDelete() !== $key2->onDelete();
411
    }
412
413
    /**
414
     * Returns the difference between the fields $field1 and $field2.
415
     *
416
     * If there are differences this method returns $field2, otherwise the
417
     * boolean false.
418
     *
419
     * @param \Doctrine\DBAL\Schema\Column $column1
420
     * @param \Doctrine\DBAL\Schema\Column $column2
421
     *
422
     * @return array
423
     */
424
    public function diffColumn(Column $column1, Column $column2)
425
    {
426
        $properties1 = $column1->toArray();
427
        $properties2 = $column2->toArray();
428
429
        $changedProperties = [];
430
431
        foreach (['type', 'notnull', 'unsigned', 'autoincrement'] as $property) {
432
            if ($properties1[$property] != $properties2[$property]) {
433
                $changedProperties[] = $property;
434
            }
435
        }
436
437
        // This is a very nasty hack to make comparator work with the legacy json_array type, which should be killed in v3
438
        if ($this->isALegacyJsonComparison($properties1['type'], $properties2['type'])) {
0 ignored issues
show
Deprecated Code introduced by
The method Doctrine\DBAL\Schema\Com...ALegacyJsonComparison() has been deprecated.

This method has been deprecated.

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