DatabaseDriver.php 15 KB

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