DatabaseDriver.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. $pkColumns = $table->getPrimaryKey()->getColumns();
  117. sort($pkColumns);
  118. sort($allForeignKeyColumns);
  119. if ($pkColumns == $allForeignKeyColumns && count($foreignKeys) == 2) {
  120. $this->manyToManyTables[$tableName] = $table;
  121. } else {
  122. // lower-casing is necessary because of Oracle Uppercase Tablenames,
  123. // assumption is lower-case + underscore separated.
  124. $className = $this->getClassNameForTable($tableName);
  125. $this->tables[$tableName] = $table;
  126. $this->classToTableNames[$className] = $tableName;
  127. }
  128. }
  129. }
  130. /**
  131. * {@inheritdoc}
  132. */
  133. public function loadMetadataForClass($className, ClassMetadataInfo $metadata)
  134. {
  135. $this->reverseEngineerMappingFromDatabase();
  136. if (!isset($this->classToTableNames[$className])) {
  137. throw new \InvalidArgumentException("Unknown class " . $className);
  138. }
  139. $tableName = $this->classToTableNames[$className];
  140. $metadata->name = $className;
  141. $metadata->table['name'] = $tableName;
  142. $columns = $this->tables[$tableName]->getColumns();
  143. $indexes = $this->tables[$tableName]->getIndexes();
  144. try {
  145. $primaryKeyColumns = $this->tables[$tableName]->getPrimaryKey()->getColumns();
  146. } catch(SchemaException $e) {
  147. $primaryKeyColumns = array();
  148. }
  149. if ($this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) {
  150. $foreignKeys = $this->tables[$tableName]->getForeignKeys();
  151. } else {
  152. $foreignKeys = array();
  153. }
  154. $allForeignKeyColumns = array();
  155. foreach ($foreignKeys AS $foreignKey) {
  156. $allForeignKeyColumns = array_merge($allForeignKeyColumns, $foreignKey->getLocalColumns());
  157. }
  158. $ids = array();
  159. $fieldMappings = array();
  160. foreach ($columns as $column) {
  161. $fieldMapping = array();
  162. if (in_array($column->getName(), $allForeignKeyColumns)) {
  163. continue;
  164. } else if ($primaryKeyColumns && in_array($column->getName(), $primaryKeyColumns)) {
  165. $fieldMapping['id'] = true;
  166. }
  167. $fieldMapping['fieldName'] = $this->getFieldNameForColumn($tableName, $column->getName(), false);
  168. $fieldMapping['columnName'] = $column->getName();
  169. $fieldMapping['type'] = strtolower((string) $column->getType());
  170. if ($column->getType() instanceof \Doctrine\DBAL\Types\StringType) {
  171. $fieldMapping['length'] = $column->getLength();
  172. $fieldMapping['fixed'] = $column->getFixed();
  173. } else if ($column->getType() instanceof \Doctrine\DBAL\Types\IntegerType) {
  174. $fieldMapping['unsigned'] = $column->getUnsigned();
  175. }
  176. $fieldMapping['nullable'] = $column->getNotNull() ? false : true;
  177. if (isset($fieldMapping['id'])) {
  178. $ids[] = $fieldMapping;
  179. } else {
  180. $fieldMappings[] = $fieldMapping;
  181. }
  182. }
  183. if ($ids) {
  184. if (count($ids) == 1) {
  185. $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO);
  186. }
  187. foreach ($ids as $id) {
  188. $metadata->mapField($id);
  189. }
  190. }
  191. foreach ($fieldMappings as $fieldMapping) {
  192. $metadata->mapField($fieldMapping);
  193. }
  194. foreach ($this->manyToManyTables AS $manyTable) {
  195. foreach ($manyTable->getForeignKeys() AS $foreignKey) {
  196. // foreign key maps to the table of the current entity, many to many association probably exists
  197. if (strtolower($tableName) == strtolower($foreignKey->getForeignTableName())) {
  198. $myFk = $foreignKey;
  199. $otherFk = null;
  200. foreach ($manyTable->getForeignKeys() AS $foreignKey) {
  201. if ($foreignKey != $myFk) {
  202. $otherFk = $foreignKey;
  203. break;
  204. }
  205. }
  206. if (!$otherFk) {
  207. // the definition of this many to many table does not contain
  208. // enough foreign key information to continue reverse engeneering.
  209. continue;
  210. }
  211. $localColumn = current($myFk->getColumns());
  212. $associationMapping = array();
  213. $associationMapping['fieldName'] = $this->getFieldNameForColumn($manyTable->getName(), current($otherFk->getColumns()), true);
  214. $associationMapping['targetEntity'] = $this->getClassNameForTable($otherFk->getForeignTableName());
  215. if (current($manyTable->getColumns())->getName() == $localColumn) {
  216. $associationMapping['inversedBy'] = $this->getFieldNameForColumn($manyTable->getName(), current($myFk->getColumns()), true);
  217. $associationMapping['joinTable'] = array(
  218. 'name' => strtolower($manyTable->getName()),
  219. 'joinColumns' => array(),
  220. 'inverseJoinColumns' => array(),
  221. );
  222. $fkCols = $myFk->getForeignColumns();
  223. $cols = $myFk->getColumns();
  224. for ($i = 0; $i < count($cols); $i++) {
  225. $associationMapping['joinTable']['joinColumns'][] = array(
  226. 'name' => $cols[$i],
  227. 'referencedColumnName' => $fkCols[$i],
  228. );
  229. }
  230. $fkCols = $otherFk->getForeignColumns();
  231. $cols = $otherFk->getColumns();
  232. for ($i = 0; $i < count($cols); $i++) {
  233. $associationMapping['joinTable']['inverseJoinColumns'][] = array(
  234. 'name' => $cols[$i],
  235. 'referencedColumnName' => $fkCols[$i],
  236. );
  237. }
  238. } else {
  239. $associationMapping['mappedBy'] = $this->getFieldNameForColumn($manyTable->getName(), current($myFk->getColumns()), true);
  240. }
  241. $metadata->mapManyToMany($associationMapping);
  242. break;
  243. }
  244. }
  245. }
  246. foreach ($foreignKeys as $foreignKey) {
  247. $foreignTable = $foreignKey->getForeignTableName();
  248. $cols = $foreignKey->getColumns();
  249. $fkCols = $foreignKey->getForeignColumns();
  250. $localColumn = current($cols);
  251. $associationMapping = array();
  252. $associationMapping['fieldName'] = $this->getFieldNameForColumn($tableName, $localColumn, true);
  253. $associationMapping['targetEntity'] = $this->getClassNameForTable($foreignTable);
  254. if ($primaryKeyColumns && in_array($localColumn, $primaryKeyColumns)) {
  255. $associationMapping['id'] = true;
  256. }
  257. for ($i = 0; $i < count($cols); $i++) {
  258. $associationMapping['joinColumns'][] = array(
  259. 'name' => $cols[$i],
  260. 'referencedColumnName' => $fkCols[$i],
  261. );
  262. }
  263. //Here we need to check if $cols are the same as $primaryKeyColums
  264. if (!array_diff($cols,$primaryKeyColumns)) {
  265. $metadata->mapOneToOne($associationMapping);
  266. } else {
  267. $metadata->mapManyToOne($associationMapping);
  268. }
  269. }
  270. }
  271. /**
  272. * {@inheritdoc}
  273. */
  274. public function isTransient($className)
  275. {
  276. return true;
  277. }
  278. /**
  279. * Return all the class names supported by this driver.
  280. *
  281. * IMPORTANT: This method must return an array of class not tables names.
  282. *
  283. * @return array
  284. */
  285. public function getAllClassNames()
  286. {
  287. $this->reverseEngineerMappingFromDatabase();
  288. return array_keys($this->classToTableNames);
  289. }
  290. /**
  291. * Set class name for a table.
  292. *
  293. * @param string $tableName
  294. * @param string $className
  295. * @return void
  296. */
  297. public function setClassNameForTable($tableName, $className)
  298. {
  299. $this->classNamesForTables[$tableName] = $className;
  300. }
  301. /**
  302. * Set field name for a column on a specific table.
  303. *
  304. * @param string $tableName
  305. * @param string $columnName
  306. * @param string $fieldName
  307. * @return void
  308. */
  309. public function setFieldNameForColumn($tableName, $columnName, $fieldName)
  310. {
  311. $this->fieldNamesForColumns[$tableName][$columnName] = $fieldName;
  312. }
  313. /**
  314. * Return the mapped class name for a table if it exists. Otherwise return "classified" version.
  315. *
  316. * @param string $tableName
  317. * @return string
  318. */
  319. private function getClassNameForTable($tableName)
  320. {
  321. if (isset($this->classNamesForTables[$tableName])) {
  322. return $this->namespace . $this->classNamesForTables[$tableName];
  323. }
  324. return $this->namespace . Inflector::classify(strtolower($tableName));
  325. }
  326. /**
  327. * Return the mapped field name for a column, if it exists. Otherwise return camelized version.
  328. *
  329. * @param string $tableName
  330. * @param string $columnName
  331. * @param boolean $fk Whether the column is a foreignkey or not.
  332. * @return string
  333. */
  334. private function getFieldNameForColumn($tableName, $columnName, $fk = false)
  335. {
  336. if (isset($this->fieldNamesForColumns[$tableName]) && isset($this->fieldNamesForColumns[$tableName][$columnName])) {
  337. return $this->fieldNamesForColumns[$tableName][$columnName];
  338. }
  339. $columnName = strtolower($columnName);
  340. // Replace _id if it is a foreignkey column
  341. if ($fk) {
  342. $columnName = str_replace('_id', '', $columnName);
  343. }
  344. return Inflector::camelize($columnName);
  345. }
  346. /**
  347. * Set the namespace for the generated entities.
  348. *
  349. * @param string $namespace
  350. * @return void
  351. */
  352. public function setNamespace($namespace)
  353. {
  354. $this->namespace = $namespace;
  355. }
  356. }