Comparator.php 14.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
<?php
/*
 *  $Id$
 *
 * 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
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL\Schema;

/**
 * Compare to Schemas and return an instance of SchemaDiff
 *
 * @copyright Copyright (C) 2005-2009 eZ Systems AS. All rights reserved.
 * @license http://ez.no/licenses/new_bsd New BSD License
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link    www.doctrine-project.org
 * @since   2.0
 * @version $Revision$
 * @author  Benjamin Eberlei <kontakt@beberlei.de>
 */
class Comparator
{
37 38 39 40 41 42 43 44 45 46 47 48 49
    /**
     * @var array
     */
    private $_checkColumnPlatformOptions = array();

    /**
     * @param string $optionName
     */
    public function addColumnPlatformOptionCheck($optionName)
    {
        $this->_checkColumnPlatformOptions[] = $optionName;
    }

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
    /**
     * @param Schema $fromSchema
     * @param Schema $toSchema
     * @return SchemaDiff
     */
    static public function compareSchemas( Schema $fromSchema, Schema $toSchema )
    {
        $c = new self();
        return $c->compare($fromSchema, $toSchema);
    }

    /**
     * Returns a SchemaDiff object containing the differences between the schemas $fromSchema and $toSchema.
     *
     * The returned diferences are returned in such a way that they contain the
     * operations to change the schema stored in $fromSchema to the schema that is
     * stored in $toSchema.
     *
     * @param Schema $fromSchema
     * @param Schema $toSchema
     *
     * @return SchemaDiff
     */
73
    public function compare(Schema $fromSchema, Schema $toSchema)
74
    {
75 76 77 78
        if ($fromSchema->hasExplicitForeignKeyIndexes() && !$toSchema->hasExplicitForeignKeyIndexes()) {
            $toSchema->visit(new \Doctrine\DBAL\Schema\Visitor\FixSchema(true));
        }

79 80
        $diff = new SchemaDiff();

81 82 83
        $foreignKeysToTable = array();

        foreach ( $toSchema->getTables() AS $tableName => $table ) {
84 85 86 87 88 89 90 91 92 93 94
            if ( !$fromSchema->hasTable($tableName) ) {
                $diff->newTables[$tableName] = $table;
            } else {
                $tableDifferences = $this->diffTable( $fromSchema->getTable($tableName), $table );
                if ( $tableDifferences !== false ) {
                    $diff->changedTables[$tableName] = $tableDifferences;
                }
            }
        }

        /* Check if there are tables removed */
95
        foreach ( $fromSchema->getTables() AS $tableName => $table ) {
96 97 98
            if ( !$toSchema->hasTable($tableName) ) {
                $diff->removedTables[$tableName] = $table;
            }
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

            // also remember all foreign keys that point to a specific table
            foreach ($table->getForeignKeys() AS $foreignKey) {
                $foreignTable = strtolower($foreignKey->getForeignTableName());
                if (!isset($foreignKeysToTable[$foreignTable])) {
                    $foreignKeysToTable[$foreignTable] = array();
                }
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
            }
        }

        foreach ($diff->removedTables AS $tableName => $table) {
            if (isset($foreignKeysToTable[$tableName])) {
                $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
            }
114 115
        }

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
        foreach ( $toSchema->getSequences() AS $sequenceName => $sequence) {
            if (!$fromSchema->hasSequence($sequenceName)) {
                $diff->newSequences[] = $sequence;
            } else {
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
                    $diff->changedSequences[] = $fromSchema->getSequence($sequenceName);
                }
            }
        }

        foreach ($fromSchema->getSequences() AS $sequenceName => $sequence) {
            if (!$toSchema->hasSequence($sequenceName)) {
                $diff->removedSequences[] = $sequence;
            }
        }
131 132 133 134

        return $diff;
    }

135 136 137 138 139
    /**
     *
     * @param Sequence $sequence1
     * @param Sequence $sequence2
     */
140
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
141 142 143 144 145 146 147 148 149 150 151 152
    {
        if($sequence1->getAllocationSize() != $sequence2->getAllocationSize()) {
            return true;
        }

        if($sequence1->getInitialValue() != $sequence2->getInitialValue()) {
            return true;
        }

        return false;
    }

153 154 155 156 157 158 159 160 161 162
    /**
     * Returns the difference between the tables $table1 and $table2.
     *
     * If there are no differences this method returns the boolean false.
     *
     * @param Table $table1
     * @param Table $table2
     *
     * @return bool|TableDiff
     */
163
    public function diffTable(Table $table1, Table $table2)
164 165
    {
        $changes = 0;
166
        $tableDifferences = new TableDiff($table1->getName());
167

168 169 170
        $table1Columns = $table1->getColumns();
        $table2Columns = $table2->getColumns();

171
        /* See if all the fields in table 1 exist in table 2 */
172
        foreach ( $table2Columns as $columnName => $column ) {
173
            if ( !$table1->hasColumn($columnName) ) {
174
                $tableDifferences->addedColumns[$columnName] = $column;
175 176 177 178
                $changes++;
            }
        }
        /* See if there are any removed fields in table 2 */
179
        foreach ( $table1Columns as $columnName => $column ) {
180
            if ( !$table2->hasColumn($columnName) ) {
181
                $tableDifferences->removedColumns[$columnName] = $column;
182 183 184
                $changes++;
            }
        }
185
        foreach ( $table1Columns as $columnName => $column ) {
186
            if ( $table2->hasColumn($columnName) ) {
187 188
                $changedProperties = $this->diffColumn( $column, $table2->getColumn($columnName) );
                if (count($changedProperties) ) {
189
                    $columnDiff = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
190
                    $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
191 192 193 194 195
                    $changes++;
                }
            }
        }

196 197 198
        // Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
        foreach ($tableDifferences->addedColumns AS $addedColumnName => $addedColumn) {
            foreach ($tableDifferences->removedColumns AS $removedColumnName => $removedColumn) {
199
                if (count($this->diffColumn($addedColumn, $removedColumn)) == 0) {
200 201 202 203 204 205 206
                    $tableDifferences->renamedColumns[$removedColumn->getName()] = $addedColumn;
                    unset($tableDifferences->addedColumns[$addedColumnName]);
                    unset($tableDifferences->removedColumns[$removedColumnName]);
                }
            }
        }

207 208 209
        $table1Indexes = $table1->getIndexes();
        $table2Indexes = $table2->getIndexes();

210 211 212 213 214 215 216 217 218 219 220 221 222
        foreach ($table2Indexes AS $index2Name => $index2Definition) {
            foreach ($table1Indexes AS $index1Name => $index1Definition) {
                if ($this->diffIndex($index1Definition, $index2Definition) === false) {
                    unset($table1Indexes[$index1Name]);
                    unset($table2Indexes[$index2Name]);
                } else {
                    if ($index1Name == $index2Name) {
                        $tableDifferences->changedIndexes[$index2Name] = $table2Indexes[$index2Name];
                        unset($table1Indexes[$index1Name]);
                        unset($table2Indexes[$index2Name]);
                        $changes++;
                    }
                }
223 224
            }
        }
225 226

        foreach ($table1Indexes AS $index1Name => $index1Definition) {
227
            $tableDifferences->removedIndexes[$index1Name] = $index1Definition;
228
            $changes++;
229
        }
230 231 232 233

        foreach ($table2Indexes AS $index2Name => $index2Definition) {
            $tableDifferences->addedIndexes[$index2Name] = $index2Definition;
            $changes++;
234 235
        }

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
        $fromFkeys = $table1->getForeignKeys();
        $toFkeys = $table2->getForeignKeys();

        foreach ($fromFkeys AS $key1 => $constraint1) {
            foreach ($toFkeys AS $key2 => $constraint2) {
                if($this->diffForeignKey($constraint1, $constraint2) === false) {
                    unset($fromFkeys[$key1]);
                    unset($toFkeys[$key2]);
                } else {
                    if (strtolower($constraint1->getName()) == strtolower($constraint2->getName())) {
                        $tableDifferences->changedForeignKeys[] = $constraint2;
                        $changes++;
                        unset($fromFkeys[$key1]);
                        unset($toFkeys[$key2]);
                    }
251 252 253 254
                }
            }
        }

255 256 257 258 259 260 261 262
        foreach ($fromFkeys AS $key1 => $constraint1) {
            $tableDifferences->removedForeignKeys[] = $constraint1;
            $changes++;
        }

        foreach ($toFkeys AS $key2 => $constraint2) {
            $tableDifferences->addedForeignKeys[] = $constraint2;
            $changes++;
263
        }
264 265 266 267

        return $changes ? $tableDifferences : false;
    }

268 269 270 271 272
    /**
     * @param ForeignKeyConstraint $key1
     * @param ForeignKeyConstraint $key2
     * @return bool
     */
273
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
274
    {
275
        if (array_map('strtolower', $key1->getLocalColumns()) != array_map('strtolower', $key2->getLocalColumns())) {
276 277 278
            return true;
        }
        
279
        if (array_map('strtolower', $key1->getForeignColumns()) != array_map('strtolower', $key2->getForeignColumns())) {
280 281 282
            return true;
        }

283 284 285 286 287
        if ($key1->hasOption('onUpdate') && $key->hasOption('onUpdate')) {
            if ($key1->getOption('onUpdate') != $key2->getOption('onUpdate')) {
                return true;
            }
        } else if ($key1->hasOption('onUpdate') != $key2->hasOption('onUpdate')) {
288 289 290
            return true;
        }

291 292 293 294 295
        if ($key1->hasOption('onDelete') && $key2->hasOption('onDelete')) {
            if ($key1->getOption('onDelete') != $key2->getOption('onDelete')) {
                return true;
            }
        } else if ($key1->hasOption('onDelete') != $key2->hasOption('onDelete')) {
296 297 298 299 300 301
            return true;
        }

        return false;
    }

302 303 304 305 306 307 308 309 310
    /**
     * Returns the difference between the fields $field1 and $field2.
     *
     * If there are differences this method returns $field2, otherwise the
     * boolean false.
     *
     * @param Column $column1
     * @param Column $column2
     *
311
     * @return array
312
     */
313
    public function diffColumn(Column $column1, Column $column2)
314
    {
315
        $changedProperties = array();
316
        if ( $column1->getType() != $column2->getType() ) {
317
            $changedProperties[] = 'type';
318 319 320
        }

        if ($column1->getNotnull() != $column2->getNotnull()) {
321
            $changedProperties[] = 'notnull';
322 323 324
        }

        if ($column1->getDefault() != $column2->getDefault()) {
325
            $changedProperties[] = 'default';
326 327 328
        }

        if ($column1->getUnsigned() != $column2->getUnsigned()) {
329
            $changedProperties[] = 'unsigned';
330 331 332 333
        }

        if ($column1->getType() instanceof \Doctrine\DBAL\Types\StringType) {
            if ($column1->getLength() != $column2->getLength()) {
334
                $changedProperties[] = 'length';
335 336 337
            }

            if ($column1->getFixed() != $column2->getFixed()) {
338
                $changedProperties[] = 'fixed';
339 340 341 342 343
            }
        }

        if ($column1->getType() instanceof \Doctrine\DBAL\Types\DecimalType) {
            if ($column1->getPrecision() != $column2->getPrecision()) {
344
                $changedProperties[] = 'precision';
345 346
            }
            if ($column1->getScale() != $column2->getScale()) {
347
                $changedProperties[] = 'scale';
348 349 350 351
            }
        }

        foreach ($this->_checkColumnPlatformOptions AS $optionName) {
352 353 354 355 356 357
            if($column1->hasPlatformOption($optionName) && $column2->hasPlatformOption($optionName)) {
                if ($column1->getPlatformOption($optionName) != $column2->getPlatformOption($optionName)) {
                    $changedProperties[] = $optionName;
                }
            } else if ($column1->hasPlatformOption($optionName) != $column2->hasPlatformOption($optionName)) {
                $changedProperties[] = $optionName;
358
            }
359 360
        }

361
        return $changedProperties;
362 363 364 365 366 367 368 369 370 371
    }

    /**
     * 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.
     *
     * @param Index $index1
     * @param Index $index2
372
     * @return bool
373
     */
374
    public function diffIndex(Index $index1, Index $index2)
375 376
    {
        if($index1->isPrimary() != $index2->isPrimary()) {
377
            return true;
378 379
        }
        if($index1->isUnique() != $index2->isUnique()) {
380
            return true;
381 382 383 384 385 386 387
        }

        // Check for removed index fields in $index2
        $index1Columns = $index1->getColumns();
        for($i = 0; $i < count($index1Columns); $i++) {
            $indexColumn = $index1Columns[$i];
            if (!$index2->hasColumnAtPosition($indexColumn, $i)) {
388
                return true;
389 390 391 392 393 394 395 396
            }
        }

        // Check for new index fields in $index2
        $index2Columns = $index2->getColumns();
        for($i = 0; $i < count($index2Columns); $i++) {
            $indexColumn = $index2Columns[$i];
            if (!$index1->hasColumnAtPosition($indexColumn, $i)) {
397
                return true;
398 399 400 401 402 403
            }
        }

        return false;
    }
}