JoinedSubclassPersister.php 19 KB

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