JoinedSubclassPersister.php 18KB

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