Comparator.php 17.1 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 22
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL\Schema;

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

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

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

61 62
        $foreignKeysToTable = array();

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

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

            $table = $fromSchema->getTable($tableName);
Steve Müller's avatar
Steve Müller committed
80
            if ( ! $toSchema->hasTable($tableName)) {
81 82
                $diff->removedTables[$tableName] = $table;
            }
83 84

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

94
        foreach ($diff->removedTables as $tableName => $table) {
95 96
            if (isset($foreignKeysToTable[$tableName])) {
                $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
97 98 99 100

                // deleting duplicated foreign keys present on both on the orphanedForeignKey
                // and the removedForeignKeys from changedTables
                foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
101 102 103 104 105
                    // 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) {
                            unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
106 107 108
                        }
                    }
                }
109
            }
110 111
        }

112
        foreach ($toSchema->getSequences() as $sequence) {
113
            $sequenceName = $sequence->getShortestName($toSchema->getName());
114
            if ( ! $fromSchema->hasSequence($sequenceName)) {
115 116 117
                if ( ! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
                    $diff->newSequences[] = $sequence;
                }
118 119
            } else {
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
120
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
121 122 123 124
                }
            }
        }

125
        foreach ($fromSchema->getSequences() as $sequence) {
126 127 128 129
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
                continue;
            }

130
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
131

132
            if ( ! $toSchema->hasSequence($sequenceName)) {
133 134 135
                $diff->removedSequences[] = $sequence;
            }
        }
136 137 138 139

        return $diff;
    }

Benjamin Morel's avatar
Benjamin Morel committed
140 141 142 143 144 145
    /**
     * @param \Doctrine\DBAL\Schema\Schema   $schema
     * @param \Doctrine\DBAL\Schema\Sequence $sequence
     *
     * @return boolean
     */
146 147 148 149 150 151 152 153 154 155 156
    private function isAutoIncrementSequenceInSchema($schema, $sequence)
    {
        foreach ($schema->getTables() as $table) {
            if ($sequence->isAutoIncrementsFor($table)) {
                return true;
            }
        }

        return false;
    }

157
    /**
Benjamin Morel's avatar
Benjamin Morel committed
158 159
     * @param \Doctrine\DBAL\Schema\Sequence $sequence1
     * @param \Doctrine\DBAL\Schema\Sequence $sequence2
160
     *
Benjamin Morel's avatar
Benjamin Morel committed
161
     * @return boolean
162
     */
163
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
164
    {
Steve Müller's avatar
Steve Müller committed
165
        if ($sequence1->getAllocationSize() != $sequence2->getAllocationSize()) {
166 167 168
            return true;
        }

Steve Müller's avatar
Steve Müller committed
169
        if ($sequence1->getInitialValue() != $sequence2->getInitialValue()) {
170 171 172 173 174 175
            return true;
        }

        return false;
    }

176 177 178 179 180
    /**
     * 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
181 182
     * @param \Doctrine\DBAL\Schema\Table $table1
     * @param \Doctrine\DBAL\Schema\Table $table2
183
     *
Benjamin Morel's avatar
Benjamin Morel committed
184
     * @return boolean|\Doctrine\DBAL\Schema\TableDiff
185
     */
186
    public function diffTable(Table $table1, Table $table2)
187 188
    {
        $changes = 0;
189
        $tableDifferences = new TableDiff($table1->getName());
190
        $tableDifferences->fromTable = $table1;
191

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

Steve Müller's avatar
Steve Müller committed
195
        /* See if all the fields in table 1 exist in table 2 */
196
        foreach ($table2Columns as $columnName => $column) {
Steve Müller's avatar
Steve Müller committed
197
            if ( !$table1->hasColumn($columnName)) {
198
                $tableDifferences->addedColumns[$columnName] = $column;
199 200 201 202
                $changes++;
            }
        }
        /* See if there are any removed fields in table 2 */
203 204 205
        foreach ($table1Columns as $columnName => $column) {
            // See if column is removed in table 2.
            if ( ! $table2->hasColumn($columnName)) {
206
                $tableDifferences->removedColumns[$columnName] = $column;
207
                $changes++;
208
                continue;
209
            }
210

211 212 213 214 215 216 217 218
            // 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++;
219 220 221
            }
        }

222
        $this->detectColumnRenamings($tableDifferences);
223

224 225 226
        $table1Indexes = $table1->getIndexes();
        $table2Indexes = $table2->getIndexes();

227 228
        foreach ($table2Indexes as $index2Name => $index2Definition) {
            foreach ($table1Indexes as $index1Name => $index1Definition) {
229
                if ($this->diffIndex($index1Definition, $index2Definition) === false) {
230 231 232 233 234
                    if ( ! $index1Definition->isPrimary() && $index1Name != $index2Name) {
                        $tableDifferences->renamedIndexes[$index1Name] = $index2Definition;
                        $changes++;
                    }

235 236 237 238 239 240 241 242 243 244
                    unset($table1Indexes[$index1Name]);
                    unset($table2Indexes[$index2Name]);
                } else {
                    if ($index1Name == $index2Name) {
                        $tableDifferences->changedIndexes[$index2Name] = $table2Indexes[$index2Name];
                        unset($table1Indexes[$index1Name]);
                        unset($table2Indexes[$index2Name]);
                        $changes++;
                    }
                }
245 246
            }
        }
247

248
        foreach ($table1Indexes as $index1Name => $index1Definition) {
249
            $tableDifferences->removedIndexes[$index1Name] = $index1Definition;
250
            $changes++;
251
        }
252

253
        foreach ($table2Indexes as $index2Name => $index2Definition) {
254 255
            $tableDifferences->addedIndexes[$index2Name] = $index2Definition;
            $changes++;
256 257
        }

258 259 260
        $fromFkeys = $table1->getForeignKeys();
        $toFkeys = $table2->getForeignKeys();

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

Benjamin Morel's avatar
Benjamin Morel committed
277
        foreach ($fromFkeys as $constraint1) {
278 279 280 281
            $tableDifferences->removedForeignKeys[] = $constraint1;
            $changes++;
        }

Benjamin Morel's avatar
Benjamin Morel committed
282
        foreach ($toFkeys as $constraint2) {
283 284
            $tableDifferences->addedForeignKeys[] = $constraint2;
            $changes++;
285
        }
286 287 288 289

        return $changes ? $tableDifferences : false;
    }

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

309
        foreach ($renameCandidates as $candidateColumns) {
310 311
            if (count($candidateColumns) == 1) {
                list($removedColumn, $addedColumn) = $candidateColumns[0];
312 313
                $removedColumnName = strtolower($removedColumn->getName());
                $addedColumnName = strtolower($addedColumn->getName());
314

315
                if ( ! isset($tableDifferences->renamedColumns[$removedColumnName])) {
316 317 318 319
                    $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
                    unset($tableDifferences->addedColumns[$addedColumnName]);
                    unset($tableDifferences->removedColumns[$removedColumnName]);
                }
320 321 322 323
            }
        }
    }

324
    /**
Benjamin Morel's avatar
Benjamin Morel committed
325 326 327 328
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $key1
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $key2
     *
     * @return boolean
329
     */
330
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
331
    {
332
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) != array_map('strtolower', $key2->getUnquotedLocalColumns())) {
333 334
            return true;
        }
335

336
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) != array_map('strtolower', $key2->getUnquotedForeignColumns())) {
337 338 339
            return true;
        }

340
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
341 342 343
            return true;
        }

344
        if ($key1->onUpdate() != $key2->onUpdate()) {
345 346 347
            return true;
        }

348
        if ($key1->onDelete() != $key2->onDelete()) {
349 350 351 352 353 354
            return true;
        }

        return false;
    }

355 356 357 358 359 360
    /**
     * 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
361 362
     * @param \Doctrine\DBAL\Schema\Column $column1
     * @param \Doctrine\DBAL\Schema\Column $column2
363
     *
364
     * @return array
365
     */
366
    public function diffColumn(Column $column1, Column $column2)
367
    {
368
        $changedProperties = array();
Steve Müller's avatar
Steve Müller committed
369
        if ($column1->getType() != $column2->getType()) {
370
            $changedProperties[] = 'type';
371 372 373
        }

        if ($column1->getNotnull() != $column2->getNotnull()) {
374
            $changedProperties[] = 'notnull';
375 376
        }

377 378 379 380 381 382 383 384 385
        $column1Default = $column1->getDefault();
        $column2Default = $column2->getDefault();

        if ($column1Default != $column2Default ||
            // 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.
            (null === $column1Default && null !== $column2Default) ||
            (null === $column2Default && null !== $column1Default)
        ) {
386
            $changedProperties[] = 'default';
387 388 389
        }

        if ($column1->getUnsigned() != $column2->getUnsigned()) {
390
            $changedProperties[] = 'unsigned';
391 392
        }

Steve Müller's avatar
Steve Müller committed
393 394 395 396 397
        $column1Type = $column1->getType();

        if ($column1Type instanceof \Doctrine\DBAL\Types\StringType ||
            $column1Type instanceof \Doctrine\DBAL\Types\BinaryType
        ) {
398 399 400 401
            // check if value of length is set at all, default value assumed otherwise.
            $length1 = $column1->getLength() ?: 255;
            $length2 = $column2->getLength() ?: 255;
            if ($length1 != $length2) {
402
                $changedProperties[] = 'length';
403 404 405
            }

            if ($column1->getFixed() != $column2->getFixed()) {
406
                $changedProperties[] = 'fixed';
407 408 409 410
            }
        }

        if ($column1->getType() instanceof \Doctrine\DBAL\Types\DecimalType) {
411
            if (($column1->getPrecision()?:10) != ($column2->getPrecision()?:10)) {
412
                $changedProperties[] = 'precision';
413 414
            }
            if ($column1->getScale() != $column2->getScale()) {
415
                $changedProperties[] = 'scale';
416 417 418
            }
        }

419 420 421 422
        if ($column1->getAutoincrement() != $column2->getAutoincrement()) {
            $changedProperties[] = 'autoincrement';
        }

423 424
        // only allow to delete comment if its set to '' not to null.
        if ($column1->getComment() !== null && $column1->getComment() != $column2->getComment()) {
425 426 427
            $changedProperties[] = 'comment';
        }

428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
        $options1 = $column1->getCustomSchemaOptions();
        $options2 = $column2->getCustomSchemaOptions();

        $commonKeys = array_keys(array_intersect_key($options1, $options2));

        foreach ($commonKeys as $key) {
            if ($options1[$key] !== $options2[$key]) {
                $changedProperties[] = $key;
            }
        }

        $diffKeys = array_keys(array_diff_key($options1, $options2) + array_diff_key($options2, $options1));

        $changedProperties = array_merge($changedProperties, $diffKeys);

443
        return $changedProperties;
444 445 446 447 448 449 450 451
    }

    /**
     * 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
452 453 454 455
     * @param \Doctrine\DBAL\Schema\Index $index1
     * @param \Doctrine\DBAL\Schema\Index $index2
     *
     * @return boolean
456
     */
457
    public function diffIndex(Index $index1, Index $index2)
458
    {
459 460
        if ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1)) {
            return false;
461
        }
Benjamin Morel's avatar
Benjamin Morel committed
462

463
        return true;
464
    }
beberlei's avatar
beberlei committed
465
}