JoinedSubclassPersister.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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\Mapping\ClassMetadata;
  21. use Doctrine\ORM\Query\ResultSetMapping;
  22. use Doctrine\DBAL\LockMode;
  23. use Doctrine\DBAL\Types\Type;
  24. use Doctrine\Common\Collections\Criteria;
  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. *
  79. * @return string
  80. *
  81. * @override
  82. */
  83. public function getOwningTable($fieldName)
  84. {
  85. if (isset($this->owningTableMap[$fieldName])) {
  86. return $this->owningTableMap[$fieldName];
  87. }
  88. switch (true) {
  89. case isset($this->class->associationMappings[$fieldName]['inherited']):
  90. $cm = $this->em->getClassMetadata($this->class->associationMappings[$fieldName]['inherited']);
  91. break;
  92. case isset($this->class->fieldMappings[$fieldName]['inherited']):
  93. $cm = $this->em->getClassMetadata($this->class->fieldMappings[$fieldName]['inherited']);
  94. break;
  95. default:
  96. $cm = $this->class;
  97. break;
  98. }
  99. $tableName = $cm->getTableName();
  100. $quotedTableName = $this->quoteStrategy->getTableName($cm, $this->platform);
  101. $this->owningTableMap[$fieldName] = $tableName;
  102. $this->quotedTableMap[$tableName] = $quotedTableName;
  103. return $tableName;
  104. }
  105. /**
  106. * {@inheritdoc}
  107. */
  108. public function executeInserts()
  109. {
  110. if ( ! $this->queuedInserts) {
  111. return;
  112. }
  113. $postInsertIds = array();
  114. $idGenerator = $this->class->idGenerator;
  115. $isPostInsertId = $idGenerator->isPostInsertGenerator();
  116. $rootClass = ($this->class->name !== $this->class->rootEntityName)
  117. ? $this->em->getClassMetadata($this->class->rootEntityName)
  118. : $this->class;
  119. // Prepare statement for the root table
  120. $rootPersister = $this->em->getUnitOfWork()->getEntityPersister($rootClass->name);
  121. $rootTableName = $rootClass->getTableName();
  122. $rootTableStmt = $this->conn->prepare($rootPersister->getInsertSQL());
  123. // Prepare statements for sub tables.
  124. $subTableStmts = array();
  125. if ($rootClass !== $this->class) {
  126. $subTableStmts[$this->class->getTableName()] = $this->conn->prepare($this->getInsertSQL());
  127. }
  128. foreach ($this->class->parentClasses as $parentClassName) {
  129. $parentClass = $this->em->getClassMetadata($parentClassName);
  130. $parentTableName = $parentClass->getTableName();
  131. if ($parentClass !== $rootClass) {
  132. $parentPersister = $this->em->getUnitOfWork()->getEntityPersister($parentClassName);
  133. $subTableStmts[$parentTableName] = $this->conn->prepare($parentPersister->getInsertSQL());
  134. }
  135. }
  136. // Execute all inserts. For each entity:
  137. // 1) Insert on root table
  138. // 2) Insert on sub tables
  139. foreach ($this->queuedInserts as $entity) {
  140. $insertData = $this->prepareInsertData($entity);
  141. // Execute insert on root table
  142. $paramIndex = 1;
  143. foreach ($insertData[$rootTableName] as $columnName => $value) {
  144. $rootTableStmt->bindValue($paramIndex++, $value, $this->columnTypes[$columnName]);
  145. }
  146. $rootTableStmt->execute();
  147. if ($isPostInsertId) {
  148. $id = $idGenerator->generate($this->em, $entity);
  149. $postInsertIds[$id] = $entity;
  150. } else {
  151. $id = $this->em->getUnitOfWork()->getEntityIdentifier($entity);
  152. }
  153. // Execute inserts on subtables.
  154. // The order doesn't matter because all child tables link to the root table via FK.
  155. foreach ($subTableStmts as $tableName => $stmt) {
  156. /** @var \Doctrine\DBAL\Statement $stmt */
  157. $paramIndex = 1;
  158. $data = isset($insertData[$tableName])
  159. ? $insertData[$tableName]
  160. : array();
  161. foreach ((array) $id as $idName => $idVal) {
  162. $type = isset($this->columnTypes[$idName]) ? $this->columnTypes[$idName] : Type::STRING;
  163. $stmt->bindValue($paramIndex++, $idVal, $type);
  164. }
  165. foreach ($data as $columnName => $value) {
  166. if (!is_array($id) || !isset($id[$columnName])) {
  167. $stmt->bindValue($paramIndex++, $value, $this->columnTypes[$columnName]);
  168. }
  169. }
  170. $stmt->execute();
  171. }
  172. }
  173. $rootTableStmt->closeCursor();
  174. foreach ($subTableStmts as $stmt) {
  175. $stmt->closeCursor();
  176. }
  177. if ($this->class->isVersioned) {
  178. $this->assignDefaultVersionValue($entity, $id);
  179. }
  180. $this->queuedInserts = array();
  181. return $postInsertIds;
  182. }
  183. /**
  184. * {@inheritdoc}
  185. */
  186. public function update($entity)
  187. {
  188. $updateData = $this->prepareUpdateData($entity);
  189. if ( ! $updateData) {
  190. return;
  191. }
  192. if (($isVersioned = $this->class->isVersioned) === false) {
  193. return;
  194. }
  195. $versionedClass = $this->getVersionedClassMetadata();
  196. $versionedTable = $versionedClass->getTableName();
  197. foreach ($updateData as $tableName => $data) {
  198. $tableName = $this->quotedTableMap[$tableName];
  199. $versioned = $isVersioned && $versionedTable === $tableName;
  200. $this->updateTable($entity, $tableName, $data, $versioned);
  201. }
  202. // Make sure the table with the version column is updated even if no columns on that
  203. // table were affected.
  204. if ($isVersioned) {
  205. if ( ! isset($updateData[$versionedTable])) {
  206. $tableName = $this->quoteStrategy->getTableName($versionedClass, $this->platform);
  207. $this->updateTable($entity, $tableName, array(), true);
  208. }
  209. $identifiers = $this->em->getUnitOfWork()->getEntityIdentifier($entity);
  210. $this->assignDefaultVersionValue($entity, $identifiers);
  211. }
  212. }
  213. /**
  214. * {@inheritdoc}
  215. */
  216. public function delete($entity)
  217. {
  218. $identifier = $this->em->getUnitOfWork()->getEntityIdentifier($entity);
  219. $id = array_combine($this->class->getIdentifierColumnNames(), $identifier);
  220. $this->deleteJoinTableRecords($identifier);
  221. // If the database platform supports FKs, just
  222. // delete the row from the root table. Cascades do the rest.
  223. if ($this->platform->supportsForeignKeyConstraints()) {
  224. $rootClass = $this->em->getClassMetadata($this->class->rootEntityName);
  225. $rootTable = $this->quoteStrategy->getTableName($rootClass, $this->platform);
  226. $this->conn->delete($rootTable, $id);
  227. return;
  228. }
  229. // Delete from all tables individually, starting from this class' table up to the root table.
  230. $rootTable = $this->quoteStrategy->getTableName($this->class, $this->platform);
  231. $this->conn->delete($rootTable, $id);
  232. foreach ($this->class->parentClasses as $parentClass) {
  233. $parentMetadata = $this->em->getClassMetadata($parentClass);
  234. $parentTable = $this->quoteStrategy->getTableName($parentMetadata, $this->platform);
  235. $this->conn->delete($parentTable, $id);
  236. }
  237. }
  238. /**
  239. * {@inheritdoc}
  240. */
  241. protected function getSelectSQL($criteria, $assoc = null, $lockMode = 0, $limit = null, $offset = null, array $orderBy = null)
  242. {
  243. $joinSql = '';
  244. $identifierColumn = $this->class->getIdentifierColumnNames();
  245. $baseTableAlias = $this->getSQLTableAlias($this->class->name);
  246. // INNER JOIN parent tables
  247. foreach ($this->class->parentClasses as $parentClassName) {
  248. $conditions = array();
  249. $parentClass = $this->em->getClassMetadata($parentClassName);
  250. $tableAlias = $this->getSQLTableAlias($parentClassName);
  251. $joinSql .= ' INNER JOIN ' . $this->quoteStrategy->getTableName($parentClass, $this->platform) . ' ' . $tableAlias . ' ON ';
  252. foreach ($identifierColumn as $idColumn) {
  253. $conditions[] = $baseTableAlias . '.' . $idColumn . ' = ' . $tableAlias . '.' . $idColumn;
  254. }
  255. $joinSql .= implode(' AND ', $conditions);
  256. }
  257. // OUTER JOIN sub tables
  258. foreach ($this->class->subClasses as $subClassName) {
  259. $conditions = array();
  260. $subClass = $this->em->getClassMetadata($subClassName);
  261. $tableAlias = $this->getSQLTableAlias($subClassName);
  262. $joinSql .= ' LEFT JOIN ' . $this->quoteStrategy->getTableName($subClass, $this->platform) . ' ' . $tableAlias . ' ON ';
  263. foreach ($identifierColumn as $idColumn) {
  264. $conditions[] = $baseTableAlias . '.' . $idColumn . ' = ' . $tableAlias . '.' . $idColumn;
  265. }
  266. $joinSql .= implode(' AND ', $conditions);
  267. }
  268. if ($assoc != null && $assoc['type'] == ClassMetadata::MANY_TO_MANY) {
  269. $joinSql .= $this->getSelectManyToManyJoinSQL($assoc);
  270. }
  271. $conditionSql = ($criteria instanceof Criteria)
  272. ? $this->getSelectConditionCriteriaSQL($criteria)
  273. : $this->getSelectConditionSQL($criteria, $assoc);
  274. // If the current class in the root entity, add the filters
  275. if ($filterSql = $this->generateFilterConditionSQL($this->em->getClassMetadata($this->class->rootEntityName), $this->getSQLTableAlias($this->class->rootEntityName))) {
  276. $conditionSql .= $conditionSql
  277. ? ' AND ' . $filterSql
  278. : $filterSql;
  279. }
  280. $orderBySql = '';
  281. if ($assoc !== null && isset($assoc['orderBy'])) {
  282. $orderBy = $assoc['orderBy'];
  283. }
  284. if ($orderBy) {
  285. $orderBySql = $this->getOrderBySQL($orderBy, $baseTableAlias);
  286. }
  287. $lockSql = '';
  288. switch ($lockMode) {
  289. case LockMode::PESSIMISTIC_READ:
  290. $lockSql = ' ' . $this->platform->getReadLockSql();
  291. break;
  292. case LockMode::PESSIMISTIC_WRITE:
  293. $lockSql = ' ' . $this->platform->getWriteLockSql();
  294. break;
  295. }
  296. $tableName = $this->quoteStrategy->getTableName($this->class, $this->platform);
  297. $where = $conditionSql != '' ? ' WHERE ' . $conditionSql : '';
  298. $columnList = $this->getSelectColumnsSQL();
  299. $query = 'SELECT ' . $columnList
  300. . ' FROM '
  301. . $tableName . ' ' . $baseTableAlias
  302. . $joinSql
  303. . $where
  304. . $orderBySql;
  305. return $this->platform->modifyLimitQuery($query, $limit, $offset) . $lockSql;
  306. }
  307. /**
  308. * {@inheritdoc}
  309. */
  310. protected function getLockTablesSql($lockMode)
  311. {
  312. $joinSql = '';
  313. $identifierColumns = $this->class->getIdentifierColumnNames();
  314. $baseTableAlias = $this->getSQLTableAlias($this->class->name);
  315. // INNER JOIN parent tables
  316. foreach ($this->class->parentClasses as $parentClassName) {
  317. $conditions = array();
  318. $tableAlias = $this->getSQLTableAlias($parentClassName);
  319. $parentClass = $this->em->getClassMetadata($parentClassName);
  320. $joinSql .= ' INNER JOIN ' . $this->quoteStrategy->getTableName($parentClass, $this->platform) . ' ' . $tableAlias . ' ON ';
  321. foreach ($identifierColumns as $idColumn) {
  322. $conditions[] = $baseTableAlias . '.' . $idColumn . ' = ' . $tableAlias . '.' . $idColumn;
  323. }
  324. $joinSql .= implode(' AND ', $conditions);
  325. }
  326. return parent::getLockTablesSql($lockMode) . $joinSql;
  327. }
  328. /**
  329. * Ensure this method is never called. This persister overrides getSelectEntitiesSQL directly.
  330. *
  331. * @return string
  332. */
  333. protected function getSelectColumnsSQL()
  334. {
  335. // Create the column list fragment only once
  336. if ($this->selectColumnListSql !== null) {
  337. return $this->selectColumnListSql;
  338. }
  339. $columnList = array();
  340. $this->rsm = new ResultSetMapping();
  341. $discrColumn = $this->class->discriminatorColumn['name'];
  342. $baseTableAlias = $this->getSQLTableAlias($this->class->name);
  343. $resultColumnName = $this->platform->getSQLResultCasing($discrColumn);
  344. $this->rsm->addEntityResult($this->class->name, 'r');
  345. $this->rsm->setDiscriminatorColumn('r', $resultColumnName);
  346. $this->rsm->addMetaResult('r', $resultColumnName, $discrColumn);
  347. // Add regular columns
  348. foreach ($this->class->fieldMappings as $fieldName => $mapping) {
  349. $class = isset($mapping['inherited'])
  350. ? $this->em->getClassMetadata($mapping['inherited'])
  351. : $this->class;
  352. $columnList[] = $this->getSelectColumnSQL($fieldName, $class);
  353. }
  354. // Add foreign key columns
  355. foreach ($this->class->associationMappings as $mapping) {
  356. if ( ! $mapping['isOwningSide'] || ! ($mapping['type'] & ClassMetadata::TO_ONE)) {
  357. continue;
  358. }
  359. $tableAlias = isset($mapping['inherited'])
  360. ? $this->getSQLTableAlias($mapping['inherited'])
  361. : $baseTableAlias;
  362. foreach ($mapping['targetToSourceKeyColumns'] as $srcColumn) {
  363. $className = isset($mapping['inherited'])
  364. ? $mapping['inherited']
  365. : $this->class->name;
  366. $columnList[] = $this->getSelectJoinColumnSQL($tableAlias, $srcColumn, $className);
  367. }
  368. }
  369. // Add discriminator column (DO NOT ALIAS, see AbstractEntityInheritancePersister#processSQLResult).
  370. $tableAlias = ($this->class->rootEntityName == $this->class->name)
  371. ? $baseTableAlias
  372. : $this->getSQLTableAlias($this->class->rootEntityName);
  373. $columnList[] = $tableAlias . '.' . $discrColumn;
  374. // sub tables
  375. foreach ($this->class->subClasses as $subClassName) {
  376. $subClass = $this->em->getClassMetadata($subClassName);
  377. $tableAlias = $this->getSQLTableAlias($subClassName);
  378. // Add subclass columns
  379. foreach ($subClass->fieldMappings as $fieldName => $mapping) {
  380. if (isset($mapping['inherited'])) {
  381. continue;
  382. }
  383. $columnList[] = $this->getSelectColumnSQL($fieldName, $subClass);
  384. }
  385. // Add join columns (foreign keys)
  386. foreach ($subClass->associationMappings as $mapping) {
  387. if ( ! $mapping['isOwningSide']
  388. || ! ($mapping['type'] & ClassMetadata::TO_ONE)
  389. || isset($mapping['inherited'])) {
  390. continue;
  391. }
  392. foreach ($mapping['targetToSourceKeyColumns'] as $srcColumn) {
  393. $className = isset($mapping['inherited'])
  394. ? $mapping['inherited']
  395. : $subClass->name;
  396. $columnList[] = $this->getSelectJoinColumnSQL($tableAlias, $srcColumn, $className);
  397. }
  398. }
  399. }
  400. $this->selectColumnListSql = implode(', ', $columnList);
  401. return $this->selectColumnListSql;
  402. }
  403. /**
  404. * {@inheritdoc}
  405. */
  406. protected function getInsertColumnList()
  407. {
  408. // Identifier columns must always come first in the column list of subclasses.
  409. $columns = $this->class->parentClasses
  410. ? $this->class->getIdentifierColumnNames()
  411. : array();
  412. foreach ($this->class->reflFields as $name => $field) {
  413. if (isset($this->class->fieldMappings[$name]['inherited'])
  414. && ! isset($this->class->fieldMappings[$name]['id'])
  415. || isset($this->class->associationMappings[$name]['inherited'])
  416. || ($this->class->isVersioned && $this->class->versionField == $name)) {
  417. continue;
  418. }
  419. if (isset($this->class->associationMappings[$name])) {
  420. $assoc = $this->class->associationMappings[$name];
  421. if ($assoc['type'] & ClassMetadata::TO_ONE && $assoc['isOwningSide']) {
  422. foreach ($assoc['targetToSourceKeyColumns'] as $sourceCol) {
  423. $columns[] = $sourceCol;
  424. }
  425. }
  426. } else if ($this->class->name != $this->class->rootEntityName ||
  427. ! $this->class->isIdGeneratorIdentity() || $this->class->identifier[0] != $name) {
  428. $columns[] = $this->quoteStrategy->getColumnName($name, $this->class, $this->platform);
  429. $this->columnTypes[$name] = $this->class->fieldMappings[$name]['type'];
  430. }
  431. }
  432. // Add discriminator column if it is the topmost class.
  433. if ($this->class->name == $this->class->rootEntityName) {
  434. $columns[] = $this->class->discriminatorColumn['name'];
  435. }
  436. return $columns;
  437. }
  438. /**
  439. * {@inheritdoc}
  440. */
  441. protected function assignDefaultVersionValue($entity, $id)
  442. {
  443. $value = $this->fetchVersionValue($this->getVersionedClassMetadata(), $id);
  444. $this->class->setFieldValue($entity, $this->class->versionField, $value);
  445. }
  446. }