SchemaTool.php 29 KB

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