Comparator.php 19 KB

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