JoinedSubclassPersister.php 19 KB

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