SchemaTool.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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\ORM\Tools;
  20. use Doctrine\DBAL\Platforms\AbstractPlatform;
  21. use Doctrine\DBAL\Schema\AbstractAsset;
  22. use Doctrine\DBAL\Schema\Comparator;
  23. use Doctrine\DBAL\Schema\Index;
  24. use Doctrine\DBAL\Schema\Schema;
  25. use Doctrine\DBAL\Schema\Table;
  26. use Doctrine\DBAL\Schema\Visitor\DropSchemaSqlCollector;
  27. use Doctrine\DBAL\Schema\Visitor\RemoveNamespacedAssets;
  28. use Doctrine\ORM\EntityManagerInterface;
  29. use Doctrine\ORM\Mapping\ClassMetadata;
  30. use Doctrine\ORM\Mapping\QuoteStrategy;
  31. use Doctrine\ORM\ORMException;
  32. use Doctrine\ORM\Tools\Event\GenerateSchemaEventArgs;
  33. use Doctrine\ORM\Tools\Event\GenerateSchemaTableEventArgs;
  34. use Throwable;
  35. use function array_diff;
  36. use function array_diff_key;
  37. use function array_filter;
  38. use function array_flip;
  39. use function array_intersect_key;
  40. use function assert;
  41. use function count;
  42. use function current;
  43. use function implode;
  44. use function in_array;
  45. use function is_array;
  46. use function is_numeric;
  47. use function strtolower;
  48. /**
  49. * The SchemaTool is a tool to create/drop/update database schemas based on
  50. * <tt>ClassMetadata</tt> class descriptors.
  51. *
  52. * @link www.doctrine-project.org
  53. */
  54. class SchemaTool
  55. {
  56. private const KNOWN_COLUMN_OPTIONS = ['comment', 'unsigned', 'fixed', 'default'];
  57. /** @var EntityManagerInterface */
  58. private $em;
  59. /** @var AbstractPlatform */
  60. private $platform;
  61. /**
  62. * The quote strategy.
  63. *
  64. * @var QuoteStrategy
  65. */
  66. private $quoteStrategy;
  67. /**
  68. * Initializes a new SchemaTool instance that uses the connection of the
  69. * provided EntityManager.
  70. */
  71. public function __construct(EntityManagerInterface $em)
  72. {
  73. $this->em = $em;
  74. $this->platform = $em->getConnection()->getDatabasePlatform();
  75. $this->quoteStrategy = $em->getConfiguration()->getQuoteStrategy();
  76. }
  77. /**
  78. * Creates the database schema for the given array of ClassMetadata instances.
  79. *
  80. * @return void
  81. *
  82. * @throws ToolsException
  83. *
  84. * @psalm-param list<ClassMetadata> $classes
  85. */
  86. public function createSchema(array $classes)
  87. {
  88. $createSchemaSql = $this->getCreateSchemaSql($classes);
  89. $conn = $this->em->getConnection();
  90. foreach ($createSchemaSql as $sql) {
  91. try {
  92. $conn->executeQuery($sql);
  93. } catch (Throwable $e) {
  94. throw ToolsException::schemaToolFailure($sql, $e);
  95. }
  96. }
  97. }
  98. /**
  99. * Gets the list of DDL statements that are required to create the database schema for
  100. * the given list of ClassMetadata instances.
  101. *
  102. * @return string[] The SQL statements needed to create the schema for the classes.
  103. *
  104. * @psalm-param list<ClassMetadata> $classes
  105. */
  106. public function getCreateSchemaSql(array $classes)
  107. {
  108. $schema = $this->getSchemaFromMetadata($classes);
  109. return $schema->toSql($this->platform);
  110. }
  111. /**
  112. * Detects instances of ClassMetadata that don't need to be processed in the SchemaTool context.
  113. *
  114. * @psalm-param array<string, bool> $processedClasses
  115. */
  116. private function processingNotRequired(
  117. ClassMetadata $class,
  118. array $processedClasses
  119. ): bool {
  120. return isset($processedClasses[$class->name]) ||
  121. $class->isMappedSuperclass ||
  122. $class->isEmbeddedClass ||
  123. ($class->isInheritanceTypeSingleTable() && $class->name !== $class->rootEntityName);
  124. }
  125. /**
  126. * Creates a Schema instance from a given set of metadata classes.
  127. *
  128. * @return Schema
  129. *
  130. * @throws ORMException
  131. *
  132. * @psalm-param list<ClassMetadata> $classes
  133. */
  134. public function getSchemaFromMetadata(array $classes)
  135. {
  136. // Reminder for processed classes, used for hierarchies
  137. $processedClasses = [];
  138. $eventManager = $this->em->getEventManager();
  139. $schemaManager = $this->em->getConnection()->getSchemaManager();
  140. $metadataSchemaConfig = $schemaManager->createSchemaConfig();
  141. $metadataSchemaConfig->setExplicitForeignKeyIndexes(false);
  142. $schema = new Schema([], [], $metadataSchemaConfig);
  143. $addedFks = [];
  144. $blacklistedFks = [];
  145. foreach ($classes as $class) {
  146. if ($this->processingNotRequired($class, $processedClasses)) {
  147. continue;
  148. }
  149. $table = $schema->createTable($this->quoteStrategy->getTableName($class, $this->platform));
  150. if ($class->isInheritanceTypeSingleTable()) {
  151. $this->gatherColumns($class, $table);
  152. $this->gatherRelationsSql($class, $table, $schema, $addedFks, $blacklistedFks);
  153. // Add the discriminator column
  154. $this->addDiscriminatorColumnDefinition($class, $table);
  155. // Aggregate all the information from all classes in the hierarchy
  156. foreach ($class->parentClasses as $parentClassName) {
  157. // Parent class information is already contained in this class
  158. $processedClasses[$parentClassName] = true;
  159. }
  160. foreach ($class->subClasses as $subClassName) {
  161. $subClass = $this->em->getClassMetadata($subClassName);
  162. $this->gatherColumns($subClass, $table);
  163. $this->gatherRelationsSql($subClass, $table, $schema, $addedFks, $blacklistedFks);
  164. $processedClasses[$subClassName] = true;
  165. }
  166. } elseif ($class->isInheritanceTypeJoined()) {
  167. // Add all non-inherited fields as columns
  168. foreach ($class->fieldMappings as $fieldName => $mapping) {
  169. if (! isset($mapping['inherited'])) {
  170. $this->gatherColumn($class, $mapping, $table);
  171. }
  172. }
  173. $this->gatherRelationsSql($class, $table, $schema, $addedFks, $blacklistedFks);
  174. // Add the discriminator column only to the root table
  175. if ($class->name === $class->rootEntityName) {
  176. $this->addDiscriminatorColumnDefinition($class, $table);
  177. } else {
  178. // Add an ID FK column to child tables
  179. $pkColumns = [];
  180. $inheritedKeyColumns = [];
  181. foreach ($class->identifier as $identifierField) {
  182. if (isset($class->fieldMappings[$identifierField]['inherited'])) {
  183. $idMapping = $class->fieldMappings[$identifierField];
  184. $this->gatherColumn($class, $idMapping, $table);
  185. $columnName = $this->quoteStrategy->getColumnName(
  186. $identifierField,
  187. $class,
  188. $this->platform
  189. );
  190. // TODO: This seems rather hackish, can we optimize it?
  191. $table->getColumn($columnName)->setAutoincrement(false);
  192. $pkColumns[] = $columnName;
  193. $inheritedKeyColumns[] = $columnName;
  194. continue;
  195. }
  196. if (isset($class->associationMappings[$identifierField]['inherited'])) {
  197. $idMapping = $class->associationMappings[$identifierField];
  198. $targetEntity = current(
  199. array_filter(
  200. $classes,
  201. static function (ClassMetadata $class) use ($idMapping): bool {
  202. return $class->name === $idMapping['targetEntity'];
  203. }
  204. )
  205. );
  206. foreach ($idMapping['joinColumns'] as $joinColumn) {
  207. if (isset($targetEntity->fieldMappings[$joinColumn['referencedColumnName']])) {
  208. $columnName = $this->quoteStrategy->getJoinColumnName(
  209. $joinColumn,
  210. $class,
  211. $this->platform
  212. );
  213. $pkColumns[] = $columnName;
  214. $inheritedKeyColumns[] = $columnName;
  215. }
  216. }
  217. }
  218. }
  219. if (! empty($inheritedKeyColumns)) {
  220. // Add a FK constraint on the ID column
  221. $table->addForeignKeyConstraint(
  222. $this->quoteStrategy->getTableName(
  223. $this->em->getClassMetadata($class->rootEntityName),
  224. $this->platform
  225. ),
  226. $inheritedKeyColumns,
  227. $inheritedKeyColumns,
  228. ['onDelete' => 'CASCADE']
  229. );
  230. }
  231. if (! empty($pkColumns)) {
  232. $table->setPrimaryKey($pkColumns);
  233. }
  234. }
  235. } elseif ($class->isInheritanceTypeTablePerClass()) {
  236. throw ORMException::notSupported();
  237. } else {
  238. $this->gatherColumns($class, $table);
  239. $this->gatherRelationsSql($class, $table, $schema, $addedFks, $blacklistedFks);
  240. }
  241. $pkColumns = [];
  242. foreach ($class->identifier as $identifierField) {
  243. if (isset($class->fieldMappings[$identifierField])) {
  244. $pkColumns[] = $this->quoteStrategy->getColumnName($identifierField, $class, $this->platform);
  245. } elseif (isset($class->associationMappings[$identifierField])) {
  246. $assoc = $class->associationMappings[$identifierField];
  247. assert(is_array($assoc));
  248. foreach ($assoc['joinColumns'] as $joinColumn) {
  249. $pkColumns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform);
  250. }
  251. }
  252. }
  253. if (! $table->hasIndex('primary')) {
  254. $table->setPrimaryKey($pkColumns);
  255. }
  256. // there can be unique indexes automatically created for join column
  257. // if join column is also primary key we should keep only primary key on this column
  258. // so, remove indexes overruled by primary key
  259. $primaryKey = $table->getIndex('primary');
  260. foreach ($table->getIndexes() as $idxKey => $existingIndex) {
  261. if ($primaryKey->overrules($existingIndex)) {
  262. $table->dropIndex($idxKey);
  263. }
  264. }
  265. if (isset($class->table['indexes'])) {
  266. foreach ($class->table['indexes'] as $indexName => $indexData) {
  267. if (! isset($indexData['flags'])) {
  268. $indexData['flags'] = [];
  269. }
  270. $table->addIndex($indexData['columns'], is_numeric($indexName) ? null : $indexName, (array) $indexData['flags'], $indexData['options'] ?? []);
  271. }
  272. }
  273. if (isset($class->table['uniqueConstraints'])) {
  274. foreach ($class->table['uniqueConstraints'] as $indexName => $indexData) {
  275. $uniqIndex = new Index($indexName, $indexData['columns'], true, false, [], $indexData['options'] ?? []);
  276. foreach ($table->getIndexes() as $tableIndexName => $tableIndex) {
  277. if ($tableIndex->isFullfilledBy($uniqIndex)) {
  278. $table->dropIndex($tableIndexName);
  279. break;
  280. }
  281. }
  282. $table->addUniqueIndex($indexData['columns'], is_numeric($indexName) ? null : $indexName, $indexData['options'] ?? []);
  283. }
  284. }
  285. if (isset($class->table['options'])) {
  286. foreach ($class->table['options'] as $key => $val) {
  287. $table->addOption($key, $val);
  288. }
  289. }
  290. $processedClasses[$class->name] = true;
  291. if ($class->isIdGeneratorSequence() && $class->name === $class->rootEntityName) {
  292. $seqDef = $class->sequenceGeneratorDefinition;
  293. $quotedName = $this->quoteStrategy->getSequenceName($seqDef, $class, $this->platform);
  294. if (! $schema->hasSequence($quotedName)) {
  295. $schema->createSequence(
  296. $quotedName,
  297. $seqDef['allocationSize'],
  298. $seqDef['initialValue']
  299. );
  300. }
  301. }
  302. if ($eventManager->hasListeners(ToolEvents::postGenerateSchemaTable)) {
  303. $eventManager->dispatchEvent(
  304. ToolEvents::postGenerateSchemaTable,
  305. new GenerateSchemaTableEventArgs($class, $schema, $table)
  306. );
  307. }
  308. }
  309. if (! $this->platform->supportsSchemas() && ! $this->platform->canEmulateSchemas()) {
  310. $schema->visit(new RemoveNamespacedAssets());
  311. }
  312. if ($eventManager->hasListeners(ToolEvents::postGenerateSchema)) {
  313. $eventManager->dispatchEvent(
  314. ToolEvents::postGenerateSchema,
  315. new GenerateSchemaEventArgs($this->em, $schema)
  316. );
  317. }
  318. return $schema;
  319. }
  320. /**
  321. * Gets a portable column definition as required by the DBAL for the discriminator
  322. * column of a class.
  323. *
  324. * @param ClassMetadata $class
  325. *
  326. * @return void
  327. */
  328. private function addDiscriminatorColumnDefinition($class, Table $table)
  329. {
  330. $discrColumn = $class->discriminatorColumn;
  331. if (
  332. ! isset($discrColumn['type']) ||
  333. (strtolower($discrColumn['type']) === 'string' && ! isset($discrColumn['length']))
  334. ) {
  335. $discrColumn['type'] = 'string';
  336. $discrColumn['length'] = 255;
  337. }
  338. $options = [
  339. 'length' => $discrColumn['length'] ?? null,
  340. 'notnull' => true,
  341. ];
  342. if (isset($discrColumn['columnDefinition'])) {
  343. $options['columnDefinition'] = $discrColumn['columnDefinition'];
  344. }
  345. $table->addColumn($discrColumn['name'], $discrColumn['type'], $options);
  346. }
  347. /**
  348. * Gathers the column definitions as required by the DBAL of all field mappings
  349. * found in the given class.
  350. *
  351. * @param ClassMetadata $class
  352. *
  353. * @return void
  354. */
  355. private function gatherColumns($class, Table $table)
  356. {
  357. $pkColumns = [];
  358. foreach ($class->fieldMappings as $mapping) {
  359. if ($class->isInheritanceTypeSingleTable() && isset($mapping['inherited'])) {
  360. continue;
  361. }
  362. $this->gatherColumn($class, $mapping, $table);
  363. if ($class->isIdentifier($mapping['fieldName'])) {
  364. $pkColumns[] = $this->quoteStrategy->getColumnName($mapping['fieldName'], $class, $this->platform);
  365. }
  366. }
  367. }
  368. /**
  369. * Creates a column definition as required by the DBAL from an ORM field mapping definition.
  370. *
  371. * @param ClassMetadata $class The class that owns the field mapping.
  372. *
  373. * @psalm-param array<string, mixed> $mapping The field mapping.
  374. */
  375. private function gatherColumn(
  376. ClassMetadata $class,
  377. array $mapping,
  378. Table $table
  379. ): void {
  380. $columnName = $this->quoteStrategy->getColumnName($mapping['fieldName'], $class, $this->platform);
  381. $columnType = $mapping['type'];
  382. $options = [];
  383. $options['length'] = $mapping['length'] ?? null;
  384. $options['notnull'] = isset($mapping['nullable']) ? ! $mapping['nullable'] : true;
  385. if ($class->isInheritanceTypeSingleTable() && $class->parentClasses) {
  386. $options['notnull'] = false;
  387. }
  388. $options['platformOptions'] = [];
  389. $options['platformOptions']['version'] = $class->isVersioned && $class->versionField === $mapping['fieldName'];
  390. if (strtolower($columnType) === 'string' && $options['length'] === null) {
  391. $options['length'] = 255;
  392. }
  393. if (isset($mapping['precision'])) {
  394. $options['precision'] = $mapping['precision'];
  395. }
  396. if (isset($mapping['scale'])) {
  397. $options['scale'] = $mapping['scale'];
  398. }
  399. if (isset($mapping['default'])) {
  400. $options['default'] = $mapping['default'];
  401. }
  402. if (isset($mapping['columnDefinition'])) {
  403. $options['columnDefinition'] = $mapping['columnDefinition'];
  404. }
  405. // the 'default' option can be overwritten here
  406. $options = $this->gatherColumnOptions($mapping) + $options;
  407. if ($class->isIdGeneratorIdentity() && $class->getIdentifierFieldNames() === [$mapping['fieldName']]) {
  408. $options['autoincrement'] = true;
  409. }
  410. if ($class->isInheritanceTypeJoined() && $class->name !== $class->rootEntityName) {
  411. $options['autoincrement'] = false;
  412. }
  413. if ($table->hasColumn($columnName)) {
  414. // required in some inheritance scenarios
  415. $table->changeColumn($columnName, $options);
  416. } else {
  417. $table->addColumn($columnName, $columnType, $options);
  418. }
  419. $isUnique = $mapping['unique'] ?? false;
  420. if ($isUnique) {
  421. $table->addUniqueIndex([$columnName]);
  422. }
  423. }
  424. /**
  425. * Gathers the SQL for properly setting up the relations of the given class.
  426. * This includes the SQL for foreign key constraints and join tables.
  427. *
  428. * @throws ORMException
  429. *
  430. * @psalm-param array<string, array{
  431. * foreignTableName: string,
  432. * foreignColumns: list<string>
  433. * }> $addedFks
  434. * @psalm-param array<string, bool> $blacklistedFks
  435. */
  436. private function gatherRelationsSql(
  437. ClassMetadata $class,
  438. Table $table,
  439. Schema $schema,
  440. array &$addedFks,
  441. array &$blacklistedFks
  442. ): void {
  443. foreach ($class->associationMappings as $id => $mapping) {
  444. if (isset($mapping['inherited']) && ! in_array($id, $class->identifier, true)) {
  445. continue;
  446. }
  447. $foreignClass = $this->em->getClassMetadata($mapping['targetEntity']);
  448. if ($mapping['type'] & ClassMetadata::TO_ONE && $mapping['isOwningSide']) {
  449. $primaryKeyColumns = []; // PK is unnecessary for this relation-type
  450. $this->gatherRelationJoinColumns(
  451. $mapping['joinColumns'],
  452. $table,
  453. $foreignClass,
  454. $mapping,
  455. $primaryKeyColumns,
  456. $addedFks,
  457. $blacklistedFks
  458. );
  459. } elseif ($mapping['type'] === ClassMetadata::ONE_TO_MANY && $mapping['isOwningSide']) {
  460. //... create join table, one-many through join table supported later
  461. throw ORMException::notSupported();
  462. } elseif ($mapping['type'] === ClassMetadata::MANY_TO_MANY && $mapping['isOwningSide']) {
  463. // create join table
  464. $joinTable = $mapping['joinTable'];
  465. $theJoinTable = $schema->createTable(
  466. $this->quoteStrategy->getJoinTableName($mapping, $foreignClass, $this->platform)
  467. );
  468. $primaryKeyColumns = [];
  469. // Build first FK constraint (relation table => source table)
  470. $this->gatherRelationJoinColumns(
  471. $joinTable['joinColumns'],
  472. $theJoinTable,
  473. $class,
  474. $mapping,
  475. $primaryKeyColumns,
  476. $addedFks,
  477. $blacklistedFks
  478. );
  479. // Build second FK constraint (relation table => target table)
  480. $this->gatherRelationJoinColumns(
  481. $joinTable['inverseJoinColumns'],
  482. $theJoinTable,
  483. $foreignClass,
  484. $mapping,
  485. $primaryKeyColumns,
  486. $addedFks,
  487. $blacklistedFks
  488. );
  489. $theJoinTable->setPrimaryKey($primaryKeyColumns);
  490. }
  491. }
  492. }
  493. /**
  494. * Gets the class metadata that is responsible for the definition of the referenced column name.
  495. *
  496. * Previously this was a simple task, but with DDC-117 this problem is actually recursive. If its
  497. * not a simple field, go through all identifier field names that are associations recursively and
  498. * find that referenced column name.
  499. *
  500. * TODO: Is there any way to make this code more pleasing?
  501. *
  502. * @psalm-return array{ClassMetadata, string}|null
  503. */
  504. private function getDefiningClass(ClassMetadata $class, string $referencedColumnName): ?array
  505. {
  506. $referencedFieldName = $class->getFieldName($referencedColumnName);
  507. if ($class->hasField($referencedFieldName)) {
  508. return [$class, $referencedFieldName];
  509. }
  510. if (in_array($referencedColumnName, $class->getIdentifierColumnNames())) {
  511. // it seems to be an entity as foreign key
  512. foreach ($class->getIdentifierFieldNames() as $fieldName) {
  513. if (
  514. $class->hasAssociation($fieldName)
  515. && $class->getSingleAssociationJoinColumnName($fieldName) === $referencedColumnName
  516. ) {
  517. return $this->getDefiningClass(
  518. $this->em->getClassMetadata($class->associationMappings[$fieldName]['targetEntity']),
  519. $class->getSingleAssociationReferencedJoinColumnName($fieldName)
  520. );
  521. }
  522. }
  523. }
  524. return null;
  525. }
  526. /**
  527. * Gathers columns and fk constraints that are required for one part of relationship.
  528. *
  529. * @throws ORMException
  530. *
  531. * @psalm-param array<string, mixed> $joinColumns
  532. * @psalm-param array<string, mixed> $mapping
  533. * @psalm-param list<string> $primaryKeyColumns
  534. * @psalm-param array<string, array{
  535. * foreignTableName: string,
  536. * foreignColumns: list<string>
  537. * }> $addedFks
  538. * @psalm-param array<string,bool> $blacklistedFks
  539. */
  540. private function gatherRelationJoinColumns(
  541. array $joinColumns,
  542. Table $theJoinTable,
  543. ClassMetadata $class,
  544. array $mapping,
  545. array &$primaryKeyColumns,
  546. array &$addedFks,
  547. array &$blacklistedFks
  548. ): void {
  549. $localColumns = [];
  550. $foreignColumns = [];
  551. $fkOptions = [];
  552. $foreignTableName = $this->quoteStrategy->getTableName($class, $this->platform);
  553. $uniqueConstraints = [];
  554. foreach ($joinColumns as $joinColumn) {
  555. [$definingClass, $referencedFieldName] = $this->getDefiningClass(
  556. $class,
  557. $joinColumn['referencedColumnName']
  558. );
  559. if (! $definingClass) {
  560. throw new ORMException(
  561. 'Column name `' . $joinColumn['referencedColumnName'] . '` referenced for relation from '
  562. . $mapping['sourceEntity'] . ' towards ' . $mapping['targetEntity'] . ' does not exist.'
  563. );
  564. }
  565. $quotedColumnName = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform);
  566. $quotedRefColumnName = $this->quoteStrategy->getReferencedJoinColumnName(
  567. $joinColumn,
  568. $class,
  569. $this->platform
  570. );
  571. $primaryKeyColumns[] = $quotedColumnName;
  572. $localColumns[] = $quotedColumnName;
  573. $foreignColumns[] = $quotedRefColumnName;
  574. if (! $theJoinTable->hasColumn($quotedColumnName)) {
  575. // Only add the column to the table if it does not exist already.
  576. // It might exist already if the foreign key is mapped into a regular
  577. // property as well.
  578. $fieldMapping = $definingClass->getFieldMapping($referencedFieldName);
  579. $columnDef = null;
  580. if (isset($joinColumn['columnDefinition'])) {
  581. $columnDef = $joinColumn['columnDefinition'];
  582. } elseif (isset($fieldMapping['columnDefinition'])) {
  583. $columnDef = $fieldMapping['columnDefinition'];
  584. }
  585. $columnOptions = ['notnull' => false, 'columnDefinition' => $columnDef];
  586. if (isset($joinColumn['nullable'])) {
  587. $columnOptions['notnull'] = ! $joinColumn['nullable'];
  588. }
  589. $columnOptions += $this->gatherColumnOptions($fieldMapping);
  590. if ($fieldMapping['type'] === 'string' && isset($fieldMapping['length'])) {
  591. $columnOptions['length'] = $fieldMapping['length'];
  592. } elseif ($fieldMapping['type'] === 'decimal') {
  593. $columnOptions['scale'] = $fieldMapping['scale'];
  594. $columnOptions['precision'] = $fieldMapping['precision'];
  595. }
  596. $theJoinTable->addColumn($quotedColumnName, $fieldMapping['type'], $columnOptions);
  597. }
  598. if (isset($joinColumn['unique']) && $joinColumn['unique'] === true) {
  599. $uniqueConstraints[] = ['columns' => [$quotedColumnName]];
  600. }
  601. if (isset($joinColumn['onDelete'])) {
  602. $fkOptions['onDelete'] = $joinColumn['onDelete'];
  603. }
  604. }
  605. // Prefer unique constraints over implicit simple indexes created for foreign keys.
  606. // Also avoids index duplication.
  607. foreach ($uniqueConstraints as $indexName => $unique) {
  608. $theJoinTable->addUniqueIndex($unique['columns'], is_numeric($indexName) ? null : $indexName);
  609. }
  610. $compositeName = $theJoinTable->getName() . '.' . implode('', $localColumns);
  611. if (
  612. isset($addedFks[$compositeName])
  613. && ($foreignTableName !== $addedFks[$compositeName]['foreignTableName']
  614. || 0 < count(array_diff($foreignColumns, $addedFks[$compositeName]['foreignColumns'])))
  615. ) {
  616. foreach ($theJoinTable->getForeignKeys() as $fkName => $key) {
  617. if (
  618. count(array_diff($key->getLocalColumns(), $localColumns)) === 0
  619. && (($key->getForeignTableName() !== $foreignTableName)
  620. || 0 < count(array_diff($key->getForeignColumns(), $foreignColumns)))
  621. ) {
  622. $theJoinTable->removeForeignKey($fkName);
  623. break;
  624. }
  625. }
  626. $blacklistedFks[$compositeName] = true;
  627. } elseif (! isset($blacklistedFks[$compositeName])) {
  628. $addedFks[$compositeName] = ['foreignTableName' => $foreignTableName, 'foreignColumns' => $foreignColumns];
  629. $theJoinTable->addUnnamedForeignKeyConstraint(
  630. $foreignTableName,
  631. $localColumns,
  632. $foreignColumns,
  633. $fkOptions
  634. );
  635. }
  636. }
  637. /**
  638. * @param mixed[] $mapping
  639. *
  640. * @return mixed[]
  641. */
  642. private function gatherColumnOptions(array $mapping): array
  643. {
  644. if (! isset($mapping['options'])) {
  645. return [];
  646. }
  647. $options = array_intersect_key($mapping['options'], array_flip(self::KNOWN_COLUMN_OPTIONS));
  648. $options['customSchemaOptions'] = array_diff_key($mapping['options'], $options);
  649. return $options;
  650. }
  651. /**
  652. * Drops the database schema for the given classes.
  653. *
  654. * In any way when an exception is thrown it is suppressed since drop was
  655. * issued for all classes of the schema and some probably just don't exist.
  656. *
  657. * @return void
  658. *
  659. * @psalm-param list<ClassMetadata> $classes
  660. */
  661. public function dropSchema(array $classes)
  662. {
  663. $dropSchemaSql = $this->getDropSchemaSQL($classes);
  664. $conn = $this->em->getConnection();
  665. foreach ($dropSchemaSql as $sql) {
  666. try {
  667. $conn->executeQuery($sql);
  668. } catch (Throwable $e) {
  669. // ignored
  670. }
  671. }
  672. }
  673. /**
  674. * Drops all elements in the database of the current connection.
  675. *
  676. * @return void
  677. */
  678. public function dropDatabase()
  679. {
  680. $dropSchemaSql = $this->getDropDatabaseSQL();
  681. $conn = $this->em->getConnection();
  682. foreach ($dropSchemaSql as $sql) {
  683. $conn->executeQuery($sql);
  684. }
  685. }
  686. /**
  687. * Gets the SQL needed to drop the database schema for the connections database.
  688. *
  689. * @return string[]
  690. */
  691. public function getDropDatabaseSQL()
  692. {
  693. $sm = $this->em->getConnection()->getSchemaManager();
  694. $schema = $sm->createSchema();
  695. $visitor = new DropSchemaSqlCollector($this->platform);
  696. $schema->visit($visitor);
  697. return $visitor->getQueries();
  698. }
  699. /**
  700. * Gets SQL to drop the tables defined by the passed classes.
  701. *
  702. * @return string[]
  703. *
  704. * @psalm-param list<ClassMetadata> $classes
  705. */
  706. public function getDropSchemaSQL(array $classes)
  707. {
  708. $visitor = new DropSchemaSqlCollector($this->platform);
  709. $schema = $this->getSchemaFromMetadata($classes);
  710. $sm = $this->em->getConnection()->getSchemaManager();
  711. $fullSchema = $sm->createSchema();
  712. foreach ($fullSchema->getTables() as $table) {
  713. if (! $schema->hasTable($table->getName())) {
  714. foreach ($table->getForeignKeys() as $foreignKey) {
  715. if ($schema->hasTable($foreignKey->getForeignTableName())) {
  716. $visitor->acceptForeignKey($table, $foreignKey);
  717. }
  718. }
  719. } else {
  720. $visitor->acceptTable($table);
  721. foreach ($table->getForeignKeys() as $foreignKey) {
  722. $visitor->acceptForeignKey($table, $foreignKey);
  723. }
  724. }
  725. }
  726. if ($this->platform->supportsSequences()) {
  727. foreach ($schema->getSequences() as $sequence) {
  728. $visitor->acceptSequence($sequence);
  729. }
  730. foreach ($schema->getTables() as $table) {
  731. if ($table->hasPrimaryKey()) {
  732. $columns = $table->getPrimaryKey()->getColumns();
  733. if (count($columns) === 1) {
  734. $checkSequence = $table->getName() . '_' . $columns[0] . '_seq';
  735. if ($fullSchema->hasSequence($checkSequence)) {
  736. $visitor->acceptSequence($fullSchema->getSequence($checkSequence));
  737. }
  738. }
  739. }
  740. }
  741. }
  742. return $visitor->getQueries();
  743. }
  744. /**
  745. * Updates the database schema of the given classes by comparing the ClassMetadata
  746. * instances to the current database schema that is inspected.
  747. *
  748. * @param mixed[] $classes
  749. * @param bool $saveMode If TRUE, only performs a partial update
  750. * without dropping assets which are scheduled for deletion.
  751. *
  752. * @return void
  753. */
  754. public function updateSchema(array $classes, $saveMode = false)
  755. {
  756. $updateSchemaSql = $this->getUpdateSchemaSql($classes, $saveMode);
  757. $conn = $this->em->getConnection();
  758. foreach ($updateSchemaSql as $sql) {
  759. $conn->executeQuery($sql);
  760. }
  761. }
  762. /**
  763. * Gets the sequence of SQL statements that need to be performed in order
  764. * to bring the given class mappings in-synch with the relational schema.
  765. *
  766. * @param mixed[] $classes The classes to consider.
  767. * @param bool $saveMode If TRUE, only generates SQL for a partial update
  768. * that does not include SQL for dropping assets which are scheduled for deletion.
  769. *
  770. * @return string[] The sequence of SQL statements.
  771. */
  772. public function getUpdateSchemaSql(array $classes, $saveMode = false)
  773. {
  774. $toSchema = $this->getSchemaFromMetadata($classes);
  775. $fromSchema = $this->createSchemaForComparison($toSchema);
  776. $comparator = new Comparator();
  777. $schemaDiff = $comparator->compare($fromSchema, $toSchema);
  778. if ($saveMode) {
  779. return $schemaDiff->toSaveSql($this->platform);
  780. }
  781. return $schemaDiff->toSql($this->platform);
  782. }
  783. /**
  784. * Creates the schema from the database, ensuring tables from the target schema are whitelisted for comparison.
  785. */
  786. private function createSchemaForComparison(Schema $toSchema): Schema
  787. {
  788. $connection = $this->em->getConnection();
  789. $schemaManager = $connection->getSchemaManager();
  790. // backup schema assets filter
  791. $config = $connection->getConfiguration();
  792. $previousFilter = $config->getSchemaAssetsFilter();
  793. if ($previousFilter === null) {
  794. return $schemaManager->createSchema();
  795. }
  796. // whitelist assets we already know about in $toSchema, use the existing filter otherwise
  797. $config->setSchemaAssetsFilter(static function ($asset) use ($previousFilter, $toSchema): bool {
  798. $assetName = $asset instanceof AbstractAsset ? $asset->getName() : $asset;
  799. return $toSchema->hasTable($assetName) || $toSchema->hasSequence($assetName) || $previousFilter($asset);
  800. });
  801. try {
  802. return $schemaManager->createSchema();
  803. } finally {
  804. // restore schema assets filter
  805. $config->setSchemaAssetsFilter($previousFilter);
  806. }
  807. }
  808. }