123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690 |
- <?php
-
-
- namespace Doctrine\ORM\Tools;
-
- use Doctrine\ORM\ORMException,
- Doctrine\DBAL\Types\Type,
- Doctrine\ORM\EntityManager,
- Doctrine\ORM\Mapping\ClassMetadata,
- Doctrine\ORM\Internal\CommitOrderCalculator,
- Doctrine\ORM\Tools\Event\GenerateSchemaTableEventArgs,
- Doctrine\ORM\Tools\Event\GenerateSchemaEventArgs;
-
-
- class SchemaTool
- {
-
-
- private $_em;
-
-
-
- private $_platform;
-
-
-
- public function __construct(EntityManager $em)
- {
- $this->_em = $em;
- $this->_platform = $em->getConnection()->getDatabasePlatform();
- }
-
-
-
- public function createSchema(array $classes)
- {
- $createSchemaSql = $this->getCreateSchemaSql($classes);
- $conn = $this->_em->getConnection();
-
- foreach ($createSchemaSql as $sql) {
- $conn->executeQuery($sql);
- }
- }
-
-
-
- public function getCreateSchemaSql(array $classes)
- {
- $schema = $this->getSchemaFromMetadata($classes);
- return $schema->toSql($this->_platform);
- }
-
-
-
- private function processingNotRequired($class, array $processedClasses)
- {
- return (
- isset($processedClasses[$class->name]) ||
- $class->isMappedSuperclass ||
- ($class->isInheritanceTypeSingleTable() && $class->name != $class->rootEntityName)
- );
- }
-
-
-
- public function getSchemaFromMetadata(array $classes)
- {
- $processedClasses = array();
-
- $sm = $this->_em->getConnection()->getSchemaManager();
- $metadataSchemaConfig = $sm->createSchemaConfig();
- $metadataSchemaConfig->setExplicitForeignKeyIndexes(false);
- $schema = new \Doctrine\DBAL\Schema\Schema(array(), array(), $metadataSchemaConfig);
-
- $evm = $this->_em->getEventManager();
-
- foreach ($classes as $class) {
- if ($this->processingNotRequired($class, $processedClasses)) {
- continue;
- }
-
- $table = $schema->createTable($class->getQuotedTableName($this->_platform));
-
- $columns = array();
-
- if ($class->isInheritanceTypeSingleTable()) {
- $columns = $this->_gatherColumns($class, $table);
- $this->_gatherRelationsSql($class, $table, $schema);
-
-
- $discrColumnDef = $this->_getDiscriminatorColumnDefinition($class, $table);
-
-
- foreach ($class->parentClasses as $parentClassName) {
-
- $processedClasses[$parentClassName] = true;
- }
-
- foreach ($class->subClasses as $subClassName) {
- $subClass = $this->_em->getClassMetadata($subClassName);
- $this->_gatherColumns($subClass, $table);
- $this->_gatherRelationsSql($subClass, $table, $schema);
- $processedClasses[$subClassName] = true;
- }
- } else if ($class->isInheritanceTypeJoined()) {
-
- $pkColumns = array();
- foreach ($class->fieldMappings as $fieldName => $mapping) {
- if ( ! isset($mapping['inherited'])) {
- $columnName = $class->getQuotedColumnName($mapping['fieldName'], $this->_platform);
- $this->_gatherColumn($class, $mapping, $table);
-
- if ($class->isIdentifier($fieldName)) {
- $pkColumns[] = $columnName;
- }
- }
- }
-
- $this->_gatherRelationsSql($class, $table, $schema);
-
-
- if ($class->name == $class->rootEntityName) {
- $discrColumnDef = $this->_getDiscriminatorColumnDefinition($class, $table);
- } else {
-
-
- $idMapping = $class->fieldMappings[$class->identifier[0]];
- $this->_gatherColumn($class, $idMapping, $table);
- $columnName = $class->getQuotedColumnName($class->identifier[0], $this->_platform);
-
- $table->getColumn($columnName)->setAutoincrement(false);
-
- $pkColumns[] = $columnName;
-
-
- $table->addUnnamedForeignKeyConstraint(
- $this->_em->getClassMetadata($class->rootEntityName)->getQuotedTableName($this->_platform),
- array($columnName), array($columnName), array('onDelete' => 'CASCADE')
- );
- }
-
- $table->setPrimaryKey($pkColumns);
-
- } else if ($class->isInheritanceTypeTablePerClass()) {
- throw ORMException::notSupported();
- } else {
- $this->_gatherColumns($class, $table);
- $this->_gatherRelationsSql($class, $table, $schema);
- }
-
- $pkColumns = array();
- foreach ($class->identifier AS $identifierField) {
- if (isset($class->fieldMappings[$identifierField])) {
- $pkColumns[] = $class->getQuotedColumnName($identifierField, $this->_platform);
- } else if (isset($class->associationMappings[$identifierField])) {
-
- $assoc = $class->associationMappings[$identifierField];
- foreach ($assoc['joinColumns'] AS $joinColumn) {
- $pkColumns[] = $joinColumn['name'];
- }
- }
- }
- if (!$table->hasIndex('primary')) {
- $table->setPrimaryKey($pkColumns);
- }
-
- if (isset($class->table['indexes'])) {
- foreach ($class->table['indexes'] AS $indexName => $indexData) {
- $table->addIndex($indexData['columns'], is_numeric($indexName) ? null : $indexName);
- }
- }
-
- if (isset($class->table['uniqueConstraints'])) {
- foreach ($class->table['uniqueConstraints'] AS $indexName => $indexData) {
- $table->addUniqueIndex($indexData['columns'], is_numeric($indexName) ? null : $indexName);
- }
- }
-
- $processedClasses[$class->name] = true;
-
- if ($class->isIdGeneratorSequence() && $class->name == $class->rootEntityName) {
- $seqDef = $class->sequenceGeneratorDefinition;
-
- if (!$schema->hasSequence($seqDef['sequenceName'])) {
- $schema->createSequence(
- $seqDef['sequenceName'],
- $seqDef['allocationSize'],
- $seqDef['initialValue']
- );
- }
- }
-
- if ($evm->hasListeners(ToolEvents::postGenerateSchemaTable)) {
- $evm->dispatchEvent(ToolEvents::postGenerateSchemaTable, new GenerateSchemaTableEventArgs($class, $schema, $table));
- }
- }
-
- if ($evm->hasListeners(ToolEvents::postGenerateSchema)) {
- $evm->dispatchEvent(ToolEvents::postGenerateSchema, new GenerateSchemaEventArgs($this->_em, $schema));
- }
-
- return $schema;
- }
-
-
-
- private function _getDiscriminatorColumnDefinition($class, $table)
- {
- $discrColumn = $class->discriminatorColumn;
-
- if (!isset($discrColumn['type']) || (strtolower($discrColumn['type']) == 'string' && $discrColumn['length'] === null)) {
- $discrColumn['type'] = 'string';
- $discrColumn['length'] = 255;
- }
-
- $table->addColumn(
- $discrColumn['name'],
- $discrColumn['type'],
- array('length' => $discrColumn['length'], 'notnull' => true)
- );
- }
-
-
-
- private function _gatherColumns($class, $table)
- {
- $columns = array();
- $pkColumns = array();
-
- foreach ($class->fieldMappings as $fieldName => $mapping) {
- if ($class->isInheritanceTypeSingleTable() && isset($mapping['inherited'])) {
- continue;
- }
-
- $column = $this->_gatherColumn($class, $mapping, $table);
-
- if ($class->isIdentifier($mapping['fieldName'])) {
- $pkColumns[] = $class->getQuotedColumnName($mapping['fieldName'], $this->_platform);
- }
- }
-
-
-
- if(!$table->hasIndex('primary')) {
-
- }
-
- return $columns;
- }
-
-
-
- private function _gatherColumn($class, array $mapping, $table)
- {
- $columnName = $class->getQuotedColumnName($mapping['fieldName'], $this->_platform);
- $columnType = $mapping['type'];
-
- $options = array();
- $options['length'] = isset($mapping['length']) ? $mapping['length'] : null;
- $options['notnull'] = isset($mapping['nullable']) ? ! $mapping['nullable'] : true;
- if ($class->isInheritanceTypeSingleTable() && count($class->parentClasses) > 0) {
- $options['notnull'] = false;
- }
-
- $options['platformOptions'] = array();
- $options['platformOptions']['version'] = $class->isVersioned && $class->versionField == $mapping['fieldName'] ? true : false;
-
- if(strtolower($columnType) == 'string' && $options['length'] === null) {
- $options['length'] = 255;
- }
-
- if (isset($mapping['precision'])) {
- $options['precision'] = $mapping['precision'];
- }
-
- if (isset($mapping['scale'])) {
- $options['scale'] = $mapping['scale'];
- }
-
- if (isset($mapping['default'])) {
- $options['default'] = $mapping['default'];
- }
-
- if (isset($mapping['columnDefinition'])) {
- $options['columnDefinition'] = $mapping['columnDefinition'];
- }
-
- if ($class->isIdGeneratorIdentity() && $class->getIdentifierFieldNames() == array($mapping['fieldName'])) {
- $options['autoincrement'] = true;
- }
- if ($class->isInheritanceTypeJoined() && $class->name != $class->rootEntityName) {
- $options['autoincrement'] = false;
- }
-
- if ($table->hasColumn($columnName)) {
-
- $table->changeColumn($columnName, $options);
- } else {
- $table->addColumn($columnName, $columnType, $options);
- }
-
- $isUnique = isset($mapping['unique']) ? $mapping['unique'] : false;
- if ($isUnique) {
- $table->addUniqueIndex(array($columnName));
- }
- }
-
-
-
- private function _gatherRelationsSql($class, $table, $schema)
- {
- foreach ($class->associationMappings as $fieldName => $mapping) {
- if (isset($mapping['inherited'])) {
- continue;
- }
-
- $foreignClass = $this->_em->getClassMetadata($mapping['targetEntity']);
-
- if ($mapping['type'] & ClassMetadata::TO_ONE && $mapping['isOwningSide']) {
- $primaryKeyColumns = $uniqueConstraints = array();
-
- $this->_gatherRelationJoinColumns($mapping['joinColumns'], $table, $foreignClass, $mapping, $primaryKeyColumns, $uniqueConstraints);
-
- foreach($uniqueConstraints AS $indexName => $unique) {
- $table->addUniqueIndex($unique['columns'], is_numeric($indexName) ? null : $indexName);
- }
- } else if ($mapping['type'] == ClassMetadata::ONE_TO_MANY && $mapping['isOwningSide']) {
-
- throw ORMException::notSupported();
- } else if ($mapping['type'] == ClassMetadata::MANY_TO_MANY && $mapping['isOwningSide']) {
-
- $joinTable = $mapping['joinTable'];
-
- $theJoinTable = $schema->createTable($foreignClass->getQuotedJoinTableName($mapping, $this->_platform));
-
- $primaryKeyColumns = $uniqueConstraints = array();
-
-
- $this->_gatherRelationJoinColumns($joinTable['joinColumns'], $theJoinTable, $class, $mapping, $primaryKeyColumns, $uniqueConstraints);
-
-
- $this->_gatherRelationJoinColumns($joinTable['inverseJoinColumns'], $theJoinTable, $foreignClass, $mapping, $primaryKeyColumns, $uniqueConstraints);
-
- $theJoinTable->setPrimaryKey($primaryKeyColumns);
-
- foreach($uniqueConstraints AS $indexName => $unique) {
- $theJoinTable->addUniqueIndex($unique['columns'], is_numeric($indexName) ? null : $indexName);
- }
- }
- }
- }
-
-
-
- private function getDefiningClass($class, $referencedColumnName)
- {
- $referencedFieldName = $class->getFieldName($referencedColumnName);
-
- if ($class->hasField($referencedFieldName)) {
- return array($class, $referencedFieldName);
- } else if (in_array($referencedColumnName, $class->getIdentifierColumnNames())) {
-
- foreach ($class->getIdentifierFieldNames() AS $fieldName) {
- if ($class->hasAssociation($fieldName) && $class->getSingleAssociationJoinColumnName($fieldName) == $referencedColumnName) {
- return $this->getDefiningClass(
- $this->_em->getClassMetadata($class->associationMappings[$fieldName]['targetEntity']),
- $class->getSingleAssociationReferencedJoinColumnName($fieldName)
- );
- }
- }
- }
-
- return null;
- }
-
-
-
- private function _gatherRelationJoinColumns($joinColumns, $theJoinTable, $class, $mapping, &$primaryKeyColumns, &$uniqueConstraints)
- {
- $localColumns = array();
- $foreignColumns = array();
- $fkOptions = array();
- $foreignTableName = $class->getQuotedTableName($this->_platform);
-
- foreach ($joinColumns as $joinColumn) {
- $columnName = $joinColumn['name'];
- list($definingClass, $referencedFieldName) = $this->getDefiningClass($class, $joinColumn['referencedColumnName']);
-
- if (!$definingClass) {
- throw new \Doctrine\ORM\ORMException(
- "Column name `".$joinColumn['referencedColumnName']."` referenced for relation from ".
- $mapping['sourceEntity'] . " towards ". $mapping['targetEntity'] . " does not exist."
- );
- }
-
- $primaryKeyColumns[] = $columnName;
- $localColumns[] = $columnName;
- $foreignColumns[] = $joinColumn['referencedColumnName'];
-
- if ( ! $theJoinTable->hasColumn($joinColumn['name'])) {
-
-
-
-
- $fieldMapping = $definingClass->getFieldMapping($referencedFieldName);
-
- $columnDef = null;
- if (isset($joinColumn['columnDefinition'])) {
- $columnDef = $joinColumn['columnDefinition'];
- } else if (isset($fieldMapping['columnDefinition'])) {
- $columnDef = $fieldMapping['columnDefinition'];
- }
- $columnOptions = array('notnull' => false, 'columnDefinition' => $columnDef);
- if (isset($joinColumn['nullable'])) {
- $columnOptions['notnull'] = !$joinColumn['nullable'];
- }
- if ($fieldMapping['type'] == "string" && isset($fieldMapping['length'])) {
- $columnOptions['length'] = $fieldMapping['length'];
- } else if ($fieldMapping['type'] == "decimal") {
- $columnOptions['scale'] = $fieldMapping['scale'];
- $columnOptions['precision'] = $fieldMapping['precision'];
- }
-
- $theJoinTable->addColumn($columnName, $fieldMapping['type'], $columnOptions);
- }
-
- if (isset($joinColumn['unique']) && $joinColumn['unique'] == true) {
- $uniqueConstraints[] = array('columns' => array($columnName));
- }
-
- if (isset($joinColumn['onUpdate'])) {
- $fkOptions['onUpdate'] = $joinColumn['onUpdate'];
- }
-
- if (isset($joinColumn['onDelete'])) {
- $fkOptions['onDelete'] = $joinColumn['onDelete'];
- }
- }
-
- $theJoinTable->addUnnamedForeignKeyConstraint(
- $foreignTableName, $localColumns, $foreignColumns, $fkOptions
- );
- }
-
-
-
- public function dropSchema(array $classes)
- {
- $dropSchemaSql = $this->getDropSchemaSQL($classes);
- $conn = $this->_em->getConnection();
-
- foreach ($dropSchemaSql as $sql) {
- try {
- $conn->executeQuery($sql);
- } catch(\Exception $e) {
-
- }
- }
- }
-
-
-
- public function dropDatabase()
- {
- $dropSchemaSql = $this->getDropDatabaseSQL();
- $conn = $this->_em->getConnection();
-
- foreach ($dropSchemaSql as $sql) {
- $conn->executeQuery($sql);
- }
- }
-
-
-
- public function getDropDatabaseSQL()
- {
- $sm = $this->_em->getConnection()->getSchemaManager();
- $schema = $sm->createSchema();
-
- $visitor = new \Doctrine\DBAL\Schema\Visitor\DropSchemaSqlCollector($this->_platform);
-
- $schema->visit($visitor);
- return $visitor->getQueries();
- }
-
-
-
- public function getDropSchemaSQL(array $classes)
- {
- $visitor = new \Doctrine\DBAL\Schema\Visitor\DropSchemaSqlCollector($this->_platform);
- $schema = $this->getSchemaFromMetadata($classes);
-
- $sm = $this->_em->getConnection()->getSchemaManager();
- $fullSchema = $sm->createSchema();
- foreach ($fullSchema->getTables() AS $table) {
- if (!$schema->hasTable($table->getName())) {
- foreach ($table->getForeignKeys() AS $foreignKey) {
-
- if ($schema->hasTable($foreignKey->getForeignTableName())) {
- $visitor->acceptForeignKey($table, $foreignKey);
- }
- }
- } else {
- $visitor->acceptTable($table);
- foreach ($table->getForeignKeys() AS $foreignKey) {
- $visitor->acceptForeignKey($table, $foreignKey);
- }
- }
- }
-
- if ($this->_platform->supportsSequences()) {
- foreach ($schema->getSequences() AS $sequence) {
- $visitor->acceptSequence($sequence);
- }
- foreach ($schema->getTables() AS $table) {
-
- if ($table->hasPrimaryKey()) {
- $columns = $table->getPrimaryKey()->getColumns();
- if (count($columns) == 1) {
- $checkSequence = $table->getName() . "_" . $columns[0] . "_seq";
- if ($fullSchema->hasSequence($checkSequence)) {
- $visitor->acceptSequence($fullSchema->getSequence($checkSequence));
- }
- }
- }
- }
- }
-
- return $visitor->getQueries();
- }
-
-
-
- public function updateSchema(array $classes, $saveMode=false)
- {
- $updateSchemaSql = $this->getUpdateSchemaSql($classes, $saveMode);
- $conn = $this->_em->getConnection();
-
- foreach ($updateSchemaSql as $sql) {
- $conn->executeQuery($sql);
- }
- }
-
-
-
- public function getUpdateSchemaSql(array $classes, $saveMode=false)
- {
- $sm = $this->_em->getConnection()->getSchemaManager();
-
- $fromSchema = $sm->createSchema();
- $toSchema = $this->getSchemaFromMetadata($classes);
-
- $comparator = new \Doctrine\DBAL\Schema\Comparator();
- $schemaDiff = $comparator->compare($fromSchema, $toSchema);
-
- if ($saveMode) {
- return $schemaDiff->toSaveSql($this->_platform);
- } else {
- return $schemaDiff->toSql($this->_platform);
- }
- }
- }
|