Comparator.php 19 KB
Newer Older
1 2 3 4
<?php

namespace Doctrine\DBAL\Schema;

5
use Doctrine\DBAL\Types;
6 7 8 9 10 11 12 13
use function array_intersect_key;
use function array_key_exists;
use function array_keys;
use function array_map;
use function array_merge;
use function array_shift;
use function array_unique;
use function count;
14
use function get_class;
15
use function strtolower;
16

17
/**
Benjamin Morel's avatar
Benjamin Morel committed
18
 * Compares two Schemas and return an instance of SchemaDiff.
19 20 21 22
 */
class Comparator
{
    /**
23
     * @return SchemaDiff
24
     */
25
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema)
26 27
    {
        $c = new self();
Benjamin Morel's avatar
Benjamin Morel committed
28

29 30 31 32 33 34
        return $c->compare($fromSchema, $toSchema);
    }

    /**
     * Returns a SchemaDiff object containing the differences between the schemas $fromSchema and $toSchema.
     *
35
     * The returned differences are returned in such a way that they contain the
36 37 38
     * operations to change the schema stored in $fromSchema to the schema that is
     * stored in $toSchema.
     *
39
     * @return SchemaDiff
40
     */
41
    public function compare(Schema $fromSchema, Schema $toSchema)
42
    {
43
        $diff             = new SchemaDiff();
44
        $diff->fromSchema = $fromSchema;
45

46
        $foreignKeysToTable = [];
47

48
        foreach ($toSchema->getNamespaces() as $namespace) {
49 50
            if ($fromSchema->hasNamespace($namespace)) {
                continue;
Marco Pivetta's avatar
Marco Pivetta committed
51
            }
52 53

            $diff->newNamespaces[$namespace] = $namespace;
54 55 56
        }

        foreach ($fromSchema->getNamespaces() as $namespace) {
57 58
            if ($toSchema->hasNamespace($namespace)) {
                continue;
59
            }
60 61

            $diff->removedNamespaces[$namespace] = $namespace;
62
        }
Marco Pivetta's avatar
Marco Pivetta committed
63

64
        foreach ($toSchema->getTables() as $table) {
65
            $tableName = $table->getShortestName($toSchema->getName());
66
            if (! $fromSchema->hasTable($tableName)) {
67
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
68
            } else {
69 70
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
                if ($tableDifferences !== false) {
71 72 73 74 75 76
                    $diff->changedTables[$tableName] = $tableDifferences;
                }
            }
        }

        /* Check if there are tables removed */
77
        foreach ($fromSchema->getTables() as $table) {
78 79 80
            $tableName = $table->getShortestName($fromSchema->getName());

            $table = $fromSchema->getTable($tableName);
81
            if (! $toSchema->hasTable($tableName)) {
82 83
                $diff->removedTables[$tableName] = $table;
            }
84 85

            // also remember all foreign keys that point to a specific table
86
            foreach ($table->getForeignKeys() as $foreignKey) {
87
                $foreignTable = strtolower($foreignKey->getForeignTableName());
88
                if (! isset($foreignKeysToTable[$foreignTable])) {
89
                    $foreignKeysToTable[$foreignTable] = [];
90 91 92 93 94
                }
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
            }
        }

95
        foreach ($diff->removedTables as $tableName => $table) {
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
            if (! isset($foreignKeysToTable[$tableName])) {
                continue;
            }

            $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);

            // deleting duplicated foreign keys present on both on the orphanedForeignKey
            // and the removedForeignKeys from changedTables
            foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
                // strtolower the table name to make if compatible with getShortestName
                $localTableName = strtolower($foreignKey->getLocalTableName());
                if (! isset($diff->changedTables[$localTableName])) {
                    continue;
                }

                foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
                    // We check if the key is from the removed table if not we skip.
                    if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
                        continue;
115
                    }
116
                    unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
117
                }
118
            }
119 120
        }

121
        foreach ($toSchema->getSequences() as $sequence) {
122
            $sequenceName = $sequence->getShortestName($toSchema->getName());
123 124
            if (! $fromSchema->hasSequence($sequenceName)) {
                if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
125 126
                    $diff->newSequences[] = $sequence;
                }
127 128
            } else {
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
129
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
130 131 132 133
                }
            }
        }

134
        foreach ($fromSchema->getSequences() as $sequence) {
135 136 137 138
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
                continue;
            }

139
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
140

141 142
            if ($toSchema->hasSequence($sequenceName)) {
                continue;
143
            }
144 145

            $diff->removedSequences[] = $sequence;
146
        }
147 148 149 150

        return $diff;
    }

Benjamin Morel's avatar
Benjamin Morel committed
151
    /**
152 153
     * @param Schema   $schema
     * @param Sequence $sequence
Benjamin Morel's avatar
Benjamin Morel committed
154
     *
155
     * @return bool
Benjamin Morel's avatar
Benjamin Morel committed
156
     */
157 158 159 160 161 162 163 164 165 166 167
    private function isAutoIncrementSequenceInSchema($schema, $sequence)
    {
        foreach ($schema->getTables() as $table) {
            if ($sequence->isAutoIncrementsFor($table)) {
                return true;
            }
        }

        return false;
    }

168
    /**
169
     * @return bool
170
     */
171
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
172
    {
173
        if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
174 175 176
            return true;
        }

Gabriel Caruso's avatar
Gabriel Caruso committed
177
        return $sequence1->getInitialValue() !== $sequence2->getInitialValue();
178 179
    }

180 181 182 183 184
    /**
     * Returns the difference between the tables $table1 and $table2.
     *
     * If there are no differences this method returns the boolean false.
     *
185
     * @return TableDiff|false
186
     */
187
    public function diffTable(Table $table1, Table $table2)
188
    {
189 190
        $changes                     = 0;
        $tableDifferences            = new TableDiff($table1->getName());
191
        $tableDifferences->fromTable = $table1;
192

193 194 195
        $table1Columns = $table1->getColumns();
        $table2Columns = $table2->getColumns();

Steve Müller's avatar
Steve Müller committed
196
        /* See if all the fields in table 1 exist in table 2 */
197
        foreach ($table2Columns as $columnName => $column) {
198 199
            if ($table1->hasColumn($columnName)) {
                continue;
200
            }
201 202 203

            $tableDifferences->addedColumns[$columnName] = $column;
            $changes++;
204 205
        }
        /* See if there are any removed fields in table 2 */
206 207
        foreach ($table1Columns as $columnName => $column) {
            // See if column is removed in table 2.
208
            if (! $table2->hasColumn($columnName)) {
209
                $tableDifferences->removedColumns[$columnName] = $column;
210
                $changes++;
211
                continue;
212
            }
213

214 215 216
            // See if column has changed properties in table 2.
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));

217 218
            if (empty($changedProperties)) {
                continue;
219
            }
220 221 222 223 224

            $columnDiff                                           = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
            $columnDiff->fromColumn                               = $column;
            $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
            $changes++;
225 226
        }

227
        $this->detectColumnRenamings($tableDifferences);
228

229 230 231
        $table1Indexes = $table1->getIndexes();
        $table2Indexes = $table2->getIndexes();

232 233 234 235
        /* See if all the indexes in table 1 exist in table 2 */
        foreach ($table2Indexes as $indexName => $index) {
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
                continue;
236
            }
237

238
            $tableDifferences->addedIndexes[$indexName] = $index;
239
            $changes++;
240
        }
241 242 243 244 245 246 247 248 249 250
        /* See if there are any removed indexes in table 2 */
        foreach ($table1Indexes as $indexName => $index) {
            // See if index is removed in table 2.
            if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
            ) {
                $tableDifferences->removedIndexes[$indexName] = $index;
                $changes++;
                continue;
            }
251

252 253 254
            // See if index has changed in table 2.
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);

255 256
            if (! $this->diffIndex($index, $table2Index)) {
                continue;
257
            }
258 259 260

            $tableDifferences->changedIndexes[$indexName] = $table2Index;
            $changes++;
261 262
        }

263 264
        $this->detectIndexRenamings($tableDifferences);

265
        $fromFkeys = $table1->getForeignKeys();
266
        $toFkeys   = $table2->getForeignKeys();
267

268 269
        foreach ($fromFkeys as $key1 => $constraint1) {
            foreach ($toFkeys as $key2 => $constraint2) {
Steve Müller's avatar
Steve Müller committed
270
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
271
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
272
                } else {
273
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
274 275
                        $tableDifferences->changedForeignKeys[] = $constraint2;
                        $changes++;
276
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
277
                    }
278 279 280 281
                }
            }
        }

Benjamin Morel's avatar
Benjamin Morel committed
282
        foreach ($fromFkeys as $constraint1) {
283 284 285 286
            $tableDifferences->removedForeignKeys[] = $constraint1;
            $changes++;
        }

Benjamin Morel's avatar
Benjamin Morel committed
287
        foreach ($toFkeys as $constraint2) {
288 289
            $tableDifferences->addedForeignKeys[] = $constraint2;
            $changes++;
290
        }
291 292 293 294

        return $changes ? $tableDifferences : false;
    }

295 296
    /**
     * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
297
     * however ambiguities between different possibilities should not lead to renaming at all.
298
     *
Benjamin Morel's avatar
Benjamin Morel committed
299
     * @return void
300 301 302
     */
    private function detectColumnRenamings(TableDiff $tableDifferences)
    {
303
        $renameCandidates = [];
304
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
Benjamin Morel's avatar
Benjamin Morel committed
305
            foreach ($tableDifferences->removedColumns as $removedColumn) {
306 307
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
                    continue;
308
                }
309 310

                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
311 312 313
            }
        }

314
        foreach ($renameCandidates as $candidateColumns) {
315 316
            if (count($candidateColumns) !== 1) {
                continue;
317
            }
318 319 320 321 322 323 324 325 326 327 328 329 330 331

            [$removedColumn, $addedColumn] = $candidateColumns[0];
            $removedColumnName             = strtolower($removedColumn->getName());
            $addedColumnName               = strtolower($addedColumn->getName());

            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
                continue;
            }

            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
            unset(
                $tableDifferences->addedColumns[$addedColumnName],
                $tableDifferences->removedColumns[$removedColumnName]
            );
332 333 334
        }
    }

335 336 337 338 339 340 341 342
    /**
     * Try to find indexes that only changed their name, rename operations maybe cheaper than add/drop
     * however ambiguities between different possibilities should not lead to renaming at all.
     *
     * @return void
     */
    private function detectIndexRenamings(TableDiff $tableDifferences)
    {
343
        $renameCandidates = [];
344 345 346 347

        // Gather possible rename candidates by comparing each added and removed index based on semantics.
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
348 349
                if ($this->diffIndex($addedIndex, $removedIndex)) {
                    continue;
350
                }
351 352

                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
353 354 355 356 357 358 359 360
            }
        }

        foreach ($renameCandidates as $candidateIndexes) {
            // If the current rename candidate contains exactly one semantically equal index,
            // we can safely rename it.
            // Otherwise it is unclear if a rename action is really intended,
            // therefore we let those ambiguous indexes be added/dropped.
361 362 363 364 365 366 367 368 369 370 371
            if (count($candidateIndexes) !== 1) {
                continue;
            }

            [$removedIndex, $addedIndex] = $candidateIndexes[0];

            $removedIndexName = strtolower($removedIndex->getName());
            $addedIndexName   = strtolower($addedIndex->getName());

            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
                continue;
372
            }
373 374 375 376 377 378

            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
            unset(
                $tableDifferences->addedIndexes[$addedIndexName],
                $tableDifferences->removedIndexes[$removedIndexName]
            );
379 380 381
        }
    }

382
    /**
383
     * @return bool
384
     */
385
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
386
    {
387
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
388 389
            return true;
        }
390

391
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
392 393 394
            return true;
        }

395
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
396 397 398
            return true;
        }

399
        if ($key1->onUpdate() !== $key2->onUpdate()) {
400 401 402
            return true;
        }

Gabriel Caruso's avatar
Gabriel Caruso committed
403
        return $key1->onDelete() !== $key2->onDelete();
404 405
    }

406 407 408 409 410 411
    /**
     * Returns the difference between the fields $field1 and $field2.
     *
     * If there are differences this method returns $field2, otherwise the
     * boolean false.
     *
412
     * @return string[]
413
     */
414
    public function diffColumn(Column $column1, Column $column2)
415
    {
416 417 418
        $properties1 = $column1->toArray();
        $properties2 = $column2->toArray();

419
        $changedProperties = [];
420

421 422 423 424 425
        if (get_class($properties1['type']) !== get_class($properties2['type'])) {
            $changedProperties[] = 'type';
        }

        foreach (['notnull', 'unsigned', 'autoincrement'] as $property) {
426 427
            if ($properties1[$property] === $properties2[$property]) {
                continue;
428
            }
429 430

            $changedProperties[] = $property;
431
        }
432

433 434 435 436 437 438 439
        // This is a very nasty hack to make comparator work with the legacy json_array type, which should be killed in v3
        if ($this->isALegacyJsonComparison($properties1['type'], $properties2['type'])) {
            array_shift($changedProperties);

            $changedProperties[] = 'comment';
        }

440 441 442
        // Null values need to be checked additionally as they tell whether to create or drop a default value.
        // null != 0, null != false, null != '' etc. This affects platform's table alteration SQL generation.
        if (($properties1['default'] === null) !== ($properties2['default'] === null)
443
            || $properties1['default'] != $properties2['default']) {
444
            $changedProperties[] = 'default';
445 446
        }

447 448 449
        if (($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
            $properties1['type'] instanceof Types\BinaryType
        ) {
450
            // check if value of length is set at all, default value assumed otherwise.
451 452
            $length1 = $properties1['length'] ?: 255;
            $length2 = $properties2['length'] ?: 255;
453
            if ($length1 !== $length2) {
454
                $changedProperties[] = 'length';
455 456
            }

457
            if ($properties1['fixed'] !== $properties2['fixed']) {
458
                $changedProperties[] = 'fixed';
459
            }
460
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
461
            if (($properties1['precision'] ?: 10) !== ($properties2['precision'] ?: 10)) {
462
                $changedProperties[] = 'precision';
463
            }
464
            if ($properties1['scale'] !== $properties2['scale']) {
465
                $changedProperties[] = 'scale';
466 467 468
            }
        }

469 470
        // A null value and an empty string are actually equal for a comment so they should not trigger a change.
        if ($properties1['comment'] !== $properties2['comment'] &&
471 472
            ! ($properties1['comment'] === null && $properties2['comment'] === '') &&
            ! ($properties2['comment'] === null && $properties1['comment'] === '')
473
        ) {
474 475 476
            $changedProperties[] = 'comment';
        }

477 478
        $customOptions1 = $column1->getCustomSchemaOptions();
        $customOptions2 = $column2->getCustomSchemaOptions();
479

480
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
481
            if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
482 483
                $changedProperties[] = $key;
            } elseif ($properties1[$key] !== $properties2[$key]) {
484 485 486 487
                $changedProperties[] = $key;
            }
        }

488 489 490 491
        $platformOptions1 = $column1->getPlatformOptions();
        $platformOptions2 = $column2->getPlatformOptions();

        foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
492 493
            if ($properties1[$key] === $properties2[$key]) {
                continue;
494
            }
495 496

            $changedProperties[] = $key;
497 498 499
        }

        return array_unique($changedProperties);
500 501
    }

502 503 504 505 506 507 508
    /**
     * TODO: kill with fire on v3.0
     *
     * @deprecated
     */
    private function isALegacyJsonComparison(Types\Type $one, Types\Type $other) : bool
    {
509
        if (! $one instanceof Types\JsonType || ! $other instanceof Types\JsonType) {
510 511 512 513 514 515 516
            return false;
        }

        return ( ! $one instanceof Types\JsonArrayType && $other instanceof Types\JsonArrayType)
            || ( ! $other instanceof Types\JsonArrayType && $one instanceof Types\JsonArrayType);
    }

517 518 519 520 521 522
    /**
     * Finds the difference between the indexes $index1 and $index2.
     *
     * Compares $index1 with $index2 and returns $index2 if there are any
     * differences or false in case there are no differences.
     *
523
     * @return bool
524
     */
525
    public function diffIndex(Index $index1, Index $index2)
526
    {
Gabriel Caruso's avatar
Gabriel Caruso committed
527
        return ! ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1));
528
    }
beberlei's avatar
beberlei committed
529
}