JoinedSubclassPersister.php 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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\Persisters;
  20. use Doctrine\ORM\ORMException,
  21. Doctrine\ORM\Mapping\ClassMetadata,
  22. Doctrine\DBAL\LockMode,
  23. Doctrine\DBAL\Types\Type,
  24. Doctrine\ORM\Query\ResultSetMapping;
  25. /**
  26. * The joined subclass persister maps a single entity instance to several tables in the
  27. * database as it is defined by the <tt>Class Table Inheritance</tt> strategy.
  28. *
  29. * @author Roman Borschel <roman@code-factory.org>
  30. * @author Benjamin Eberlei <kontakt@beberlei.de>
  31. * @since 2.0
  32. * @see http://martinfowler.com/eaaCatalog/classTableInheritance.html
  33. */
  34. class JoinedSubclassPersister extends AbstractEntityInheritancePersister
  35. {
  36. /**
  37. * Map that maps column names to the table names that own them.
  38. * This is mainly a temporary cache, used during a single request.
  39. *
  40. * @var array
  41. */
  42. private $_owningTableMap = array();
  43. /**
  44. * Map of table to quoted table names.
  45. *
  46. * @var array
  47. */
  48. private $_quotedTableMap = array();
  49. /**
  50. * {@inheritdoc}
  51. */
  52. protected function _getDiscriminatorColumnTableName()
  53. {
  54. if ($this->_class->name == $this->_class->rootEntityName) {
  55. return $this->_class->table['name'];
  56. } else {
  57. return $this->_em->getClassMetadata($this->_class->rootEntityName)->table['name'];
  58. }
  59. }
  60. /**
  61. * This function finds the ClassMetadata instance in an inheritance hierarchy
  62. * that is responsible for enabling versioning.
  63. *
  64. * @return \Doctrine\ORM\Mapping\ClassMetadata
  65. */
  66. private function _getVersionedClassMetadata()
  67. {
  68. if (isset($this->_class->fieldMappings[$this->_class->versionField]['inherited'])) {
  69. $definingClassName = $this->_class->fieldMappings[$this->_class->versionField]['inherited'];
  70. return $this->_em->getClassMetadata($definingClassName);
  71. }
  72. return $this->_class;
  73. }
  74. /**
  75. * Gets the name of the table that owns the column the given field is mapped to.
  76. *
  77. * @param string $fieldName
  78. * @return string
  79. * @override
  80. */
  81. public function getOwningTable($fieldName)
  82. {
  83. if (!isset($this->_owningTableMap[$fieldName])) {
  84. if (isset($this->_class->associationMappings[$fieldName]['inherited'])) {
  85. $cm = $this->_em->getClassMetadata($this->_class->associationMappings[$fieldName]['inherited']);
  86. } else if (isset($this->_class->fieldMappings[$fieldName]['inherited'])) {
  87. $cm = $this->_em->getClassMetadata($this->_class->fieldMappings[$fieldName]['inherited']);
  88. } else {
  89. $cm = $this->_class;
  90. }
  91. $this->_owningTableMap[$fieldName] = $cm->table['name'];
  92. $this->_quotedTableMap[$cm->table['name']] = $cm->getQuotedTableName($this->_platform);
  93. }
  94. return $this->_owningTableMap[$fieldName];
  95. }
  96. /**
  97. * {@inheritdoc}
  98. */
  99. public function executeInserts()
  100. {
  101. if ( ! $this->_queuedInserts) {
  102. return;
  103. }
  104. $postInsertIds = array();
  105. $idGen = $this->_class->idGenerator;
  106. $isPostInsertId = $idGen->isPostInsertGenerator();
  107. // Prepare statement for the root table
  108. $rootClass = $this->_class->name == $this->_class->rootEntityName ?
  109. $this->_class : $this->_em->getClassMetadata($this->_class->rootEntityName);
  110. $rootPersister = $this->_em->getUnitOfWork()->getEntityPersister($rootClass->name);
  111. $rootTableName = $rootClass->table['name'];
  112. $rootTableStmt = $this->_conn->prepare($rootPersister->_getInsertSQL());
  113. // Prepare statements for sub tables.
  114. $subTableStmts = array();
  115. if ($rootClass !== $this->_class) {
  116. $subTableStmts[$this->_class->table['name']] = $this->_conn->prepare($this->_getInsertSQL());
  117. }
  118. foreach ($this->_class->parentClasses as $parentClassName) {
  119. $parentClass = $this->_em->getClassMetadata($parentClassName);
  120. $parentTableName = $parentClass->table['name'];
  121. if ($parentClass !== $rootClass) {
  122. $parentPersister = $this->_em->getUnitOfWork()->getEntityPersister($parentClassName);
  123. $subTableStmts[$parentTableName] = $this->_conn->prepare($parentPersister->_getInsertSQL());
  124. }
  125. }
  126. // Execute all inserts. For each entity:
  127. // 1) Insert on root table
  128. // 2) Insert on sub tables
  129. foreach ($this->_queuedInserts as $entity) {
  130. $insertData = $this->_prepareInsertData($entity);
  131. // Execute insert on root table
  132. $paramIndex = 1;
  133. foreach ($insertData[$rootTableName] as $columnName => $value) {
  134. $rootTableStmt->bindValue($paramIndex++, $value, $this->_columnTypes[$columnName]);
  135. }
  136. $rootTableStmt->execute();
  137. if ($isPostInsertId) {
  138. $id = $idGen->generate($this->_em, $entity);
  139. $postInsertIds[$id] = $entity;
  140. } else {
  141. $id = $this->_em->getUnitOfWork()->getEntityIdentifier($entity);
  142. }
  143. // Execute inserts on subtables.
  144. // The order doesn't matter because all child tables link to the root table via FK.
  145. foreach ($subTableStmts as $tableName => $stmt) {
  146. $data = isset($insertData[$tableName]) ? $insertData[$tableName] : array();
  147. $paramIndex = 1;
  148. foreach ((array) $id as $idName => $idVal) {
  149. $type = isset($this->_columnTypes[$idName]) ? $this->_columnTypes[$idName] : Type::STRING;
  150. $stmt->bindValue($paramIndex++, $idVal, $type);
  151. }
  152. foreach ($data as $columnName => $value) {
  153. $stmt->bindValue($paramIndex++, $value, $this->_columnTypes[$columnName]);
  154. }
  155. $stmt->execute();
  156. }
  157. }
  158. $rootTableStmt->closeCursor();
  159. foreach ($subTableStmts as $stmt) {
  160. $stmt->closeCursor();
  161. }
  162. if ($this->_class->isVersioned) {
  163. $this->assignDefaultVersionValue($entity, $id);
  164. }
  165. $this->_queuedInserts = array();
  166. return $postInsertIds;
  167. }
  168. /**
  169. * {@inheritdoc}
  170. */
  171. public function update($entity)
  172. {
  173. $updateData = $this->_prepareUpdateData($entity);
  174. if (($isVersioned = $this->_class->isVersioned) != false) {
  175. $versionedClass = $this->_getVersionedClassMetadata();
  176. $versionedTable = $versionedClass->table['name'];
  177. }
  178. if ($updateData) {
  179. foreach ($updateData as $tableName => $data) {
  180. $this->_updateTable($entity, $this->_quotedTableMap[$tableName], $data, $isVersioned && $versionedTable == $tableName);
  181. }
  182. // Make sure the table with the version column is updated even if no columns on that
  183. // table were affected.
  184. if ($isVersioned && ! isset($updateData[$versionedTable])) {
  185. $this->_updateTable($entity, $versionedClass->getQuotedTableName($this->_platform), array(), true);
  186. $id = $this->_em->getUnitOfWork()->getEntityIdentifier($entity);
  187. $this->assignDefaultVersionValue($entity, $id);
  188. }
  189. }
  190. }
  191. /**
  192. * {@inheritdoc}
  193. */
  194. public function delete($entity)
  195. {
  196. $identifier = $this->_em->getUnitOfWork()->getEntityIdentifier($entity);
  197. $this->deleteJoinTableRecords($identifier);
  198. $id = array_combine($this->_class->getIdentifierColumnNames(), $identifier);
  199. // If the database platform supports FKs, just
  200. // delete the row from the root table. Cascades do the rest.
  201. if ($this->_platform->supportsForeignKeyConstraints()) {
  202. $this->_conn->delete($this->_em->getClassMetadata($this->_class->rootEntityName)
  203. ->getQuotedTableName($this->_platform), $id);
  204. } else {
  205. // Delete from all tables individually, starting from this class' table up to the root table.
  206. $this->_conn->delete($this->_class->getQuotedTableName($this->_platform), $id);
  207. foreach ($this->_class->parentClasses as $parentClass) {
  208. $this->_conn->delete($this->_em->getClassMetadata($parentClass)->getQuotedTableName($this->_platform), $id);
  209. }
  210. }
  211. }
  212. /**
  213. * {@inheritdoc}
  214. */
  215. protected function _getSelectEntitiesSQL(array $criteria, $assoc = null, $lockMode = 0, $limit = null, $offset = null, array $orderBy = null)
  216. {
  217. $idColumns = $this->_class->getIdentifierColumnNames();
  218. $baseTableAlias = $this->_getSQLTableAlias($this->_class->name);
  219. // Create the column list fragment only once
  220. if ($this->_selectColumnListSql === null) {
  221. $this->_rsm = new ResultSetMapping();
  222. $this->_rsm->addEntityResult($this->_class->name, 'r');
  223. // Add regular columns
  224. $columnList = '';
  225. foreach ($this->_class->fieldMappings as $fieldName => $mapping) {
  226. if ($columnList != '') $columnList .= ', ';
  227. $columnList .= $this->_getSelectColumnSQL($fieldName,
  228. isset($mapping['inherited']) ?
  229. $this->_em->getClassMetadata($mapping['inherited']) :
  230. $this->_class);
  231. }
  232. // Add foreign key columns
  233. foreach ($this->_class->associationMappings as $assoc2) {
  234. if ($assoc2['isOwningSide'] && $assoc2['type'] & ClassMetadata::TO_ONE) {
  235. $tableAlias = isset($assoc2['inherited']) ?
  236. $this->_getSQLTableAlias($assoc2['inherited'])
  237. : $baseTableAlias;
  238. foreach ($assoc2['targetToSourceKeyColumns'] as $srcColumn) {
  239. if ($columnList != '') $columnList .= ', ';
  240. $columnList .= $this->getSelectJoinColumnSQL($tableAlias, $srcColumn,
  241. isset($assoc2['inherited']) ? $assoc2['inherited'] : $this->_class->name
  242. );
  243. }
  244. }
  245. }
  246. // Add discriminator column (DO NOT ALIAS, see AbstractEntityInheritancePersister#_processSQLResult).
  247. $discrColumn = $this->_class->discriminatorColumn['name'];
  248. if ($this->_class->rootEntityName == $this->_class->name) {
  249. $columnList .= ", $baseTableAlias.$discrColumn";
  250. } else {
  251. $columnList .= ', ' . $this->_getSQLTableAlias($this->_class->rootEntityName)
  252. . ".$discrColumn";
  253. }
  254. $resultColumnName = $this->_platform->getSQLResultCasing($discrColumn);
  255. $this->_rsm->setDiscriminatorColumn('r', $resultColumnName);
  256. $this->_rsm->addMetaResult('r', $resultColumnName, $discrColumn);
  257. }
  258. // INNER JOIN parent tables
  259. $joinSql = '';
  260. foreach ($this->_class->parentClasses as $parentClassName) {
  261. $parentClass = $this->_em->getClassMetadata($parentClassName);
  262. $tableAlias = $this->_getSQLTableAlias($parentClassName);
  263. $joinSql .= ' INNER JOIN ' . $parentClass->getQuotedTableName($this->_platform) . ' ' . $tableAlias . ' ON ';
  264. $first = true;
  265. foreach ($idColumns as $idColumn) {
  266. if ($first) $first = false; else $joinSql .= ' AND ';
  267. $joinSql .= $baseTableAlias . '.' . $idColumn . ' = ' . $tableAlias . '.' . $idColumn;
  268. }
  269. }
  270. // OUTER JOIN sub tables
  271. foreach ($this->_class->subClasses as $subClassName) {
  272. $subClass = $this->_em->getClassMetadata($subClassName);
  273. $tableAlias = $this->_getSQLTableAlias($subClassName);
  274. if ($this->_selectColumnListSql === null) {
  275. // Add subclass columns
  276. foreach ($subClass->fieldMappings as $fieldName => $mapping) {
  277. if (isset($mapping['inherited'])) {
  278. continue;
  279. }
  280. $columnList .= ', ' . $this->_getSelectColumnSQL($fieldName, $subClass);
  281. }
  282. // Add join columns (foreign keys)
  283. foreach ($subClass->associationMappings as $assoc2) {
  284. if ($assoc2['isOwningSide'] && $assoc2['type'] & ClassMetadata::TO_ONE
  285. && ! isset($assoc2['inherited'])) {
  286. foreach ($assoc2['targetToSourceKeyColumns'] as $srcColumn) {
  287. if ($columnList != '') $columnList .= ', ';
  288. $columnList .= $this->getSelectJoinColumnSQL($tableAlias, $srcColumn,
  289. isset($assoc2['inherited']) ? $assoc2['inherited'] : $subClass->name
  290. );
  291. }
  292. }
  293. }
  294. }
  295. // Add LEFT JOIN
  296. $joinSql .= ' LEFT JOIN ' . $subClass->getQuotedTableName($this->_platform) . ' ' . $tableAlias . ' ON ';
  297. $first = true;
  298. foreach ($idColumns as $idColumn) {
  299. if ($first) $first = false; else $joinSql .= ' AND ';
  300. $joinSql .= $baseTableAlias . '.' . $idColumn . ' = ' . $tableAlias . '.' . $idColumn;
  301. }
  302. }
  303. $joinSql .= $assoc != null && $assoc['type'] == ClassMetadata::MANY_TO_MANY ?
  304. $this->_getSelectManyToManyJoinSQL($assoc) : '';
  305. $conditionSql = $this->_getSelectConditionSQL($criteria, $assoc);
  306. $orderBy = ($assoc !== null && isset($assoc['orderBy'])) ? $assoc['orderBy'] : $orderBy;
  307. $orderBySql = $orderBy ? $this->_getOrderBySQL($orderBy, $baseTableAlias) : '';
  308. if ($this->_selectColumnListSql === null) {
  309. $this->_selectColumnListSql = $columnList;
  310. }
  311. $lockSql = '';
  312. if ($lockMode == LockMode::PESSIMISTIC_READ) {
  313. $lockSql = ' ' . $this->_platform->getReadLockSql();
  314. } else if ($lockMode == LockMode::PESSIMISTIC_WRITE) {
  315. $lockSql = ' ' . $this->_platform->getWriteLockSql();
  316. }
  317. return $this->_platform->modifyLimitQuery('SELECT ' . $this->_selectColumnListSql
  318. . ' FROM ' . $this->_class->getQuotedTableName($this->_platform) . ' ' . $baseTableAlias
  319. . $joinSql
  320. . ($conditionSql != '' ? ' WHERE ' . $conditionSql : '') . $orderBySql, $limit, $offset)
  321. . $lockSql;
  322. }
  323. /**
  324. * Get the FROM and optionally JOIN conditions to lock the entity managed by this persister.
  325. *
  326. * @return string
  327. */
  328. public function getLockTablesSql()
  329. {
  330. $idColumns = $this->_class->getIdentifierColumnNames();
  331. $baseTableAlias = $this->_getSQLTableAlias($this->_class->name);
  332. // INNER JOIN parent tables
  333. $joinSql = '';
  334. foreach ($this->_class->parentClasses as $parentClassName) {
  335. $parentClass = $this->_em->getClassMetadata($parentClassName);
  336. $tableAlias = $this->_getSQLTableAlias($parentClassName);
  337. $joinSql .= ' INNER JOIN ' . $parentClass->getQuotedTableName($this->_platform) . ' ' . $tableAlias . ' ON ';
  338. $first = true;
  339. foreach ($idColumns as $idColumn) {
  340. if ($first) $first = false; else $joinSql .= ' AND ';
  341. $joinSql .= $baseTableAlias . '.' . $idColumn . ' = ' . $tableAlias . '.' . $idColumn;
  342. }
  343. }
  344. return 'FROM ' . $this->_class->getQuotedTableName($this->_platform) . ' ' . $baseTableAlias . $joinSql;
  345. }
  346. /* Ensure this method is never called. This persister overrides _getSelectEntitiesSQL directly. */
  347. protected function _getSelectColumnListSQL()
  348. {
  349. throw new \BadMethodCallException("Illegal invocation of ".__METHOD__.".");
  350. }
  351. /** {@inheritdoc} */
  352. protected function _getInsertColumnList()
  353. {
  354. // Identifier columns must always come first in the column list of subclasses.
  355. $columns = $this->_class->parentClasses ? $this->_class->getIdentifierColumnNames() : array();
  356. foreach ($this->_class->reflFields as $name => $field) {
  357. if (isset($this->_class->fieldMappings[$name]['inherited']) && ! isset($this->_class->fieldMappings[$name]['id'])
  358. || isset($this->_class->associationMappings[$name]['inherited'])
  359. || ($this->_class->isVersioned && $this->_class->versionField == $name)) {
  360. continue;
  361. }
  362. if (isset($this->_class->associationMappings[$name])) {
  363. $assoc = $this->_class->associationMappings[$name];
  364. if ($assoc['type'] & ClassMetadata::TO_ONE && $assoc['isOwningSide']) {
  365. foreach ($assoc['targetToSourceKeyColumns'] as $sourceCol) {
  366. $columns[] = $sourceCol;
  367. }
  368. }
  369. } else if ($this->_class->name != $this->_class->rootEntityName ||
  370. ! $this->_class->isIdGeneratorIdentity() || $this->_class->identifier[0] != $name) {
  371. $columns[] = $this->_class->getQuotedColumnName($name, $this->_platform);
  372. }
  373. }
  374. // Add discriminator column if it is the topmost class.
  375. if ($this->_class->name == $this->_class->rootEntityName) {
  376. $columns[] = $this->_class->discriminatorColumn['name'];
  377. }
  378. return $columns;
  379. }
  380. /**
  381. * {@inheritdoc}
  382. */
  383. protected function assignDefaultVersionValue($entity, $id)
  384. {
  385. $value = $this->fetchVersionValue($this->_getVersionedClassMetadata(), $id);
  386. $this->_class->setFieldValue($entity, $this->_class->versionField, $value);
  387. }
  388. }