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