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.
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>.
20 namespace Doctrine\ORM\Persisters;
22 use Doctrine\ORM\ORMException;
23 use Doctrine\ORM\Mapping\ClassMetadata;
24 use Doctrine\ORM\Query\ResultSetMapping;
26 use Doctrine\DBAL\LockMode;
27 use Doctrine\DBAL\Types\Type;
29 use Doctrine\Common\Collections\Criteria;
32 * The joined subclass persister maps a single entity instance to several tables in the
33 * database as it is defined by the <tt>Class Table Inheritance</tt> strategy.
35 * @author Roman Borschel <roman@code-factory.org>
36 * @author Benjamin Eberlei <kontakt@beberlei.de>
37 * @author Alexander <iam.asm89@gmail.com>
39 * @see http://martinfowler.com/eaaCatalog/classTableInheritance.html
41 class JoinedSubclassPersister extends AbstractEntityInheritancePersister
44 * Map that maps column names to the table names that own them.
45 * This is mainly a temporary cache, used during a single request.
49 private $_owningTableMap = array();
52 * Map of table to quoted table names.
56 private $_quotedTableMap = array();
61 protected function _getDiscriminatorColumnTableName()
63 $class = ($this->_class->name !== $this->_class->rootEntityName)
64 ? $this->_em->getClassMetadata($this->_class->rootEntityName)
67 return $class->getTableName();
71 * This function finds the ClassMetadata instance in an inheritance hierarchy
72 * that is responsible for enabling versioning.
74 * @return \Doctrine\ORM\Mapping\ClassMetadata
76 private function _getVersionedClassMetadata()
78 if (isset($this->_class->fieldMappings[$this->_class->versionField]['inherited'])) {
79 $definingClassName = $this->_class->fieldMappings[$this->_class->versionField]['inherited'];
81 return $this->_em->getClassMetadata($definingClassName);
88 * Gets the name of the table that owns the column the given field is mapped to.
90 * @param string $fieldName
94 public function getOwningTable($fieldName)
96 if (isset($this->_owningTableMap[$fieldName])) {
97 return $this->_owningTableMap[$fieldName];
100 if (isset($this->_class->associationMappings[$fieldName]['inherited'])) {
101 $cm = $this->_em->getClassMetadata($this->_class->associationMappings[$fieldName]['inherited']);
102 } else if (isset($this->_class->fieldMappings[$fieldName]['inherited'])) {
103 $cm = $this->_em->getClassMetadata($this->_class->fieldMappings[$fieldName]['inherited']);
108 $tableName = $cm->getTableName();
110 $this->_owningTableMap[$fieldName] = $tableName;
111 $this->_quotedTableMap[$tableName] = $this->quoteStrategy->getTableName($cm, $this->_platform);
119 public function executeInserts()
121 if ( ! $this->_queuedInserts) {
125 $postInsertIds = array();
126 $idGen = $this->_class->idGenerator;
127 $isPostInsertId = $idGen->isPostInsertGenerator();
129 // Prepare statement for the root table
130 $rootClass = ($this->_class->name !== $this->_class->rootEntityName) ? $this->_em->getClassMetadata($this->_class->rootEntityName) : $this->_class;
131 $rootPersister = $this->_em->getUnitOfWork()->getEntityPersister($rootClass->name);
132 $rootTableName = $rootClass->getTableName();
133 $rootTableStmt = $this->_conn->prepare($rootPersister->_getInsertSQL());
135 // Prepare statements for sub tables.
136 $subTableStmts = array();
138 if ($rootClass !== $this->_class) {
139 $subTableStmts[$this->_class->getTableName()] = $this->_conn->prepare($this->_getInsertSQL());
142 foreach ($this->_class->parentClasses as $parentClassName) {
143 $parentClass = $this->_em->getClassMetadata($parentClassName);
144 $parentTableName = $parentClass->getTableName();
146 if ($parentClass !== $rootClass) {
147 $parentPersister = $this->_em->getUnitOfWork()->getEntityPersister($parentClassName);
148 $subTableStmts[$parentTableName] = $this->_conn->prepare($parentPersister->_getInsertSQL());
152 // Execute all inserts. For each entity:
153 // 1) Insert on root table
154 // 2) Insert on sub tables
155 foreach ($this->_queuedInserts as $entity) {
156 $insertData = $this->_prepareInsertData($entity);
158 // Execute insert on root table
161 foreach ($insertData[$rootTableName] as $columnName => $value) {
162 $rootTableStmt->bindValue($paramIndex++, $value, $this->_columnTypes[$columnName]);
165 $rootTableStmt->execute();
167 if ($isPostInsertId) {
168 $id = $idGen->generate($this->_em, $entity);
169 $postInsertIds[$id] = $entity;
171 $id = $this->_em->getUnitOfWork()->getEntityIdentifier($entity);
174 // Execute inserts on subtables.
175 // The order doesn't matter because all child tables link to the root table via FK.
176 foreach ($subTableStmts as $tableName => $stmt) {
177 $data = isset($insertData[$tableName]) ? $insertData[$tableName] : array();
180 foreach ((array) $id as $idName => $idVal) {
181 $type = isset($this->_columnTypes[$idName]) ? $this->_columnTypes[$idName] : Type::STRING;
183 $stmt->bindValue($paramIndex++, $idVal, $type);
186 foreach ($data as $columnName => $value) {
187 $stmt->bindValue($paramIndex++, $value, $this->_columnTypes[$columnName]);
194 $rootTableStmt->closeCursor();
196 foreach ($subTableStmts as $stmt) {
197 $stmt->closeCursor();
200 if ($this->_class->isVersioned) {
201 $this->assignDefaultVersionValue($entity, $id);
204 $this->_queuedInserts = array();
206 return $postInsertIds;
212 public function update($entity)
214 $updateData = $this->_prepareUpdateData($entity);
216 if (($isVersioned = $this->_class->isVersioned) != false) {
217 $versionedClass = $this->_getVersionedClassMetadata();
218 $versionedTable = $versionedClass->getTableName();
222 foreach ($updateData as $tableName => $data) {
224 $entity, $this->_quotedTableMap[$tableName], $data, $isVersioned && $versionedTable == $tableName
228 // Make sure the table with the version column is updated even if no columns on that
229 // table were affected.
230 if ($isVersioned && ! isset($updateData[$versionedTable])) {
231 $this->_updateTable($entity, $this->quoteStrategy->getTableName($versionedClass, $this->_platform), array(), true);
233 $id = $this->_em->getUnitOfWork()->getEntityIdentifier($entity);
234 $this->assignDefaultVersionValue($entity, $id);
242 public function delete($entity)
244 $identifier = $this->_em->getUnitOfWork()->getEntityIdentifier($entity);
245 $this->deleteJoinTableRecords($identifier);
247 $id = array_combine($this->_class->getIdentifierColumnNames(), $identifier);
249 // If the database platform supports FKs, just
250 // delete the row from the root table. Cascades do the rest.
251 if ($this->_platform->supportsForeignKeyConstraints()) {
252 $this->_conn->delete(
253 $this->quoteStrategy->getTableName($this->_em->getClassMetadata($this->_class->rootEntityName), $this->_platform), $id
256 // Delete from all tables individually, starting from this class' table up to the root table.
257 $this->_conn->delete($this->quoteStrategy->getTableName($this->_class, $this->_platform), $id);
259 foreach ($this->_class->parentClasses as $parentClass) {
260 $this->_conn->delete(
261 $this->quoteStrategy->getTableName($this->_em->getClassMetadata($parentClass), $this->_platform), $id
270 protected function _getSelectEntitiesSQL($criteria, $assoc = null, $lockMode = 0, $limit = null, $offset = null, array $orderBy = null)
272 $idColumns = $this->_class->getIdentifierColumnNames();
273 $baseTableAlias = $this->_getSQLTableAlias($this->_class->name);
275 // Create the column list fragment only once
276 if ($this->_selectColumnListSql === null) {
278 $this->_rsm = new ResultSetMapping();
279 $this->_rsm->addEntityResult($this->_class->name, 'r');
281 // Add regular columns
284 foreach ($this->_class->fieldMappings as $fieldName => $mapping) {
285 if ($columnList != '') $columnList .= ', ';
287 $columnList .= $this->_getSelectColumnSQL(
289 isset($mapping['inherited']) ? $this->_em->getClassMetadata($mapping['inherited']) : $this->_class
293 // Add foreign key columns
294 foreach ($this->_class->associationMappings as $assoc2) {
295 if ($assoc2['isOwningSide'] && $assoc2['type'] & ClassMetadata::TO_ONE) {
296 $tableAlias = isset($assoc2['inherited']) ? $this->_getSQLTableAlias($assoc2['inherited']) : $baseTableAlias;
298 foreach ($assoc2['targetToSourceKeyColumns'] as $srcColumn) {
299 if ($columnList != '') $columnList .= ', ';
301 $columnList .= $this->getSelectJoinColumnSQL(
304 isset($assoc2['inherited']) ? $assoc2['inherited'] : $this->_class->name
310 // Add discriminator column (DO NOT ALIAS, see AbstractEntityInheritancePersister#_processSQLResult).
311 $discrColumn = $this->_class->discriminatorColumn['name'];
312 $tableAlias = ($this->_class->rootEntityName == $this->_class->name) ? $baseTableAlias : $this->_getSQLTableAlias($this->_class->rootEntityName);
313 $columnList .= ', ' . $tableAlias . '.' . $discrColumn;
315 $resultColumnName = $this->_platform->getSQLResultCasing($discrColumn);
317 $this->_rsm->setDiscriminatorColumn('r', $resultColumnName);
318 $this->_rsm->addMetaResult('r', $resultColumnName, $discrColumn);
321 // INNER JOIN parent tables
324 foreach ($this->_class->parentClasses as $parentClassName) {
325 $parentClass = $this->_em->getClassMetadata($parentClassName);
326 $tableAlias = $this->_getSQLTableAlias($parentClassName);
327 $joinSql .= ' INNER JOIN ' . $this->quoteStrategy->getTableName($parentClass, $this->_platform) . ' ' . $tableAlias . ' ON ';
330 foreach ($idColumns as $idColumn) {
331 if ($first) $first = false; else $joinSql .= ' AND ';
333 $joinSql .= $baseTableAlias . '.' . $idColumn . ' = ' . $tableAlias . '.' . $idColumn;
337 // OUTER JOIN sub tables
338 foreach ($this->_class->subClasses as $subClassName) {
339 $subClass = $this->_em->getClassMetadata($subClassName);
340 $tableAlias = $this->_getSQLTableAlias($subClassName);
342 if ($this->_selectColumnListSql === null) {
343 // Add subclass columns
344 foreach ($subClass->fieldMappings as $fieldName => $mapping) {
345 if (isset($mapping['inherited'])) continue;
347 $columnList .= ', ' . $this->_getSelectColumnSQL($fieldName, $subClass);
350 // Add join columns (foreign keys)
351 foreach ($subClass->associationMappings as $assoc2) {
352 if ($assoc2['isOwningSide'] && $assoc2['type'] & ClassMetadata::TO_ONE && ! isset($assoc2['inherited'])) {
353 foreach ($assoc2['targetToSourceKeyColumns'] as $srcColumn) {
354 if ($columnList != '') $columnList .= ', ';
356 $columnList .= $this->getSelectJoinColumnSQL(
359 isset($assoc2['inherited']) ? $assoc2['inherited'] : $subClass->name
367 $joinSql .= ' LEFT JOIN ' . $this->quoteStrategy->getTableName($subClass, $this->_platform) . ' ' . $tableAlias . ' ON ';
370 foreach ($idColumns as $idColumn) {
371 if ($first) $first = false; else $joinSql .= ' AND ';
373 $joinSql .= $baseTableAlias . '.' . $idColumn . ' = ' . $tableAlias . '.' . $idColumn;
377 $joinSql .= ($assoc != null && $assoc['type'] == ClassMetadata::MANY_TO_MANY) ? $this->_getSelectManyToManyJoinSQL($assoc) : '';
379 $conditionSql = ($criteria instanceof Criteria)
380 ? $this->_getSelectConditionCriteriaSQL($criteria)
381 : $this->_getSelectConditionSQL($criteria, $assoc);
383 // If the current class in the root entity, add the filters
384 if ($filterSql = $this->generateFilterConditionSQL($this->_em->getClassMetadata($this->_class->rootEntityName), $this->_getSQLTableAlias($this->_class->rootEntityName))) {
386 $conditionSql .= ' AND ';
389 $conditionSql .= $filterSql;
392 $orderBy = ($assoc !== null && isset($assoc['orderBy'])) ? $assoc['orderBy'] : $orderBy;
393 $orderBySql = $orderBy ? $this->_getOrderBySQL($orderBy, $baseTableAlias) : '';
395 if ($this->_selectColumnListSql === null) {
396 $this->_selectColumnListSql = $columnList;
401 if ($lockMode == LockMode::PESSIMISTIC_READ) {
402 $lockSql = ' ' . $this->_platform->getReadLockSql();
403 } else if ($lockMode == LockMode::PESSIMISTIC_WRITE) {
404 $lockSql = ' ' . $this->_platform->getWriteLockSql();
407 return $this->_platform->modifyLimitQuery('SELECT ' . $this->_selectColumnListSql
408 . ' FROM ' . $this->quoteStrategy->getTableName($this->_class, $this->_platform) . ' ' . $baseTableAlias
410 . ($conditionSql != '' ? ' WHERE ' . $conditionSql : '') . $orderBySql, $limit, $offset)
415 * Get the FROM and optionally JOIN conditions to lock the entity managed by this persister.
419 public function getLockTablesSql()
421 $idColumns = $this->_class->getIdentifierColumnNames();
422 $baseTableAlias = $this->_getSQLTableAlias($this->_class->name);
424 // INNER JOIN parent tables
427 foreach ($this->_class->parentClasses as $parentClassName) {
428 $parentClass = $this->_em->getClassMetadata($parentClassName);
429 $tableAlias = $this->_getSQLTableAlias($parentClassName);
430 $joinSql .= ' INNER JOIN ' . $this->quoteStrategy->getTableName($parentClass, $this->_platform) . ' ' . $tableAlias . ' ON ';
433 foreach ($idColumns as $idColumn) {
434 if ($first) $first = false; else $joinSql .= ' AND ';
436 $joinSql .= $baseTableAlias . '.' . $idColumn . ' = ' . $tableAlias . '.' . $idColumn;
440 return 'FROM ' .$this->quoteStrategy->getTableName($this->_class, $this->_platform) . ' ' . $baseTableAlias . $joinSql;
443 /* Ensure this method is never called. This persister overrides _getSelectEntitiesSQL directly. */
444 protected function _getSelectColumnListSQL()
446 throw new \BadMethodCallException("Illegal invocation of ".__METHOD__.".");
450 protected function _getInsertColumnList()
452 // Identifier columns must always come first in the column list of subclasses.
453 $columns = $this->_class->parentClasses ? $this->_class->getIdentifierColumnNames() : array();
455 foreach ($this->_class->reflFields as $name => $field) {
456 if (isset($this->_class->fieldMappings[$name]['inherited']) && ! isset($this->_class->fieldMappings[$name]['id'])
457 || isset($this->_class->associationMappings[$name]['inherited'])
458 || ($this->_class->isVersioned && $this->_class->versionField == $name)) {
462 if (isset($this->_class->associationMappings[$name])) {
463 $assoc = $this->_class->associationMappings[$name];
464 if ($assoc['type'] & ClassMetadata::TO_ONE && $assoc['isOwningSide']) {
465 foreach ($assoc['targetToSourceKeyColumns'] as $sourceCol) {
466 $columns[] = $sourceCol;
469 } else if ($this->_class->name != $this->_class->rootEntityName ||
470 ! $this->_class->isIdGeneratorIdentity() || $this->_class->identifier[0] != $name) {
471 $columns[] = $this->quoteStrategy->getColumnName($name, $this->_class, $this->_platform);
475 // Add discriminator column if it is the topmost class.
476 if ($this->_class->name == $this->_class->rootEntityName) {
477 $columns[] = $this->_class->discriminatorColumn['name'];
486 protected function assignDefaultVersionValue($entity, $id)
488 $value = $this->fetchVersionValue($this->_getVersionedClassMetadata(), $id);
489 $this->_class->setFieldValue($entity, $this->_class->versionField, $value);