Comparator.php 19 KB

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