SchemaTool.php 32 KB

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