Skip to content

Commit

Permalink
Merge branch 'DDC-616'
Browse files Browse the repository at this point in the history
  • Loading branch information
beberlei committed Jun 20, 2010
2 parents 51e6681 + cd978fb commit 206710f
Show file tree
Hide file tree
Showing 2 changed files with 147 additions and 28 deletions.
138 changes: 119 additions & 19 deletions lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,20 @@
*/
class DatabaseDriver implements Driver
{
/** The SchemaManager. */
/**
* @var AbstractSchemaManager
*/
private $_sm;

/**
* @var array
*/
private $tables = null;

/**
* @var array
*/
private $manyToManyTables = array();

/**
* Initializes a new AnnotationDriver that uses the given AnnotationReader for reading
Expand All @@ -51,22 +63,69 @@ public function __construct(AbstractSchemaManager $schemaManager)
{
$this->_sm = $schemaManager;
}

private function reverseEngineerMappingFromDatabase()
{
if ($this->tables !== null) {
return;
}

foreach ($this->_sm->listTableNames() as $tableName) {
$tableName = strtolower($tableName);
$tables[$tableName] = $this->_sm->listTableDetails($tableName);
}

$this->tables = array();
foreach ($tables AS $name => $table) {
/* @var $table Table */
if ($this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) {
$foreignKeys = $table->getForeignKeys();
} else {
$foreignKeys = array();
}

$allForeignKeyColumns = array();
foreach ($foreignKeys AS $foreignKey) {
$allForeignKeyColumns = array_merge($allForeignKeyColumns, $foreignKey->getLocalColumns());
}

$pkColumns = $table->getPrimaryKey()->getColumns();
sort($pkColumns);
sort($allForeignKeyColumns);

if ($pkColumns == $allForeignKeyColumns) {
if (count($table->getForeignKeys()) != 2) {
throw new \InvalidArgumentException("ManyToMany tables with more or less than two foreign keys are not supported by the Database Reverese Engineering Driver.");
}

$this->manyToManyTables[$name] = $table;
} else {
$this->tables[$name] = $table;
}
}
}

/**
* {@inheritdoc}
*/
public function loadMetadataForClass($className, ClassMetadataInfo $metadata)
{
$tableName = $className;
$className = Inflector::classify(strtolower($tableName));
$this->reverseEngineerMappingFromDatabase();

$tableName = Inflector::tableize($className);

$metadata->name = $className;
$metadata->table['name'] = $tableName;

$columns = $this->_sm->listTableColumns($tableName);
if (!isset($this->tables[$tableName])) {
throw new \InvalidArgumentException("Unknown table " . $tableName . " referred from class " . $className);
}

$columns = $this->tables[$tableName]->getColumns();
$indexes = $this->tables[$tableName]->getIndexes();

if ($this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) {
$foreignKeys = $this->_sm->listTableForeignKeys($tableName);
$foreignKeys = $this->tables[$tableName]->getForeignKeys();
} else {
$foreignKeys = array();
}
Expand All @@ -76,8 +135,6 @@ public function loadMetadataForClass($className, ClassMetadataInfo $metadata)
$allForeignKeyColumns = array_merge($allForeignKeyColumns, $foreignKey->getLocalColumns());
}

$indexes = $this->_sm->listTableIndexes($tableName);

$ids = array();
$fieldMappings = array();
foreach ($columns as $column) {
Expand Down Expand Up @@ -121,23 +178,71 @@ public function loadMetadataForClass($className, ClassMetadataInfo $metadata)
$metadata->mapField($fieldMapping);
}

foreach ($this->manyToManyTables AS $manyTable) {
foreach ($manyTable->getForeignKeys() AS $foreignKey) {
if ($tableName == strtolower($foreignKey->getForeignTableName())) {
$myFk = $foreignKey;
foreach ($manyTable->getForeignKeys() AS $foreignKey) {
if ($foreignKey != $myFk) {
$otherFk = $foreignKey;
break;
}
}

$localColumn = current($myFk->getColumns());
$associationMapping = array();
$associationMapping['fieldName'] = Inflector::camelize(str_replace('_id', '', strtolower(current($otherFk->getColumns()))));
$associationMapping['targetEntity'] = Inflector::classify(strtolower($otherFk->getForeignTableName()));
if (current($manyTable->getColumns())->getName() == $localColumn) {
$associationMapping['inversedBy'] = Inflector::camelize(str_replace('_id', '', strtolower(current($myFk->getColumns()))));
$associationMapping['joinTable'] = array(
'name' => strtolower($manyTable->getName()),
'joinColumns' => array(),
'inverseJoinColumns' => array(),
);

$fkCols = $myFk->getForeignColumns();
$cols = $myFk->getColumns();
for ($i = 0; $i < count($cols); $i++) {
$associationMapping['joinTable']['joinColumns'][] = array(
'name' => $cols[$i],
'referencedColumnName' => $fkCols[$i],
);
}

$fkCols = $otherFk->getForeignColumns();
$cols = $otherFk->getColumns();
for ($i = 0; $i < count($cols); $i++) {
$associationMapping['joinTable']['inverseJoinColumns'][] = array(
'name' => $cols[$i],
'referencedColumnName' => $fkCols[$i],
);
}
} else {
$associationMapping['mappedBy'] = Inflector::camelize(str_replace('_id', '', strtolower(current($myFk->getColumns()))));
}
$metadata->mapManyToMany($associationMapping);
break;
}
}
}

foreach ($foreignKeys as $foreignKey) {
$foreignTable = $foreignKey->getForeignTableName();
$cols = $foreignKey->getColumns();
$localColumn = current($cols);

$fkCols = $foreignKey->getForeignColumns();

$localColumn = current($cols);
$associationMapping = array();
$associationMapping['fieldName'] = Inflector::camelize(str_replace('_id', '', strtolower($localColumn)));
$associationMapping['targetEntity'] = Inflector::classify($foreignKey->getForeignTableName());
$associationMapping['targetEntity'] = Inflector::classify($foreignTable);

for ($i = 0; $i < count($cols); $i++) {
$associationMapping['joinColumns'][] = array(
'name' => $cols[$i],
'referencedColumnName' => $fkCols[$i],
);
}

$metadata->mapManyToOne($associationMapping);
}
}
Expand All @@ -153,19 +258,14 @@ public function isTransient($className)
/**
* Return all the class names supported by this driver.
*
* IMPORTANT: This method must return an array of table names because we need
* to know the table name after we inflect it to create the entity class name.
* IMPORTANT: This method must return an array of class not tables names.
*
* @return array
*/
public function getAllClassNames()
{
$classes = array();

foreach ($this->_sm->listTableNames() as $tableName) {
$classes[] = $tableName;
}
$this->reverseEngineerMappingFromDatabase();

return $classes;
return array_map(array('Doctrine\Common\Util\Inflector', 'classify'), array_keys($this->tables));
}
}
37 changes: 28 additions & 9 deletions tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ class DatabaseDriverTest extends \Doctrine\Tests\OrmFunctionalTestCase

public function setUp()
{
$this->useModelSet('cms');
parent::setUp();

$this->_sm = $this->_em->getConnection()->getSchemaManager();
Expand All @@ -36,8 +37,8 @@ public function testLoadMetadataFromDatabase()

$metadatas = $this->extractClassMetadata(array("DbdriverFoo"));

$this->assertArrayHasKey('dbdriver_foo', $metadatas);
$metadata = $metadatas['dbdriver_foo'];
$this->assertArrayHasKey('DbdriverFoo', $metadatas);
$metadata = $metadatas['DbdriverFoo'];

$this->assertArrayHasKey('id', $metadata->fieldMappings);
$this->assertEquals('id', $metadata->fieldMappings['id']['fieldName']);
Expand Down Expand Up @@ -74,8 +75,8 @@ public function testLoadMetadataWithForeignKeyFromDatabase()

$metadatas = $this->extractClassMetadata(array("DbdriverBar", "DbdriverBaz"));

$this->assertArrayHasKey('dbdriver_baz', $metadatas);
$bazMetadata = $metadatas['dbdriver_baz'];
$this->assertArrayHasKey('DbdriverBaz', $metadatas);
$bazMetadata = $metadatas['DbdriverBaz'];

$this->assertArrayNotHasKey('barId', $bazMetadata->fieldMappings, "The foreign Key field should not be inflected as 'barId' field, its an association.");
$this->assertArrayHasKey('id', $bazMetadata->fieldMappings);
Expand All @@ -86,6 +87,24 @@ public function testLoadMetadataWithForeignKeyFromDatabase()
$this->assertType('Doctrine\ORM\Mapping\OneToOneMapping', $bazMetadata->associationMappings['bar']);
}

public function testDetectManyToManyTables()
{
if (!$this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) {
$this->markTestSkipped('Platform does not support foreign keys.');
}

$metadatas = $this->extractClassMetadata(array("CmsUsers", "CmsGroups"));

$this->assertArrayHasKey('CmsUsers', $metadatas, 'CmsUsers entity was not detected.');
$this->assertArrayHasKey('CmsGroups', $metadatas, 'CmsGroups entity was not detected.');

$this->assertEquals(1, count($metadatas['CmsUsers']->associationMappings));
$this->assertArrayHasKey('group', $metadatas['CmsUsers']->associationMappings);
$this->assertEquals(1, count($metadatas['CmsGroups']->associationMappings));
$this->assertArrayHasKey('user', $metadatas['CmsGroups']->associationMappings);
}


/**
*
* @param string $className
Expand All @@ -97,13 +116,13 @@ protected function extractClassMetadata(array $classNames)
$metadatas = array();

$driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($this->_sm);
foreach ($driver->getAllClassNames() as $dbTableName) {
if (!in_array(strtolower(Inflector::classify($dbTableName)), $classNames)) {
foreach ($driver->getAllClassNames() as $className) {
if (!in_array(strtolower($className), $classNames)) {
continue;
}
$class = new ClassMetadataInfo($dbTableName);
$driver->loadMetadataForClass($dbTableName, $class);
$metadatas[strtolower($dbTableName)] = $class;
$class = new ClassMetadataInfo($className);
$driver->loadMetadataForClass($className, $class);
$metadatas[$className] = $class;
}

if (count($metadatas) != count($classNames)) {
Expand Down

0 comments on commit 206710f

Please sign in to comment.