vendor/doctrine/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php
changeset 0 7f95f8617b0b
equal deleted inserted replaced
-1:000000000000 0:7f95f8617b0b
       
     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\Mapping\Driver;
       
    21 
       
    22 use Doctrine\Common\Cache\ArrayCache,
       
    23     Doctrine\Common\Annotations\AnnotationReader,
       
    24     Doctrine\DBAL\Schema\AbstractSchemaManager,
       
    25     Doctrine\DBAL\Schema\SchemaException,
       
    26     Doctrine\ORM\Mapping\ClassMetadataInfo,
       
    27     Doctrine\ORM\Mapping\MappingException,
       
    28     Doctrine\Common\Util\Inflector;
       
    29 
       
    30 /**
       
    31  * The DatabaseDriver reverse engineers the mapping metadata from a database.
       
    32  *
       
    33  * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
       
    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  Benjamin Eberlei <kontakt@beberlei.de>
       
    39  */
       
    40 class DatabaseDriver implements Driver
       
    41 {
       
    42     /**
       
    43      * @var AbstractSchemaManager
       
    44      */
       
    45     private $_sm;
       
    46 
       
    47     /**
       
    48      * @var array
       
    49      */
       
    50     private $tables = null;
       
    51 
       
    52     private $classToTableNames = array();
       
    53 
       
    54     /**
       
    55      * @var array
       
    56      */
       
    57     private $manyToManyTables = array();
       
    58 
       
    59     /**
       
    60      * @var array
       
    61      */
       
    62     private $classNamesForTables = array();
       
    63 
       
    64     /**
       
    65      * @var array
       
    66      */
       
    67     private $fieldNamesForColumns = array();
       
    68 
       
    69     /**
       
    70      * The namespace for the generated entities.
       
    71      *
       
    72      * @var string
       
    73      */
       
    74     private $namespace;
       
    75 
       
    76     /**
       
    77      * Initializes a new AnnotationDriver that uses the given AnnotationReader for reading
       
    78      * docblock annotations.
       
    79      * 
       
    80      * @param AnnotationReader $reader The AnnotationReader to use.
       
    81      */
       
    82     public function __construct(AbstractSchemaManager $schemaManager)
       
    83     {
       
    84         $this->_sm = $schemaManager;
       
    85     }
       
    86 
       
    87     /**
       
    88      * Set tables manually instead of relying on the reverse engeneering capabilities of SchemaManager.
       
    89      *
       
    90      * @param array $entityTables
       
    91      * @param array $manyToManyTables
       
    92      * @return void
       
    93      */
       
    94     public function setTables($entityTables, $manyToManyTables)
       
    95     {
       
    96         $this->tables = $this->manyToManyTables = $this->classToTableNames = array();
       
    97         foreach ($entityTables AS $table) {
       
    98             $className = $this->getClassNameForTable($table->getName());
       
    99             $this->classToTableNames[$className] = $table->getName();
       
   100             $this->tables[$table->getName()] = $table;
       
   101         }
       
   102         foreach ($manyToManyTables AS $table) {
       
   103             $this->manyToManyTables[$table->getName()] = $table;
       
   104         }
       
   105     }
       
   106 
       
   107     private function reverseEngineerMappingFromDatabase()
       
   108     {
       
   109         if ($this->tables !== null) {
       
   110             return;
       
   111         }
       
   112 
       
   113         $tables = array();
       
   114                 
       
   115         foreach ($this->_sm->listTableNames() as $tableName) {
       
   116             $tables[$tableName] = $this->_sm->listTableDetails($tableName);
       
   117         }
       
   118 
       
   119         $this->tables = $this->manyToManyTables = $this->classToTableNames = array();
       
   120         foreach ($tables AS $tableName => $table) {
       
   121             /* @var $table Table */
       
   122             if ($this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) {
       
   123                 $foreignKeys = $table->getForeignKeys();
       
   124             } else {
       
   125                 $foreignKeys = array();
       
   126             }
       
   127 
       
   128             $allForeignKeyColumns = array();
       
   129             foreach ($foreignKeys AS $foreignKey) {
       
   130                 $allForeignKeyColumns = array_merge($allForeignKeyColumns, $foreignKey->getLocalColumns());
       
   131             }
       
   132             
       
   133             $pkColumns = $table->getPrimaryKey()->getColumns();
       
   134             sort($pkColumns);
       
   135             sort($allForeignKeyColumns);
       
   136 
       
   137             if ($pkColumns == $allForeignKeyColumns && count($foreignKeys) == 2) {
       
   138                 $this->manyToManyTables[$tableName] = $table;
       
   139             } else {
       
   140                 // lower-casing is necessary because of Oracle Uppercase Tablenames,
       
   141                 // assumption is lower-case + underscore separated.
       
   142                 $className = $this->getClassNameForTable($tableName);
       
   143                 $this->tables[$tableName] = $table;
       
   144                 $this->classToTableNames[$className] = $tableName;
       
   145             }
       
   146         }
       
   147     }
       
   148     
       
   149     /**
       
   150      * {@inheritdoc}
       
   151      */
       
   152     public function loadMetadataForClass($className, ClassMetadataInfo $metadata)
       
   153     {
       
   154         $this->reverseEngineerMappingFromDatabase();
       
   155 
       
   156         if (!isset($this->classToTableNames[$className])) {
       
   157             throw new \InvalidArgumentException("Unknown class " . $className);
       
   158         }
       
   159 
       
   160         $tableName = $this->classToTableNames[$className];
       
   161 
       
   162         $metadata->name = $className;
       
   163         $metadata->table['name'] = $tableName;
       
   164 
       
   165         $columns = $this->tables[$tableName]->getColumns();
       
   166         $indexes = $this->tables[$tableName]->getIndexes();
       
   167         try {
       
   168             $primaryKeyColumns = $this->tables[$tableName]->getPrimaryKey()->getColumns();
       
   169         } catch(SchemaException $e) {
       
   170             $primaryKeyColumns = array();
       
   171         }
       
   172         
       
   173         if ($this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) {
       
   174             $foreignKeys = $this->tables[$tableName]->getForeignKeys();
       
   175         } else {
       
   176             $foreignKeys = array();
       
   177         }
       
   178 
       
   179         $allForeignKeyColumns = array();
       
   180         foreach ($foreignKeys AS $foreignKey) {
       
   181             $allForeignKeyColumns = array_merge($allForeignKeyColumns, $foreignKey->getLocalColumns());
       
   182         }
       
   183 
       
   184         $ids = array();
       
   185         $fieldMappings = array();
       
   186         foreach ($columns as $column) {
       
   187             $fieldMapping = array();
       
   188             if ($primaryKeyColumns && in_array($column->getName(), $primaryKeyColumns)) {
       
   189                 $fieldMapping['id'] = true;
       
   190             } else if (in_array($column->getName(), $allForeignKeyColumns)) {
       
   191                 continue;
       
   192             }
       
   193 
       
   194             $fieldMapping['fieldName'] = $this->getFieldNameForColumn($tableName, $column->getName(), false);
       
   195             $fieldMapping['columnName'] = $column->getName();
       
   196             $fieldMapping['type'] = strtolower((string) $column->getType());
       
   197 
       
   198             if ($column->getType() instanceof \Doctrine\DBAL\Types\StringType) {
       
   199                 $fieldMapping['length'] = $column->getLength();
       
   200                 $fieldMapping['fixed'] = $column->getFixed();
       
   201             } else if ($column->getType() instanceof \Doctrine\DBAL\Types\IntegerType) {
       
   202                 $fieldMapping['unsigned'] = $column->getUnsigned();
       
   203             }
       
   204             $fieldMapping['nullable'] = $column->getNotNull() ? false : true;
       
   205 
       
   206             if (isset($fieldMapping['id'])) {
       
   207                 $ids[] = $fieldMapping;
       
   208             } else {
       
   209                 $fieldMappings[] = $fieldMapping;
       
   210             }
       
   211         }
       
   212 
       
   213         if ($ids) {
       
   214             if (count($ids) == 1) {
       
   215                 $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO);
       
   216             }
       
   217 
       
   218             foreach ($ids as $id) {
       
   219                 $metadata->mapField($id);
       
   220             }
       
   221         }
       
   222 
       
   223         foreach ($fieldMappings as $fieldMapping) {
       
   224             $metadata->mapField($fieldMapping);
       
   225         }
       
   226 
       
   227         foreach ($this->manyToManyTables AS $manyTable) {
       
   228             foreach ($manyTable->getForeignKeys() AS $foreignKey) {
       
   229                 // foreign  key maps to the table of the current entity, many to many association probably exists
       
   230                 if (strtolower($tableName) == strtolower($foreignKey->getForeignTableName())) {
       
   231                     $myFk = $foreignKey;
       
   232                     $otherFk = null;
       
   233                     foreach ($manyTable->getForeignKeys() AS $foreignKey) {
       
   234                         if ($foreignKey != $myFk) {
       
   235                             $otherFk = $foreignKey;
       
   236                             break;
       
   237                         }
       
   238                     }
       
   239 
       
   240                     if (!$otherFk) {
       
   241                         // the definition of this many to many table does not contain
       
   242                         // enough foreign key information to continue reverse engeneering.
       
   243                         continue;
       
   244                     }
       
   245 
       
   246                     $localColumn = current($myFk->getColumns());
       
   247                     $associationMapping = array();
       
   248                     $associationMapping['fieldName'] = $this->getFieldNameForColumn($manyTable->getName(), current($otherFk->getColumns()), true);
       
   249                     $associationMapping['targetEntity'] = $this->getClassNameForTable($otherFk->getForeignTableName());
       
   250                     if (current($manyTable->getColumns())->getName() == $localColumn) {
       
   251                         $associationMapping['inversedBy'] = $this->getFieldNameForColumn($manyTable->getName(), current($myFk->getColumns()), true);
       
   252                         $associationMapping['joinTable'] = array(
       
   253                             'name' => strtolower($manyTable->getName()),
       
   254                             'joinColumns' => array(),
       
   255                             'inverseJoinColumns' => array(),
       
   256                         );
       
   257 
       
   258                         $fkCols = $myFk->getForeignColumns();
       
   259                         $cols = $myFk->getColumns();
       
   260                         for ($i = 0; $i < count($cols); $i++) {
       
   261                             $associationMapping['joinTable']['joinColumns'][] = array(
       
   262                                 'name' => $cols[$i],
       
   263                                 'referencedColumnName' => $fkCols[$i],
       
   264                             );
       
   265                         }
       
   266 
       
   267                         $fkCols = $otherFk->getForeignColumns();
       
   268                         $cols = $otherFk->getColumns();
       
   269                         for ($i = 0; $i < count($cols); $i++) {
       
   270                             $associationMapping['joinTable']['inverseJoinColumns'][] = array(
       
   271                                 'name' => $cols[$i],
       
   272                                 'referencedColumnName' => $fkCols[$i],
       
   273                             );
       
   274                         }
       
   275                     } else {
       
   276                         $associationMapping['mappedBy'] = $this->getFieldNameForColumn($manyTable->getName(), current($myFk->getColumns()), true);
       
   277                     }
       
   278                     $metadata->mapManyToMany($associationMapping);
       
   279                     break;
       
   280                 }
       
   281             }
       
   282         }
       
   283 
       
   284         foreach ($foreignKeys as $foreignKey) {
       
   285             $foreignTable = $foreignKey->getForeignTableName();
       
   286             $cols = $foreignKey->getColumns();
       
   287             $fkCols = $foreignKey->getForeignColumns();
       
   288 
       
   289             $localColumn = current($cols);
       
   290             $associationMapping = array();
       
   291             $associationMapping['fieldName'] = $this->getFieldNameForColumn($tableName, $localColumn, true);
       
   292             $associationMapping['targetEntity'] = $this->getClassNameForTable($foreignTable);
       
   293 
       
   294             for ($i = 0; $i < count($cols); $i++) {
       
   295                 $associationMapping['joinColumns'][] = array(
       
   296                     'name' => $cols[$i],
       
   297                     'referencedColumnName' => $fkCols[$i],
       
   298                 );
       
   299             }
       
   300             $metadata->mapManyToOne($associationMapping);
       
   301         }
       
   302     }
       
   303 
       
   304     /**
       
   305      * {@inheritdoc}
       
   306      */
       
   307     public function isTransient($className)
       
   308     {
       
   309         return true;
       
   310     }
       
   311 
       
   312     /**
       
   313      * Return all the class names supported by this driver.
       
   314      *
       
   315      * IMPORTANT: This method must return an array of class not tables names.
       
   316      *
       
   317      * @return array
       
   318      */
       
   319     public function getAllClassNames()
       
   320     {
       
   321         $this->reverseEngineerMappingFromDatabase();
       
   322 
       
   323         return array_keys($this->classToTableNames);
       
   324     }
       
   325 
       
   326     /**
       
   327      * Set class name for a table.
       
   328      *
       
   329      * @param string $tableName
       
   330      * @param string $className
       
   331      * @return void
       
   332      */
       
   333     public function setClassNameForTable($tableName, $className)
       
   334     {
       
   335         $this->classNamesForTables[$tableName] = $className;
       
   336     }
       
   337 
       
   338     /**
       
   339      * Set field name for a column on a specific table.
       
   340      *
       
   341      * @param string $tableName
       
   342      * @param string $columnName
       
   343      * @param string $fieldName
       
   344      * @return void
       
   345      */
       
   346     public function setFieldNameForColumn($tableName, $columnName, $fieldName)
       
   347     {
       
   348         $this->fieldNamesForColumns[$tableName][$columnName] = $fieldName;
       
   349     }
       
   350 
       
   351     /**
       
   352      * Return the mapped class name for a table if it exists. Otherwise return "classified" version.
       
   353      *
       
   354      * @param string $tableName
       
   355      * @return string
       
   356      */
       
   357     private function getClassNameForTable($tableName)
       
   358     {
       
   359         if (isset($this->classNamesForTables[$tableName])) {
       
   360             return $this->namespace . $this->classNamesForTables[$tableName];
       
   361         }
       
   362 
       
   363         return $this->namespace . Inflector::classify(strtolower($tableName));
       
   364     }
       
   365 
       
   366     /**
       
   367      * Return the mapped field name for a column, if it exists. Otherwise return camelized version.
       
   368      *
       
   369      * @param string $tableName
       
   370      * @param string $columnName
       
   371      * @param boolean $fk Whether the column is a foreignkey or not.
       
   372      * @return string
       
   373      */
       
   374     private function getFieldNameForColumn($tableName, $columnName, $fk = false)
       
   375     {
       
   376         if (isset($this->fieldNamesForColumns[$tableName]) && isset($this->fieldNamesForColumns[$tableName][$columnName])) {
       
   377             return $this->fieldNamesForColumns[$tableName][$columnName];
       
   378         }
       
   379 
       
   380         $columnName = strtolower($columnName);
       
   381 
       
   382         // Replace _id if it is a foreignkey column
       
   383         if ($fk) {
       
   384             $columnName = str_replace('_id', '', $columnName);
       
   385         }
       
   386         return Inflector::camelize($columnName);
       
   387     }
       
   388 
       
   389     /**
       
   390      * Set the namespace for the generated entities.
       
   391      *
       
   392      * @param string $namespace
       
   393      * @return void
       
   394      */
       
   395     public function setNamespace($namespace)
       
   396     {
       
   397         $this->namespace = $namespace;
       
   398     }
       
   399 }