Failed Conditions
Push — master ( 0dbcf1...e125a4 )
by Marco
19:24
created

Comparator::detectColumnRenamings()   C

Complexity

Conditions 7
Paths 16

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 15
cts 15
cp 1
rs 6.9811
c 0
b 0
f 0
cc 7
eloc 15
nc 16
nop 1
crap 7
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
24
/**
25
 * Compares two Schemas and return an instance of SchemaDiff.
26
 *
27
 * @link   www.doctrine-project.org
28
 * @since  2.0
29
 * @author Benjamin Eberlei <[email protected]>
30
 */
31
class Comparator
32
{
33
    /**
34
     * @param \Doctrine\DBAL\Schema\Schema $fromSchema
35
     * @param \Doctrine\DBAL\Schema\Schema $toSchema
36
     *
37
     * @return \Doctrine\DBAL\Schema\SchemaDiff
38
     */
39 17
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema)
40
    {
41 17
        $c = new self();
42
43 17
        return $c->compare($fromSchema, $toSchema);
44
    }
45
46
    /**
47
     * Returns a SchemaDiff object containing the differences between the schemas $fromSchema and $toSchema.
48
     *
49
     * The returned differences are returned in such a way that they contain the
50
     * operations to change the schema stored in $fromSchema to the schema that is
51
     * stored in $toSchema.
52
     *
53
     * @param \Doctrine\DBAL\Schema\Schema $fromSchema
54
     * @param \Doctrine\DBAL\Schema\Schema $toSchema
55
     *
56
     * @return \Doctrine\DBAL\Schema\SchemaDiff
57
     */
58 27
    public function compare(Schema $fromSchema, Schema $toSchema)
59
    {
60 27
        $diff = new SchemaDiff();
61 27
        $diff->fromSchema = $fromSchema;
62
63 27
        $foreignKeysToTable = [];
64
65 27
        foreach ($toSchema->getNamespaces() as $namespace) {
66 2
            if ( ! $fromSchema->hasNamespace($namespace)) {
67 2
                $diff->newNamespaces[$namespace] = $namespace;
68
            }
69
        }
70
71 27
        foreach ($fromSchema->getNamespaces() as $namespace) {
72 2
            if ( ! $toSchema->hasNamespace($namespace)) {
73 2
                $diff->removedNamespaces[$namespace] = $namespace;
74
            }
75
        }
76
77 27
        foreach ($toSchema->getTables() as $table) {
78 21
            $tableName = $table->getShortestName($toSchema->getName());
79 21
            if ( ! $fromSchema->hasTable($tableName)) {
80 5
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
81
            } else {
82 19
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
83 19
                if ($tableDifferences !== false) {
84 21
                    $diff->changedTables[$tableName] = $tableDifferences;
85
                }
86
            }
87
        }
88
89
        /* Check if there are tables removed */
90 27
        foreach ($fromSchema->getTables() as $table) {
91 20
            $tableName = $table->getShortestName($fromSchema->getName());
92
93 20
            $table = $fromSchema->getTable($tableName);
94 20
            if ( ! $toSchema->hasTable($tableName)) {
95 5
                $diff->removedTables[$tableName] = $table;
96
            }
97
98
            // also remember all foreign keys that point to a specific table
99 20
            foreach ($table->getForeignKeys() as $foreignKey) {
100 2
                $foreignTable = strtolower($foreignKey->getForeignTableName());
101 2
                if (!isset($foreignKeysToTable[$foreignTable])) {
102 2
                    $foreignKeysToTable[$foreignTable] = [];
103
                }
104 20
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
105
            }
106
        }
107
108 27
        foreach ($diff->removedTables as $tableName => $table) {
109 5
            if (isset($foreignKeysToTable[$tableName])) {
110 2
                $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
111
112
                // deleting duplicated foreign keys present on both on the orphanedForeignKey
113
                // and the removedForeignKeys from changedTables
114 2
                foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
115
                    // strtolower the table name to make if compatible with getShortestName
116 2
                    $localTableName = strtolower($foreignKey->getLocalTableName());
117 2
                    if (isset($diff->changedTables[$localTableName])) {
118 2
                        foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
119
                            // We check if the key is from the removed table if not we skip.
120 2
                            if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
121 1
                                continue;
122
                            }
123 5
                            unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
124
                        }
125
                    }
126
                }
127
            }
128
        }
129
130 27
        foreach ($toSchema->getSequences() as $sequence) {
131 4
            $sequenceName = $sequence->getShortestName($toSchema->getName());
132 4
            if ( ! $fromSchema->hasSequence($sequenceName)) {
133 3
                if ( ! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
134 3
                    $diff->newSequences[] = $sequence;
135
                }
136
            } else {
137 2
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
138 4
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
139
                }
140
            }
141
        }
142
143 27
        foreach ($fromSchema->getSequences() as $sequence) {
144 4
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
145 1
                continue;
146
            }
147
148 3
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
149
150 3
            if ( ! $toSchema->hasSequence($sequenceName)) {
151 3
                $diff->removedSequences[] = $sequence;
152
            }
153
        }
154
155 27
        return $diff;
156
    }
157
158
    /**
159
     * @param \Doctrine\DBAL\Schema\Schema   $schema
160
     * @param \Doctrine\DBAL\Schema\Sequence $sequence
161
     *
162
     * @return bool
163
     */
164 6
    private function isAutoIncrementSequenceInSchema($schema, $sequence)
165
    {
166 6
        foreach ($schema->getTables() as $table) {
167 2
            if ($sequence->isAutoIncrementsFor($table)) {
168 2
                return true;
169
            }
170
        }
171
172 4
        return false;
173
    }
174
175
    /**
176
     * @param \Doctrine\DBAL\Schema\Sequence $sequence1
177
     * @param \Doctrine\DBAL\Schema\Sequence $sequence2
178
     *
179
     * @return bool
180
     */
181 3
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
182
    {
183 3
        if ($sequence1->getAllocationSize() != $sequence2->getAllocationSize()) {
184 2
            return true;
185
        }
186
187 2
        return $sequence1->getInitialValue() !== $sequence2->getInitialValue();
188
    }
189
190
    /**
191
     * Returns the difference between the tables $table1 and $table2.
192
     *
193
     * If there are no differences this method returns the boolean false.
194
     *
195
     * @param \Doctrine\DBAL\Schema\Table $table1
196
     * @param \Doctrine\DBAL\Schema\Table $table2
197
     *
198
     * @return bool|\Doctrine\DBAL\Schema\TableDiff
199
     */
200 127
    public function diffTable(Table $table1, Table $table2)
201
    {
202 127
        $changes = 0;
203 127
        $tableDifferences = new TableDiff($table1->getName());
204 127
        $tableDifferences->fromTable = $table1;
205
206 127
        $table1Columns = $table1->getColumns();
207 127
        $table2Columns = $table2->getColumns();
208
209
        /* See if all the fields in table 1 exist in table 2 */
210 127
        foreach ($table2Columns as $columnName => $column) {
211 122
            if ( !$table1->hasColumn($columnName)) {
212 30
                $tableDifferences->addedColumns[$columnName] = $column;
213 122
                $changes++;
214
            }
215
        }
216
        /* See if there are any removed fields in table 2 */
217 127
        foreach ($table1Columns as $columnName => $column) {
218
            // See if column is removed in table 2.
219 122
            if ( ! $table2->hasColumn($columnName)) {
220 30
                $tableDifferences->removedColumns[$columnName] = $column;
221 30
                $changes++;
222 30
                continue;
223
            }
224
225
            // See if column has changed properties in table 2.
226 101
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));
227
228 101
            if ( ! empty($changedProperties)) {
229 45
                $columnDiff = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
230 45
                $columnDiff->fromColumn = $column;
231 45
                $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
232 101
                $changes++;
233
            }
234
        }
235
236 127
        $this->detectColumnRenamings($tableDifferences);
237
238 127
        $table1Indexes = $table1->getIndexes();
239 127
        $table2Indexes = $table2->getIndexes();
240
241
        /* See if all the indexes in table 1 exist in table 2 */
242 127
        foreach ($table2Indexes as $indexName => $index) {
243 50
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
244 34
                continue;
245
            }
246
247 16
            $tableDifferences->addedIndexes[$indexName] = $index;
248 16
            $changes++;
249
        }
250
        /* See if there are any removed indexes in table 2 */
251 127
        foreach ($table1Indexes as $indexName => $index) {
252
            // See if index is removed in table 2.
253 47
            if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
254 47
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
255
            ) {
256 18
                $tableDifferences->removedIndexes[$indexName] = $index;
257 18
                $changes++;
258 18
                continue;
259
            }
260
261
            // See if index has changed in table 2.
262 34
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
263
264 34
            if ($this->diffIndex($index, $table2Index)) {
0 ignored issues
show
Bug introduced by
It seems like $table2Index can also be of type null; however, parameter $index2 of Doctrine\DBAL\Schema\Comparator::diffIndex() does only seem to accept Doctrine\DBAL\Schema\Index, maybe add an additional type check? ( Ignorable by Annotation )

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

264
            if ($this->diffIndex($index, /** @scrutinizer ignore-type */ $table2Index)) {
Loading history...
265 15
                $tableDifferences->changedIndexes[$indexName] = $table2Index;
266 34
                $changes++;
267
            }
268
        }
269
270 127
        $this->detectIndexRenamings($tableDifferences);
271
272 127
        $fromFkeys = $table1->getForeignKeys();
273 127
        $toFkeys = $table2->getForeignKeys();
274
275 127
        foreach ($fromFkeys as $key1 => $constraint1) {
276 11
            foreach ($toFkeys as $key2 => $constraint2) {
277 4
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
278 1
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
279
                } else {
280 3
                    if (strtolower($constraint1->getName()) == strtolower($constraint2->getName())) {
281 2
                        $tableDifferences->changedForeignKeys[] = $constraint2;
282 2
                        $changes++;
283 11
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
284
                    }
285
                }
286
            }
287
        }
288
289 127
        foreach ($fromFkeys as $constraint1) {
290 8
            $tableDifferences->removedForeignKeys[] = $constraint1;
291 8
            $changes++;
292
        }
293
294 127
        foreach ($toFkeys as $constraint2) {
295 2
            $tableDifferences->addedForeignKeys[] = $constraint2;
296 2
            $changes++;
297
        }
298
299 127
        return $changes ? $tableDifferences : false;
300
    }
301
302
    /**
303
     * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
304
     * however ambiguities between different possibilities should not lead to renaming at all.
305
     *
306
     * @param \Doctrine\DBAL\Schema\TableDiff $tableDifferences
307
     *
308
     * @return void
309
     */
310 127
    private function detectColumnRenamings(TableDiff $tableDifferences)
311
    {
312 127
        $renameCandidates = [];
313 127
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
314 30
            foreach ($tableDifferences->removedColumns as $removedColumn) {
315 23
                if (count($this->diffColumn($addedColumn, $removedColumn)) == 0) {
316 30
                    $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
317
                }
318
            }
319
        }
320
321 127
        foreach ($renameCandidates as $candidateColumns) {
322 23
            if (count($candidateColumns) == 1) {
323 22
                list($removedColumn, $addedColumn) = $candidateColumns[0];
324 22
                $removedColumnName = strtolower($removedColumn->getName());
325 22
                $addedColumnName = strtolower($addedColumn->getName());
326
327 22
                if ( ! isset($tableDifferences->renamedColumns[$removedColumnName])) {
328 22
                    $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
329
                    unset(
330 22
                        $tableDifferences->addedColumns[$addedColumnName],
331 23
                        $tableDifferences->removedColumns[$removedColumnName]
332
                    );
333
                }
334
            }
335
        }
336 127
    }
337
338
    /**
339
     * Try to find indexes that only changed their name, rename operations maybe cheaper than add/drop
340
     * however ambiguities between different possibilities should not lead to renaming at all.
341
     *
342
     * @param \Doctrine\DBAL\Schema\TableDiff $tableDifferences
343
     *
344
     * @return void
345
     */
346 127
    private function detectIndexRenamings(TableDiff $tableDifferences)
347
    {
348 127
        $renameCandidates = [];
349
350
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
351 127
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
352 16
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
353 7
                if (! $this->diffIndex($addedIndex, $removedIndex)) {
354 16
                    $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
355
                }
356
            }
357
        }
358
359 127
        foreach ($renameCandidates as $candidateIndexes) {
360
            // If the current rename candidate contains exactly one semantically equal index,
361
            // we can safely rename it.
362
            // Otherwise it is unclear if a rename action is really intended,
363
            // therefore we let those ambiguous indexes be added/dropped.
364 3
            if (count($candidateIndexes) === 1) {
365 2
                list($removedIndex, $addedIndex) = $candidateIndexes[0];
366
367 2
                $removedIndexName = strtolower($removedIndex->getName());
368 2
                $addedIndexName = strtolower($addedIndex->getName());
369
370 2
                if (! isset($tableDifferences->renamedIndexes[$removedIndexName])) {
371 2
                    $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
372
                    unset(
373 2
                        $tableDifferences->addedIndexes[$addedIndexName],
374 3
                        $tableDifferences->removedIndexes[$removedIndexName]
375
                    );
376
                }
377
            }
378
        }
379 127
    }
380
381
    /**
382
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $key1
383
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $key2
384
     *
385
     * @return bool
386
     */
387 7
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
388
    {
389 7
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) != array_map('strtolower', $key2->getUnquotedLocalColumns())) {
390 1
            return true;
391
        }
392
393 6
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) != array_map('strtolower', $key2->getUnquotedForeignColumns())) {
394
            return true;
395
        }
396
397 6
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
398 1
            return true;
399
        }
400
401 5
        if ($key1->onUpdate() != $key2->onUpdate()) {
402 1
            return true;
403
        }
404
405 4
        return $key1->onDelete() !== $key2->onDelete();
406
    }
407
408
    /**
409
     * Returns the difference between the fields $field1 and $field2.
410
     *
411
     * If there are differences this method returns $field2, otherwise the
412
     * boolean false.
413
     *
414
     * @param \Doctrine\DBAL\Schema\Column $column1
415
     * @param \Doctrine\DBAL\Schema\Column $column2
416
     *
417
     * @return array
418
     */
419 144
    public function diffColumn(Column $column1, Column $column2)
420
    {
421 144
        $properties1 = $column1->toArray();
422 144
        $properties2 = $column2->toArray();
423
424 144
        $changedProperties = [];
425
426 144
        foreach (['type', 'notnull', 'unsigned', 'autoincrement'] as $property) {
427 144
            if ($properties1[$property] != $properties2[$property]) {
428 144
                $changedProperties[] = $property;
429
            }
430
        }
431
432
        // This is a very nasty hack to make comparator work with the legacy json_array type, which should be killed in v3
433 144
        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

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