Comparator.php 19.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
Benjamin Eberlei's avatar
Benjamin Eberlei committed
16
 * and is licensed under the MIT license. For more information, see
17 18 19 20 21
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL\Schema;

22 23
use Doctrine\DBAL\Types;

24
/**
Benjamin Morel's avatar
Benjamin Morel committed
25
 * Compares two Schemas and return an instance of SchemaDiff.
26
 *
Benjamin Morel's avatar
Benjamin Morel committed
27 28 29
 * @link   www.doctrine-project.org
 * @since  2.0
 * @author Benjamin Eberlei <kontakt@beberlei.de>
30 31 32 33
 */
class Comparator
{
    /**
Benjamin Morel's avatar
Benjamin Morel committed
34 35 36 37
     * @param \Doctrine\DBAL\Schema\Schema $fromSchema
     * @param \Doctrine\DBAL\Schema\Schema $toSchema
     *
     * @return \Doctrine\DBAL\Schema\SchemaDiff
38
     */
Benjamin Morel's avatar
Benjamin Morel committed
39
    static public function compareSchemas(Schema $fromSchema, Schema $toSchema)
40 41
    {
        $c = new self();
Benjamin Morel's avatar
Benjamin Morel committed
42

43 44 45 46 47 48
        return $c->compare($fromSchema, $toSchema);
    }

    /**
     * Returns a SchemaDiff object containing the differences between the schemas $fromSchema and $toSchema.
     *
49
     * The returned differences are returned in such a way that they contain the
50 51 52
     * operations to change the schema stored in $fromSchema to the schema that is
     * stored in $toSchema.
     *
Benjamin Morel's avatar
Benjamin Morel committed
53 54
     * @param \Doctrine\DBAL\Schema\Schema $fromSchema
     * @param \Doctrine\DBAL\Schema\Schema $toSchema
55
     *
Benjamin Morel's avatar
Benjamin Morel committed
56
     * @return \Doctrine\DBAL\Schema\SchemaDiff
57
     */
58
    public function compare(Schema $fromSchema, Schema $toSchema)
59 60
    {
        $diff = new SchemaDiff();
61
        $diff->fromSchema = $fromSchema;
62

63 64
        $foreignKeysToTable = array();

65 66
        foreach ($toSchema->getNamespaces() as $namespace) {
            if ( ! $fromSchema->hasNamespace($namespace)) {
Marco Pivetta's avatar
Marco Pivetta committed
67 68
                $diff->newNamespaces[$namespace] = $namespace;
            }
69 70 71 72 73 74 75
        }

        foreach ($fromSchema->getNamespaces() as $namespace) {
            if ( ! $toSchema->hasNamespace($namespace)) {
                $diff->removedNamespaces[$namespace] = $namespace;
            }
        }
Marco Pivetta's avatar
Marco Pivetta committed
76

77
        foreach ($toSchema->getTables() as $table) {
78
            $tableName = $table->getShortestName($toSchema->getName());
79
            if ( ! $fromSchema->hasTable($tableName)) {
80
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
81
            } else {
82 83
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
                if ($tableDifferences !== false) {
84 85 86 87 88 89
                    $diff->changedTables[$tableName] = $tableDifferences;
                }
            }
        }

        /* Check if there are tables removed */
90
        foreach ($fromSchema->getTables() as $table) {
91 92 93
            $tableName = $table->getShortestName($fromSchema->getName());

            $table = $fromSchema->getTable($tableName);
Steve Müller's avatar
Steve Müller committed
94
            if ( ! $toSchema->hasTable($tableName)) {
95 96
                $diff->removedTables[$tableName] = $table;
            }
97 98

            // also remember all foreign keys that point to a specific table
99
            foreach ($table->getForeignKeys() as $foreignKey) {
100 101 102 103 104 105 106 107
                $foreignTable = strtolower($foreignKey->getForeignTableName());
                if (!isset($foreignKeysToTable[$foreignTable])) {
                    $foreignKeysToTable[$foreignTable] = array();
                }
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
            }
        }

108
        foreach ($diff->removedTables as $tableName => $table) {
109 110
            if (isset($foreignKeysToTable[$tableName])) {
                $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
111 112 113 114

                // deleting duplicated foreign keys present on both on the orphanedForeignKey
                // and the removedForeignKeys from changedTables
                foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
115 116 117 118
                    // strtolower the table name to make if compatible with getShortestName
                    $localTableName = strtolower($foreignKey->getLocalTableName());
                    if (isset($diff->changedTables[$localTableName])) {
                        foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
Steve Müller's avatar
Steve Müller committed
119 120
                            // We check if the key is from the removed table if not we skip.
                            if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
121 122
                                continue;
                            }
123
                            unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
124 125 126
                        }
                    }
                }
127
            }
128 129
        }

130
        foreach ($toSchema->getSequences() as $sequence) {
131
            $sequenceName = $sequence->getShortestName($toSchema->getName());
132
            if ( ! $fromSchema->hasSequence($sequenceName)) {
133 134 135
                if ( ! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
                    $diff->newSequences[] = $sequence;
                }
136 137
            } else {
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
138
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
139 140 141 142
                }
            }
        }

143
        foreach ($fromSchema->getSequences() as $sequence) {
144 145 146 147
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
                continue;
            }

148
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
149

150
            if ( ! $toSchema->hasSequence($sequenceName)) {
151 152 153
                $diff->removedSequences[] = $sequence;
            }
        }
154 155 156 157

        return $diff;
    }

Benjamin Morel's avatar
Benjamin Morel committed
158 159 160 161 162 163
    /**
     * @param \Doctrine\DBAL\Schema\Schema   $schema
     * @param \Doctrine\DBAL\Schema\Sequence $sequence
     *
     * @return boolean
     */
164 165 166 167 168 169 170 171 172 173 174
    private function isAutoIncrementSequenceInSchema($schema, $sequence)
    {
        foreach ($schema->getTables() as $table) {
            if ($sequence->isAutoIncrementsFor($table)) {
                return true;
            }
        }

        return false;
    }

175
    /**
Benjamin Morel's avatar
Benjamin Morel committed
176 177
     * @param \Doctrine\DBAL\Schema\Sequence $sequence1
     * @param \Doctrine\DBAL\Schema\Sequence $sequence2
178
     *
Benjamin Morel's avatar
Benjamin Morel committed
179
     * @return boolean
180
     */
181
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
182
    {
Steve Müller's avatar
Steve Müller committed
183
        if ($sequence1->getAllocationSize() != $sequence2->getAllocationSize()) {
184 185 186
            return true;
        }

Steve Müller's avatar
Steve Müller committed
187
        if ($sequence1->getInitialValue() != $sequence2->getInitialValue()) {
188 189 190 191 192 193
            return true;
        }

        return false;
    }

194 195 196 197 198
    /**
     * Returns the difference between the tables $table1 and $table2.
     *
     * If there are no differences this method returns the boolean false.
     *
Benjamin Morel's avatar
Benjamin Morel committed
199 200
     * @param \Doctrine\DBAL\Schema\Table $table1
     * @param \Doctrine\DBAL\Schema\Table $table2
201
     *
Benjamin Morel's avatar
Benjamin Morel committed
202
     * @return boolean|\Doctrine\DBAL\Schema\TableDiff
203
     */
204
    public function diffTable(Table $table1, Table $table2)
205 206
    {
        $changes = 0;
207
        $tableDifferences = new TableDiff($table1->getName());
208
        $tableDifferences->fromTable = $table1;
209

210 211 212
        $table1Columns = $table1->getColumns();
        $table2Columns = $table2->getColumns();

Steve Müller's avatar
Steve Müller committed
213
        /* See if all the fields in table 1 exist in table 2 */
214
        foreach ($table2Columns as $columnName => $column) {
Steve Müller's avatar
Steve Müller committed
215
            if ( !$table1->hasColumn($columnName)) {
216
                $tableDifferences->addedColumns[$columnName] = $column;
217 218 219 220
                $changes++;
            }
        }
        /* See if there are any removed fields in table 2 */
221 222 223
        foreach ($table1Columns as $columnName => $column) {
            // See if column is removed in table 2.
            if ( ! $table2->hasColumn($columnName)) {
224
                $tableDifferences->removedColumns[$columnName] = $column;
225
                $changes++;
226
                continue;
227
            }
228

229 230 231 232 233 234 235 236
            // See if column has changed properties in table 2.
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));

            if ( ! empty($changedProperties)) {
                $columnDiff = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
                $columnDiff->fromColumn = $column;
                $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
                $changes++;
237 238 239
            }
        }

240
        $this->detectColumnRenamings($tableDifferences);
241

242 243 244
        $table1Indexes = $table1->getIndexes();
        $table2Indexes = $table2->getIndexes();

245 246 247 248
        /* 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;
249
            }
250

251
            $tableDifferences->addedIndexes[$indexName] = $index;
252
            $changes++;
253
        }
254 255 256 257 258 259 260 261 262 263
        /* 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;
            }
264

265 266 267 268 269 270 271
            // See if index has changed in table 2.
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);

            if ($this->diffIndex($index, $table2Index)) {
                $tableDifferences->changedIndexes[$indexName] = $table2Index;
                $changes++;
            }
272 273
        }

274 275
        $this->detectIndexRenamings($tableDifferences);

276 277 278
        $fromFkeys = $table1->getForeignKeys();
        $toFkeys = $table2->getForeignKeys();

279 280
        foreach ($fromFkeys as $key1 => $constraint1) {
            foreach ($toFkeys as $key2 => $constraint2) {
Steve Müller's avatar
Steve Müller committed
281
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
282 283 284 285 286 287 288 289 290
                    unset($fromFkeys[$key1]);
                    unset($toFkeys[$key2]);
                } else {
                    if (strtolower($constraint1->getName()) == strtolower($constraint2->getName())) {
                        $tableDifferences->changedForeignKeys[] = $constraint2;
                        $changes++;
                        unset($fromFkeys[$key1]);
                        unset($toFkeys[$key2]);
                    }
291 292 293 294
                }
            }
        }

Benjamin Morel's avatar
Benjamin Morel committed
295
        foreach ($fromFkeys as $constraint1) {
296 297 298 299
            $tableDifferences->removedForeignKeys[] = $constraint1;
            $changes++;
        }

Benjamin Morel's avatar
Benjamin Morel committed
300
        foreach ($toFkeys as $constraint2) {
301 302
            $tableDifferences->addedForeignKeys[] = $constraint2;
            $changes++;
303
        }
304 305 306 307

        return $changes ? $tableDifferences : false;
    }

308 309
    /**
     * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
310
     * however ambiguities between different possibilities should not lead to renaming at all.
311
     *
Benjamin Morel's avatar
Benjamin Morel committed
312 313 314
     * @param \Doctrine\DBAL\Schema\TableDiff $tableDifferences
     *
     * @return void
315 316 317 318
     */
    private function detectColumnRenamings(TableDiff $tableDifferences)
    {
        $renameCandidates = array();
319
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
Benjamin Morel's avatar
Benjamin Morel committed
320
            foreach ($tableDifferences->removedColumns as $removedColumn) {
321
                if (count($this->diffColumn($addedColumn, $removedColumn)) == 0) {
322
                    $renameCandidates[$addedColumn->getName()][] = array($removedColumn, $addedColumn, $addedColumnName);
323 324 325 326
                }
            }
        }

327
        foreach ($renameCandidates as $candidateColumns) {
328 329
            if (count($candidateColumns) == 1) {
                list($removedColumn, $addedColumn) = $candidateColumns[0];
330 331
                $removedColumnName = strtolower($removedColumn->getName());
                $addedColumnName = strtolower($addedColumn->getName());
332

333
                if ( ! isset($tableDifferences->renamedColumns[$removedColumnName])) {
334 335 336 337
                    $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
                    unset($tableDifferences->addedColumns[$addedColumnName]);
                    unset($tableDifferences->removedColumns[$removedColumnName]);
                }
338 339 340 341
            }
        }
    }

342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
    /**
     * 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.
     *
     * @param \Doctrine\DBAL\Schema\TableDiff $tableDifferences
     *
     * @return void
     */
    private function detectIndexRenamings(TableDiff $tableDifferences)
    {
        $renameCandidates = array();

        // 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) {
                if (! $this->diffIndex($addedIndex, $removedIndex)) {
                    $renameCandidates[$addedIndex->getName()][] = array($removedIndex, $addedIndex, $addedIndexName);
                }
            }
        }

        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.
            if (count($candidateIndexes) === 1) {
                list($removedIndex, $addedIndex) = $candidateIndexes[0];

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

                if (! isset($tableDifferences->renamedIndexes[$removedIndexName])) {
                    $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
                    unset($tableDifferences->addedIndexes[$addedIndexName]);
                    unset($tableDifferences->removedIndexes[$removedIndexName]);
                }
            }
        }
    }

383
    /**
Benjamin Morel's avatar
Benjamin Morel committed
384 385 386 387
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $key1
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $key2
     *
     * @return boolean
388
     */
389
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
390
    {
391
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) != array_map('strtolower', $key2->getUnquotedLocalColumns())) {
392 393
            return true;
        }
394

395
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) != array_map('strtolower', $key2->getUnquotedForeignColumns())) {
396 397 398
            return true;
        }

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

403
        if ($key1->onUpdate() != $key2->onUpdate()) {
404 405 406
            return true;
        }

407
        if ($key1->onDelete() != $key2->onDelete()) {
408 409 410 411 412 413
            return true;
        }

        return false;
    }

414 415 416 417 418 419
    /**
     * Returns the difference between the fields $field1 and $field2.
     *
     * If there are differences this method returns $field2, otherwise the
     * boolean false.
     *
Benjamin Morel's avatar
Benjamin Morel committed
420 421
     * @param \Doctrine\DBAL\Schema\Column $column1
     * @param \Doctrine\DBAL\Schema\Column $column2
422
     *
423
     * @return array
424
     */
425
    public function diffColumn(Column $column1, Column $column2)
426
    {
427 428 429
        $properties1 = $column1->toArray();
        $properties2 = $column2->toArray();

430
        $changedProperties = array();
431

432 433 434 435
        foreach (array('type', 'notnull', 'unsigned', 'autoincrement') as $property) {
            if ($properties1[$property] != $properties2[$property]) {
                $changedProperties[] = $property;
            }
436
        }
437

438
        if ($properties1['default'] != $properties2['default'] ||
439 440
            // 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.
441 442
            (null === $properties1['default'] && null !== $properties2['default']) ||
            (null === $properties2['default'] && null !== $properties1['default'])
443
        ) {
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 461
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
            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 471 472 473
        // 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'] &&
            ! (null === $properties1['comment'] && '' === $properties2['comment']) &&
            ! (null === $properties2['comment'] && '' === $properties1['comment'])
        ) {
474 475 476
            $changedProperties[] = 'comment';
        }

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

480 481 482 483
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
            if ( ! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
                $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
            if ($properties1[$key] !== $properties2[$key]) {
493 494 495 496 497
                $changedProperties[] = $key;
            }
        }

        return array_unique($changedProperties);
498 499 500 501 502 503 504 505
    }

    /**
     * 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.
     *
Benjamin Morel's avatar
Benjamin Morel committed
506 507 508 509
     * @param \Doctrine\DBAL\Schema\Index $index1
     * @param \Doctrine\DBAL\Schema\Index $index2
     *
     * @return boolean
510
     */
511
    public function diffIndex(Index $index1, Index $index2)
512
    {
513 514
        if ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1)) {
            return false;
515
        }
Benjamin Morel's avatar
Benjamin Morel committed
516

517
        return true;
518
    }
beberlei's avatar
beberlei committed
519
}