Comparator.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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. namespace Doctrine\DBAL\Schema;
  20. use Doctrine\DBAL\Types;
  21. /**
  22. * Compares two Schemas and return an instance of SchemaDiff.
  23. *
  24. * @link www.doctrine-project.org
  25. * @since 2.0
  26. * @author Benjamin Eberlei <kontakt@beberlei.de>
  27. */
  28. class Comparator
  29. {
  30. /**
  31. * @param \Doctrine\DBAL\Schema\Schema $fromSchema
  32. * @param \Doctrine\DBAL\Schema\Schema $toSchema
  33. *
  34. * @return \Doctrine\DBAL\Schema\SchemaDiff
  35. */
  36. static public function compareSchemas(Schema $fromSchema, Schema $toSchema)
  37. {
  38. $c = new self();
  39. return $c->compare($fromSchema, $toSchema);
  40. }
  41. /**
  42. * Returns a SchemaDiff object containing the differences between the schemas $fromSchema and $toSchema.
  43. *
  44. * The returned differences are returned in such a way that they contain the
  45. * operations to change the schema stored in $fromSchema to the schema that is
  46. * stored in $toSchema.
  47. *
  48. * @param \Doctrine\DBAL\Schema\Schema $fromSchema
  49. * @param \Doctrine\DBAL\Schema\Schema $toSchema
  50. *
  51. * @return \Doctrine\DBAL\Schema\SchemaDiff
  52. */
  53. public function compare(Schema $fromSchema, Schema $toSchema)
  54. {
  55. $diff = new SchemaDiff();
  56. $diff->fromSchema = $fromSchema;
  57. $foreignKeysToTable = array();
  58. foreach ($toSchema->getNamespaces() as $namespace) {
  59. if ( ! $fromSchema->hasNamespace($namespace)) {
  60. $diff->newNamespaces[$namespace] = $namespace;
  61. }
  62. }
  63. foreach ($fromSchema->getNamespaces() as $namespace) {
  64. if ( ! $toSchema->hasNamespace($namespace)) {
  65. $diff->removedNamespaces[$namespace] = $namespace;
  66. }
  67. }
  68. foreach ($toSchema->getTables() as $table) {
  69. $tableName = $table->getShortestName($toSchema->getName());
  70. if ( ! $fromSchema->hasTable($tableName)) {
  71. $diff->newTables[$tableName] = $toSchema->getTable($tableName);
  72. } else {
  73. $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
  74. if ($tableDifferences !== false) {
  75. $diff->changedTables[$tableName] = $tableDifferences;
  76. }
  77. }
  78. }
  79. /* Check if there are tables removed */
  80. foreach ($fromSchema->getTables() as $table) {
  81. $tableName = $table->getShortestName($fromSchema->getName());
  82. $table = $fromSchema->getTable($tableName);
  83. if ( ! $toSchema->hasTable($tableName)) {
  84. $diff->removedTables[$tableName] = $table;
  85. }
  86. // also remember all foreign keys that point to a specific table
  87. foreach ($table->getForeignKeys() as $foreignKey) {
  88. $foreignTable = strtolower($foreignKey->getForeignTableName());
  89. if (!isset($foreignKeysToTable[$foreignTable])) {
  90. $foreignKeysToTable[$foreignTable] = array();
  91. }
  92. $foreignKeysToTable[$foreignTable][] = $foreignKey;
  93. }
  94. }
  95. foreach ($diff->removedTables as $tableName => $table) {
  96. if (isset($foreignKeysToTable[$tableName])) {
  97. $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
  98. // deleting duplicated foreign keys present on both on the orphanedForeignKey
  99. // and the removedForeignKeys from changedTables
  100. foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
  101. // strtolower the table name to make if compatible with getShortestName
  102. $localTableName = strtolower($foreignKey->getLocalTableName());
  103. if (isset($diff->changedTables[$localTableName])) {
  104. foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
  105. // We check if the key is from the removed table if not we skip.
  106. if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
  107. continue;
  108. }
  109. unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
  110. }
  111. }
  112. }
  113. }
  114. }
  115. foreach ($toSchema->getSequences() as $sequence) {
  116. $sequenceName = $sequence->getShortestName($toSchema->getName());
  117. if ( ! $fromSchema->hasSequence($sequenceName)) {
  118. if ( ! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
  119. $diff->newSequences[] = $sequence;
  120. }
  121. } else {
  122. if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
  123. $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
  124. }
  125. }
  126. }
  127. foreach ($fromSchema->getSequences() as $sequence) {
  128. if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
  129. continue;
  130. }
  131. $sequenceName = $sequence->getShortestName($fromSchema->getName());
  132. if ( ! $toSchema->hasSequence($sequenceName)) {
  133. $diff->removedSequences[] = $sequence;
  134. }
  135. }
  136. return $diff;
  137. }
  138. /**
  139. * @param \Doctrine\DBAL\Schema\Schema $schema
  140. * @param \Doctrine\DBAL\Schema\Sequence $sequence
  141. *
  142. * @return boolean
  143. */
  144. private function isAutoIncrementSequenceInSchema($schema, $sequence)
  145. {
  146. foreach ($schema->getTables() as $table) {
  147. if ($sequence->isAutoIncrementsFor($table)) {
  148. return true;
  149. }
  150. }
  151. return false;
  152. }
  153. /**
  154. * @param \Doctrine\DBAL\Schema\Sequence $sequence1
  155. * @param \Doctrine\DBAL\Schema\Sequence $sequence2
  156. *
  157. * @return boolean
  158. */
  159. public function diffSequence(Sequence $sequence1, Sequence $sequence2)
  160. {
  161. if ($sequence1->getAllocationSize() != $sequence2->getAllocationSize()) {
  162. return true;
  163. }
  164. if ($sequence1->getInitialValue() != $sequence2->getInitialValue()) {
  165. return true;
  166. }
  167. return false;
  168. }
  169. /**
  170. * Returns the difference between the tables $table1 and $table2.
  171. *
  172. * If there are no differences this method returns the boolean false.
  173. *
  174. * @param \Doctrine\DBAL\Schema\Table $table1
  175. * @param \Doctrine\DBAL\Schema\Table $table2
  176. *
  177. * @return boolean|\Doctrine\DBAL\Schema\TableDiff
  178. */
  179. public function diffTable(Table $table1, Table $table2)
  180. {
  181. $changes = 0;
  182. $tableDifferences = new TableDiff($table1->getName());
  183. $tableDifferences->fromTable = $table1;
  184. $table1Columns = $table1->getColumns();
  185. $table2Columns = $table2->getColumns();
  186. /* See if all the fields in table 1 exist in table 2 */
  187. foreach ($table2Columns as $columnName => $column) {
  188. if ( !$table1->hasColumn($columnName)) {
  189. $tableDifferences->addedColumns[$columnName] = $column;
  190. $changes++;
  191. }
  192. }
  193. /* See if there are any removed fields in table 2 */
  194. foreach ($table1Columns as $columnName => $column) {
  195. // See if column is removed in table 2.
  196. if ( ! $table2->hasColumn($columnName)) {
  197. $tableDifferences->removedColumns[$columnName] = $column;
  198. $changes++;
  199. continue;
  200. }
  201. // See if column has changed properties in table 2.
  202. $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));
  203. if ( ! empty($changedProperties)) {
  204. $columnDiff = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
  205. $columnDiff->fromColumn = $column;
  206. $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
  207. $changes++;
  208. }
  209. }
  210. $this->detectColumnRenamings($tableDifferences);
  211. $table1Indexes = $table1->getIndexes();
  212. $table2Indexes = $table2->getIndexes();
  213. /* See if all the indexes in table 1 exist in table 2 */
  214. foreach ($table2Indexes as $indexName => $index) {
  215. if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
  216. continue;
  217. }
  218. $tableDifferences->addedIndexes[$indexName] = $index;
  219. $changes++;
  220. }
  221. /* See if there are any removed indexes in table 2 */
  222. foreach ($table1Indexes as $indexName => $index) {
  223. // See if index is removed in table 2.
  224. if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
  225. ! $index->isPrimary() && ! $table2->hasIndex($indexName)
  226. ) {
  227. $tableDifferences->removedIndexes[$indexName] = $index;
  228. $changes++;
  229. continue;
  230. }
  231. // See if index has changed in table 2.
  232. $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
  233. if ($this->diffIndex($index, $table2Index)) {
  234. $tableDifferences->changedIndexes[$indexName] = $table2Index;
  235. $changes++;
  236. }
  237. }
  238. $this->detectIndexRenamings($tableDifferences);
  239. $fromFkeys = $table1->getForeignKeys();
  240. $toFkeys = $table2->getForeignKeys();
  241. foreach ($fromFkeys as $key1 => $constraint1) {
  242. foreach ($toFkeys as $key2 => $constraint2) {
  243. if ($this->diffForeignKey($constraint1, $constraint2) === false) {
  244. unset($fromFkeys[$key1]);
  245. unset($toFkeys[$key2]);
  246. } else {
  247. if (strtolower($constraint1->getName()) == strtolower($constraint2->getName())) {
  248. $tableDifferences->changedForeignKeys[] = $constraint2;
  249. $changes++;
  250. unset($fromFkeys[$key1]);
  251. unset($toFkeys[$key2]);
  252. }
  253. }
  254. }
  255. }
  256. foreach ($fromFkeys as $constraint1) {
  257. $tableDifferences->removedForeignKeys[] = $constraint1;
  258. $changes++;
  259. }
  260. foreach ($toFkeys as $constraint2) {
  261. $tableDifferences->addedForeignKeys[] = $constraint2;
  262. $changes++;
  263. }
  264. return $changes ? $tableDifferences : false;
  265. }
  266. /**
  267. * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
  268. * however ambiguities between different possibilities should not lead to renaming at all.
  269. *
  270. * @param \Doctrine\DBAL\Schema\TableDiff $tableDifferences
  271. *
  272. * @return void
  273. */
  274. private function detectColumnRenamings(TableDiff $tableDifferences)
  275. {
  276. $renameCandidates = array();
  277. foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
  278. foreach ($tableDifferences->removedColumns as $removedColumn) {
  279. if (count($this->diffColumn($addedColumn, $removedColumn)) == 0) {
  280. $renameCandidates[$addedColumn->getName()][] = array($removedColumn, $addedColumn, $addedColumnName);
  281. }
  282. }
  283. }
  284. foreach ($renameCandidates as $candidateColumns) {
  285. if (count($candidateColumns) == 1) {
  286. list($removedColumn, $addedColumn) = $candidateColumns[0];
  287. $removedColumnName = strtolower($removedColumn->getName());
  288. $addedColumnName = strtolower($addedColumn->getName());
  289. if ( ! isset($tableDifferences->renamedColumns[$removedColumnName])) {
  290. $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
  291. unset($tableDifferences->addedColumns[$addedColumnName]);
  292. unset($tableDifferences->removedColumns[$removedColumnName]);
  293. }
  294. }
  295. }
  296. }
  297. /**
  298. * Try to find indexes that only changed their name, rename operations maybe cheaper than add/drop
  299. * however ambiguities between different possibilities should not lead to renaming at all.
  300. *
  301. * @param \Doctrine\DBAL\Schema\TableDiff $tableDifferences
  302. *
  303. * @return void
  304. */
  305. private function detectIndexRenamings(TableDiff $tableDifferences)
  306. {
  307. $renameCandidates = array();
  308. // Gather possible rename candidates by comparing each added and removed index based on semantics.
  309. foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
  310. foreach ($tableDifferences->removedIndexes as $removedIndex) {
  311. if (! $this->diffIndex($addedIndex, $removedIndex)) {
  312. $renameCandidates[$addedIndex->getName()][] = array($removedIndex, $addedIndex, $addedIndexName);
  313. }
  314. }
  315. }
  316. foreach ($renameCandidates as $candidateIndexes) {
  317. // If the current rename candidate contains exactly one semantically equal index,
  318. // we can safely rename it.
  319. // Otherwise it is unclear if a rename action is really intended,
  320. // therefore we let those ambiguous indexes be added/dropped.
  321. if (count($candidateIndexes) === 1) {
  322. list($removedIndex, $addedIndex) = $candidateIndexes[0];
  323. $removedIndexName = strtolower($removedIndex->getName());
  324. $addedIndexName = strtolower($addedIndex->getName());
  325. if (! isset($tableDifferences->renamedIndexes[$removedIndexName])) {
  326. $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
  327. unset($tableDifferences->addedIndexes[$addedIndexName]);
  328. unset($tableDifferences->removedIndexes[$removedIndexName]);
  329. }
  330. }
  331. }
  332. }
  333. /**
  334. * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $key1
  335. * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $key2
  336. *
  337. * @return boolean
  338. */
  339. public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
  340. {
  341. if (array_map('strtolower', $key1->getUnquotedLocalColumns()) != array_map('strtolower', $key2->getUnquotedLocalColumns())) {
  342. return true;
  343. }
  344. if (array_map('strtolower', $key1->getUnquotedForeignColumns()) != array_map('strtolower', $key2->getUnquotedForeignColumns())) {
  345. return true;
  346. }
  347. if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
  348. return true;
  349. }
  350. if ($key1->onUpdate() != $key2->onUpdate()) {
  351. return true;
  352. }
  353. if ($key1->onDelete() != $key2->onDelete()) {
  354. return true;
  355. }
  356. return false;
  357. }
  358. /**
  359. * Returns the difference between the fields $field1 and $field2.
  360. *
  361. * If there are differences this method returns $field2, otherwise the
  362. * boolean false.
  363. *
  364. * @param \Doctrine\DBAL\Schema\Column $column1
  365. * @param \Doctrine\DBAL\Schema\Column $column2
  366. *
  367. * @return array
  368. */
  369. public function diffColumn(Column $column1, Column $column2)
  370. {
  371. $properties1 = $column1->toArray();
  372. $properties2 = $column2->toArray();
  373. $changedProperties = array();
  374. foreach (array('type', 'notnull', 'unsigned', 'autoincrement') as $property) {
  375. if ($properties1[$property] != $properties2[$property]) {
  376. $changedProperties[] = $property;
  377. }
  378. }
  379. if ($properties1['default'] != $properties2['default'] ||
  380. // Null values need to be checked additionally as they tell whether to create or drop a default value.
  381. // null != 0, null != false, null != '' etc. This affects platform's table alteration SQL generation.
  382. (null === $properties1['default'] && null !== $properties2['default']) ||
  383. (null === $properties2['default'] && null !== $properties1['default'])
  384. ) {
  385. $changedProperties[] = 'default';
  386. }
  387. if (($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
  388. $properties1['type'] instanceof Types\BinaryType
  389. ) {
  390. // check if value of length is set at all, default value assumed otherwise.
  391. $length1 = $properties1['length'] ?: 255;
  392. $length2 = $properties2['length'] ?: 255;
  393. if ($length1 != $length2) {
  394. $changedProperties[] = 'length';
  395. }
  396. if ($properties1['fixed'] != $properties2['fixed']) {
  397. $changedProperties[] = 'fixed';
  398. }
  399. } elseif ($properties1['type'] instanceof Types\DecimalType) {
  400. if (($properties1['precision'] ?: 10) != ($properties2['precision'] ?: 10)) {
  401. $changedProperties[] = 'precision';
  402. }
  403. if ($properties1['scale'] != $properties2['scale']) {
  404. $changedProperties[] = 'scale';
  405. }
  406. }
  407. // A null value and an empty string are actually equal for a comment so they should not trigger a change.
  408. if ($properties1['comment'] !== $properties2['comment'] &&
  409. ! (null === $properties1['comment'] && '' === $properties2['comment']) &&
  410. ! (null === $properties2['comment'] && '' === $properties1['comment'])
  411. ) {
  412. $changedProperties[] = 'comment';
  413. }
  414. $customOptions1 = $column1->getCustomSchemaOptions();
  415. $customOptions2 = $column2->getCustomSchemaOptions();
  416. foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
  417. if ( ! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
  418. $changedProperties[] = $key;
  419. } elseif ($properties1[$key] !== $properties2[$key]) {
  420. $changedProperties[] = $key;
  421. }
  422. }
  423. $platformOptions1 = $column1->getPlatformOptions();
  424. $platformOptions2 = $column2->getPlatformOptions();
  425. foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
  426. if ($properties1[$key] !== $properties2[$key]) {
  427. $changedProperties[] = $key;
  428. }
  429. }
  430. return array_unique($changedProperties);
  431. }
  432. /**
  433. * Finds the difference between the indexes $index1 and $index2.
  434. *
  435. * Compares $index1 with $index2 and returns $index2 if there are any
  436. * differences or false in case there are no differences.
  437. *
  438. * @param \Doctrine\DBAL\Schema\Index $index1
  439. * @param \Doctrine\DBAL\Schema\Index $index2
  440. *
  441. * @return boolean
  442. */
  443. public function diffIndex(Index $index1, Index $index2)
  444. {
  445. if ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1)) {
  446. return false;
  447. }
  448. return true;
  449. }
  450. }