PageRenderTime 53ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/php/lib/doctrine2/Doctrine/ORM/Query/SqlWalker.php

https://bitbucket.org/ecelis/lml
PHP | 2205 lines | 1210 code | 409 blank | 586 comment | 147 complexity | ee8230a8d9da20bb7b903d995569a991 MD5 | raw file
Possible License(s): BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  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\Query;
  20. use Doctrine\DBAL\LockMode,
  21. Doctrine\DBAL\Types\Type,
  22. Doctrine\ORM\Mapping\ClassMetadata,
  23. Doctrine\ORM\Query,
  24. Doctrine\ORM\Query\QueryException,
  25. Doctrine\ORM\Mapping\ClassMetadataInfo;
  26. /**
  27. * The SqlWalker is a TreeWalker that walks over a DQL AST and constructs
  28. * the corresponding SQL.
  29. *
  30. * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
  31. * @author Roman Borschel <roman@code-factory.org>
  32. * @author Benjamin Eberlei <kontakt@beberlei.de>
  33. * @author Alexander <iam.asm89@gmail.com>
  34. * @since 2.0
  35. * @todo Rename: SQLWalker
  36. */
  37. class SqlWalker implements TreeWalker
  38. {
  39. /**
  40. * @var string
  41. */
  42. const HINT_DISTINCT = 'doctrine.distinct';
  43. /**
  44. * @var ResultSetMapping
  45. */
  46. private $rsm;
  47. /**
  48. * Counters for generating unique column aliases.
  49. *
  50. * @var integer
  51. */
  52. private $aliasCounter = 0;
  53. /**
  54. * Counters for generating unique table aliases.
  55. *
  56. * @var integer
  57. */
  58. private $tableAliasCounter = 0;
  59. /**
  60. * Counters for generating unique scalar result.
  61. *
  62. * @var integer
  63. */
  64. private $scalarResultCounter = 1;
  65. /**
  66. * Counters for generating unique parameter indexes.
  67. *
  68. * @var integer
  69. */
  70. private $sqlParamIndex = 0;
  71. /**
  72. * @var ParserResult
  73. */
  74. private $parserResult;
  75. /**
  76. * @var EntityManager
  77. */
  78. private $em;
  79. /**
  80. * @var \Doctrine\DBAL\Connection
  81. */
  82. private $conn;
  83. /**
  84. * @var AbstractQuery
  85. */
  86. private $query;
  87. /**
  88. * @var array
  89. */
  90. private $tableAliasMap = array();
  91. /**
  92. * Map from result variable names to their SQL column alias names.
  93. *
  94. * @var array
  95. */
  96. private $scalarResultAliasMap = array();
  97. /**
  98. * Map from DQL-Alias + Field-Name to SQL Column Alias
  99. *
  100. * @var array
  101. */
  102. private $scalarFields = array();
  103. /**
  104. * Map of all components/classes that appear in the DQL query.
  105. *
  106. * @var array
  107. */
  108. private $queryComponents;
  109. /**
  110. * A list of classes that appear in non-scalar SelectExpressions.
  111. *
  112. * @var array
  113. */
  114. private $selectedClasses = array();
  115. /**
  116. * The DQL alias of the root class of the currently traversed query.
  117. *
  118. * @var array
  119. */
  120. private $rootAliases = array();
  121. /**
  122. * Flag that indicates whether to generate SQL table aliases in the SQL.
  123. * These should only be generated for SELECT queries, not for UPDATE/DELETE.
  124. *
  125. * @var boolean
  126. */
  127. private $useSqlTableAliases = true;
  128. /**
  129. * The database platform abstraction.
  130. *
  131. * @var AbstractPlatform
  132. */
  133. private $platform;
  134. /**
  135. * The quote strategy.
  136. *
  137. * @var \Doctrine\ORM\Mapping\QuoteStrategy
  138. */
  139. private $quoteStrategy;
  140. /**
  141. * {@inheritDoc}
  142. */
  143. public function __construct($query, $parserResult, array $queryComponents)
  144. {
  145. $this->query = $query;
  146. $this->parserResult = $parserResult;
  147. $this->queryComponents = $queryComponents;
  148. $this->rsm = $parserResult->getResultSetMapping();
  149. $this->em = $query->getEntityManager();
  150. $this->conn = $this->em->getConnection();
  151. $this->platform = $this->conn->getDatabasePlatform();
  152. $this->quoteStrategy = $this->em->getConfiguration()->getQuoteStrategy();
  153. }
  154. /**
  155. * Gets the Query instance used by the walker.
  156. *
  157. * @return Query.
  158. */
  159. public function getQuery()
  160. {
  161. return $this->query;
  162. }
  163. /**
  164. * Gets the Connection used by the walker.
  165. *
  166. * @return Connection
  167. */
  168. public function getConnection()
  169. {
  170. return $this->conn;
  171. }
  172. /**
  173. * Gets the EntityManager used by the walker.
  174. *
  175. * @return EntityManager
  176. */
  177. public function getEntityManager()
  178. {
  179. return $this->em;
  180. }
  181. /**
  182. * Gets the information about a single query component.
  183. *
  184. * @param string $dqlAlias The DQL alias.
  185. * @return array
  186. */
  187. public function getQueryComponent($dqlAlias)
  188. {
  189. return $this->queryComponents[$dqlAlias];
  190. }
  191. /**
  192. * Gets an executor that can be used to execute the result of this walker.
  193. *
  194. * @return AbstractExecutor
  195. */
  196. public function getExecutor($AST)
  197. {
  198. switch (true) {
  199. case ($AST instanceof AST\DeleteStatement):
  200. $primaryClass = $this->em->getClassMetadata($AST->deleteClause->abstractSchemaName);
  201. return ($primaryClass->isInheritanceTypeJoined())
  202. ? new Exec\MultiTableDeleteExecutor($AST, $this)
  203. : new Exec\SingleTableDeleteUpdateExecutor($AST, $this);
  204. case ($AST instanceof AST\UpdateStatement):
  205. $primaryClass = $this->em->getClassMetadata($AST->updateClause->abstractSchemaName);
  206. return ($primaryClass->isInheritanceTypeJoined())
  207. ? new Exec\MultiTableUpdateExecutor($AST, $this)
  208. : new Exec\SingleTableDeleteUpdateExecutor($AST, $this);
  209. default:
  210. return new Exec\SingleSelectExecutor($AST, $this);
  211. }
  212. }
  213. /**
  214. * Generates a unique, short SQL table alias.
  215. *
  216. * @param string $tableName Table name
  217. * @param string $dqlAlias The DQL alias.
  218. * @return string Generated table alias.
  219. */
  220. public function getSQLTableAlias($tableName, $dqlAlias = '')
  221. {
  222. $tableName .= ($dqlAlias) ? '@[' . $dqlAlias . ']' : '';
  223. if ( ! isset($this->tableAliasMap[$tableName])) {
  224. $this->tableAliasMap[$tableName] = strtolower(substr($tableName, 0, 1)) . $this->tableAliasCounter++ . '_';
  225. }
  226. return $this->tableAliasMap[$tableName];
  227. }
  228. /**
  229. * Forces the SqlWalker to use a specific alias for a table name, rather than
  230. * generating an alias on its own.
  231. *
  232. * @param string $tableName
  233. * @param string $alias
  234. * @param string $dqlAlias
  235. * @return string
  236. */
  237. public function setSQLTableAlias($tableName, $alias, $dqlAlias = '')
  238. {
  239. $tableName .= ($dqlAlias) ? '@[' . $dqlAlias . ']' : '';
  240. $this->tableAliasMap[$tableName] = $alias;
  241. return $alias;
  242. }
  243. /**
  244. * Gets an SQL column alias for a column name.
  245. *
  246. * @param string $columnName
  247. * @return string
  248. */
  249. public function getSQLColumnAlias($columnName)
  250. {
  251. return $this->quoteStrategy->getColumnAlias($columnName, $this->aliasCounter++, $this->platform);
  252. }
  253. /**
  254. * Generates the SQL JOINs that are necessary for Class Table Inheritance
  255. * for the given class.
  256. *
  257. * @param ClassMetadata $class The class for which to generate the joins.
  258. * @param string $dqlAlias The DQL alias of the class.
  259. * @return string The SQL.
  260. */
  261. private function _generateClassTableInheritanceJoins($class, $dqlAlias)
  262. {
  263. $sql = '';
  264. $baseTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
  265. // INNER JOIN parent class tables
  266. foreach ($class->parentClasses as $parentClassName) {
  267. $parentClass = $this->em->getClassMetadata($parentClassName);
  268. $tableAlias = $this->getSQLTableAlias($parentClass->getTableName(), $dqlAlias);
  269. // If this is a joined association we must use left joins to preserve the correct result.
  270. $sql .= isset($this->queryComponents[$dqlAlias]['relation']) ? ' LEFT ' : ' INNER ';
  271. $sql .= 'JOIN ' . $this->quoteStrategy->getTableName($parentClass, $this->platform) . ' ' . $tableAlias . ' ON ';
  272. $sqlParts = array();
  273. foreach ($this->quoteStrategy->getIdentifierColumnNames($class, $this->platform) as $columnName) {
  274. $sqlParts[] = $baseTableAlias . '.' . $columnName . ' = ' . $tableAlias . '.' . $columnName;
  275. }
  276. // Add filters on the root class
  277. if ($filterSql = $this->generateFilterConditionSQL($parentClass, $tableAlias)) {
  278. $sqlParts[] = $filterSql;
  279. }
  280. $sql .= implode(' AND ', $sqlParts);
  281. }
  282. // Ignore subclassing inclusion if partial objects is disallowed
  283. if ($this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD)) {
  284. return $sql;
  285. }
  286. // LEFT JOIN child class tables
  287. foreach ($class->subClasses as $subClassName) {
  288. $subClass = $this->em->getClassMetadata($subClassName);
  289. $tableAlias = $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias);
  290. $sql .= ' LEFT JOIN ' . $this->quoteStrategy->getTableName($subClass, $this->platform) . ' ' . $tableAlias . ' ON ';
  291. $sqlParts = array();
  292. foreach ($this->quoteStrategy->getIdentifierColumnNames($subClass, $this->platform) as $columnName) {
  293. $sqlParts[] = $baseTableAlias . '.' . $columnName . ' = ' . $tableAlias . '.' . $columnName;
  294. }
  295. $sql .= implode(' AND ', $sqlParts);
  296. }
  297. return $sql;
  298. }
  299. private function _generateOrderedCollectionOrderByItems()
  300. {
  301. $sqlParts = array();
  302. foreach ($this->selectedClasses as $selectedClass) {
  303. $dqlAlias = $selectedClass['dqlAlias'];
  304. $qComp = $this->queryComponents[$dqlAlias];
  305. if ( ! isset($qComp['relation']['orderBy'])) continue;
  306. foreach ($qComp['relation']['orderBy'] as $fieldName => $orientation) {
  307. $columnName = $this->quoteStrategy->getColumnName($fieldName, $qComp['metadata'], $this->platform);
  308. $tableName = ($qComp['metadata']->isInheritanceTypeJoined())
  309. ? $this->em->getUnitOfWork()->getEntityPersister($qComp['metadata']->name)->getOwningTable($fieldName)
  310. : $qComp['metadata']->getTableName();
  311. $sqlParts[] = $this->getSQLTableAlias($tableName, $dqlAlias) . '.' . $columnName . ' ' . $orientation;
  312. }
  313. }
  314. return implode(', ', $sqlParts);
  315. }
  316. /**
  317. * Generates a discriminator column SQL condition for the class with the given DQL alias.
  318. *
  319. * @param array $dqlAliases List of root DQL aliases to inspect for discriminator restrictions.
  320. * @return string
  321. */
  322. private function _generateDiscriminatorColumnConditionSQL(array $dqlAliases)
  323. {
  324. $sqlParts = array();
  325. foreach ($dqlAliases as $dqlAlias) {
  326. $class = $this->queryComponents[$dqlAlias]['metadata'];
  327. if ( ! $class->isInheritanceTypeSingleTable()) continue;
  328. $conn = $this->em->getConnection();
  329. $values = array();
  330. if ($class->discriminatorValue !== null) { // discrimnators can be 0
  331. $values[] = $conn->quote($class->discriminatorValue);
  332. }
  333. foreach ($class->subClasses as $subclassName) {
  334. $values[] = $conn->quote($this->em->getClassMetadata($subclassName)->discriminatorValue);
  335. }
  336. $sqlParts[] = (($this->useSqlTableAliases) ? $this->getSQLTableAlias($class->getTableName(), $dqlAlias) . '.' : '')
  337. . $class->discriminatorColumn['name'] . ' IN (' . implode(', ', $values) . ')';
  338. }
  339. $sql = implode(' AND ', $sqlParts);
  340. return (count($sqlParts) > 1) ? '(' . $sql . ')' : $sql;
  341. }
  342. /**
  343. * Generates the filter SQL for a given entity and table alias.
  344. *
  345. * @param ClassMetadata $targetEntity Metadata of the target entity.
  346. * @param string $targetTableAlias The table alias of the joined/selected table.
  347. *
  348. * @return string The SQL query part to add to a query.
  349. */
  350. private function generateFilterConditionSQL(ClassMetadata $targetEntity, $targetTableAlias)
  351. {
  352. if (!$this->em->hasFilters()) {
  353. return '';
  354. }
  355. switch($targetEntity->inheritanceType) {
  356. case ClassMetadata::INHERITANCE_TYPE_NONE:
  357. break;
  358. case ClassMetadata::INHERITANCE_TYPE_JOINED:
  359. // The classes in the inheritance will be added to the query one by one,
  360. // but only the root node is getting filtered
  361. if ($targetEntity->name !== $targetEntity->rootEntityName) {
  362. return '';
  363. }
  364. break;
  365. case ClassMetadata::INHERITANCE_TYPE_SINGLE_TABLE:
  366. // With STI the table will only be queried once, make sure that the filters
  367. // are added to the root entity
  368. $targetEntity = $this->em->getClassMetadata($targetEntity->rootEntityName);
  369. break;
  370. default:
  371. //@todo: throw exception?
  372. return '';
  373. break;
  374. }
  375. $filterClauses = array();
  376. foreach ($this->em->getFilters()->getEnabledFilters() as $filter) {
  377. if ('' !== $filterExpr = $filter->addFilterConstraint($targetEntity, $targetTableAlias)) {
  378. $filterClauses[] = '(' . $filterExpr . ')';
  379. }
  380. }
  381. return implode(' AND ', $filterClauses);
  382. }
  383. /**
  384. * Walks down a SelectStatement AST node, thereby generating the appropriate SQL.
  385. *
  386. * @return string The SQL.
  387. */
  388. public function walkSelectStatement(AST\SelectStatement $AST)
  389. {
  390. $sql = $this->walkSelectClause($AST->selectClause);
  391. $sql .= $this->walkFromClause($AST->fromClause);
  392. $sql .= $this->walkWhereClause($AST->whereClause);
  393. $sql .= $AST->groupByClause ? $this->walkGroupByClause($AST->groupByClause) : '';
  394. $sql .= $AST->havingClause ? $this->walkHavingClause($AST->havingClause) : '';
  395. if (($orderByClause = $AST->orderByClause) !== null) {
  396. $sql .= $AST->orderByClause ? $this->walkOrderByClause($AST->orderByClause) : '';
  397. } else if (($orderBySql = $this->_generateOrderedCollectionOrderByItems()) !== '') {
  398. $sql .= ' ORDER BY ' . $orderBySql;
  399. }
  400. $sql = $this->platform->modifyLimitQuery(
  401. $sql, $this->query->getMaxResults(), $this->query->getFirstResult()
  402. );
  403. if (($lockMode = $this->query->getHint(Query::HINT_LOCK_MODE)) !== false) {
  404. switch ($lockMode) {
  405. case LockMode::PESSIMISTIC_READ:
  406. $sql .= ' ' . $this->platform->getReadLockSQL();
  407. break;
  408. case LockMode::PESSIMISTIC_WRITE:
  409. $sql .= ' ' . $this->platform->getWriteLockSQL();
  410. break;
  411. case LockMode::OPTIMISTIC:
  412. foreach ($this->selectedClasses as $selectedClass) {
  413. if ( ! $selectedClass['class']->isVersioned) {
  414. throw \Doctrine\ORM\OptimisticLockException::lockFailed($selectedClass['class']->name);
  415. }
  416. }
  417. break;
  418. case LockMode::NONE:
  419. break;
  420. default:
  421. throw \Doctrine\ORM\Query\QueryException::invalidLockMode();
  422. }
  423. }
  424. return $sql;
  425. }
  426. /**
  427. * Walks down an UpdateStatement AST node, thereby generating the appropriate SQL.
  428. *
  429. * @param UpdateStatement
  430. * @return string The SQL.
  431. */
  432. public function walkUpdateStatement(AST\UpdateStatement $AST)
  433. {
  434. $this->useSqlTableAliases = false;
  435. return $this->walkUpdateClause($AST->updateClause)
  436. . $this->walkWhereClause($AST->whereClause);
  437. }
  438. /**
  439. * Walks down a DeleteStatement AST node, thereby generating the appropriate SQL.
  440. *
  441. * @param DeleteStatement
  442. * @return string The SQL.
  443. */
  444. public function walkDeleteStatement(AST\DeleteStatement $AST)
  445. {
  446. $this->useSqlTableAliases = false;
  447. return $this->walkDeleteClause($AST->deleteClause)
  448. . $this->walkWhereClause($AST->whereClause);
  449. }
  450. /**
  451. * Walks down an IdentificationVariable AST node, thereby generating the appropriate SQL.
  452. * This one differs of ->walkIdentificationVariable() because it generates the entity identifiers.
  453. *
  454. * @param string $identVariable
  455. * @return string
  456. */
  457. public function walkEntityIdentificationVariable($identVariable)
  458. {
  459. $class = $this->queryComponents[$identVariable]['metadata'];
  460. $tableAlias = $this->getSQLTableAlias($class->getTableName(), $identVariable);
  461. $sqlParts = array();
  462. foreach ($this->quoteStrategy->getIdentifierColumnNames($class, $this->platform) as $columnName) {
  463. $sqlParts[] = $tableAlias . '.' . $columnName;
  464. }
  465. return implode(', ', $sqlParts);
  466. }
  467. /**
  468. * Walks down an IdentificationVariable (no AST node associated), thereby generating the SQL.
  469. *
  470. * @param string $identificationVariable
  471. * @param string $fieldName
  472. * @return string The SQL.
  473. */
  474. public function walkIdentificationVariable($identificationVariable, $fieldName = null)
  475. {
  476. $class = $this->queryComponents[$identificationVariable]['metadata'];
  477. if (
  478. $fieldName !== null && $class->isInheritanceTypeJoined() &&
  479. isset($class->fieldMappings[$fieldName]['inherited'])
  480. ) {
  481. $class = $this->em->getClassMetadata($class->fieldMappings[$fieldName]['inherited']);
  482. }
  483. return $this->getSQLTableAlias($class->getTableName(), $identificationVariable);
  484. }
  485. /**
  486. * Walks down a PathExpression AST node, thereby generating the appropriate SQL.
  487. *
  488. * @param mixed
  489. * @return string The SQL.
  490. */
  491. public function walkPathExpression($pathExpr)
  492. {
  493. $sql = '';
  494. switch ($pathExpr->type) {
  495. case AST\PathExpression::TYPE_STATE_FIELD:
  496. $fieldName = $pathExpr->field;
  497. $dqlAlias = $pathExpr->identificationVariable;
  498. $class = $this->queryComponents[$dqlAlias]['metadata'];
  499. if ($this->useSqlTableAliases) {
  500. $sql .= $this->walkIdentificationVariable($dqlAlias, $fieldName) . '.';
  501. }
  502. $sql .= $this->quoteStrategy->getColumnName($fieldName, $class, $this->platform);
  503. break;
  504. case AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION:
  505. // 1- the owning side:
  506. // Just use the foreign key, i.e. u.group_id
  507. $fieldName = $pathExpr->field;
  508. $dqlAlias = $pathExpr->identificationVariable;
  509. $class = $this->queryComponents[$dqlAlias]['metadata'];
  510. if (isset($class->associationMappings[$fieldName]['inherited'])) {
  511. $class = $this->em->getClassMetadata($class->associationMappings[$fieldName]['inherited']);
  512. }
  513. $assoc = $class->associationMappings[$fieldName];
  514. if ( ! $assoc['isOwningSide']) {
  515. throw QueryException::associationPathInverseSideNotSupported();
  516. }
  517. // COMPOSITE KEYS NOT (YET?) SUPPORTED
  518. if (count($assoc['sourceToTargetKeyColumns']) > 1) {
  519. throw QueryException::associationPathCompositeKeyNotSupported();
  520. }
  521. if ($this->useSqlTableAliases) {
  522. $sql .= $this->getSQLTableAlias($class->getTableName(), $dqlAlias) . '.';
  523. }
  524. $sql .= reset($assoc['targetToSourceKeyColumns']);
  525. break;
  526. default:
  527. throw QueryException::invalidPathExpression($pathExpr);
  528. }
  529. return $sql;
  530. }
  531. /**
  532. * Walks down a SelectClause AST node, thereby generating the appropriate SQL.
  533. *
  534. * @param $selectClause
  535. * @return string The SQL.
  536. */
  537. public function walkSelectClause($selectClause)
  538. {
  539. $sql = 'SELECT ' . (($selectClause->isDistinct) ? 'DISTINCT ' : '');
  540. $sqlSelectExpressions = array_filter(array_map(array($this, 'walkSelectExpression'), $selectClause->selectExpressions));
  541. if ($this->query->getHint(Query::HINT_INTERNAL_ITERATION) == true && $selectClause->isDistinct) {
  542. $this->query->setHint(self::HINT_DISTINCT, true);
  543. }
  544. $addMetaColumns = ! $this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD) &&
  545. $this->query->getHydrationMode() == Query::HYDRATE_OBJECT
  546. ||
  547. $this->query->getHydrationMode() != Query::HYDRATE_OBJECT &&
  548. $this->query->getHint(Query::HINT_INCLUDE_META_COLUMNS);
  549. foreach ($this->selectedClasses as $selectedClass) {
  550. $class = $selectedClass['class'];
  551. $dqlAlias = $selectedClass['dqlAlias'];
  552. $resultAlias = $selectedClass['resultAlias'];
  553. // Register as entity or joined entity result
  554. if ($this->queryComponents[$dqlAlias]['relation'] === null) {
  555. $this->rsm->addEntityResult($class->name, $dqlAlias, $resultAlias);
  556. } else {
  557. $this->rsm->addJoinedEntityResult(
  558. $class->name,
  559. $dqlAlias,
  560. $this->queryComponents[$dqlAlias]['parent'],
  561. $this->queryComponents[$dqlAlias]['relation']['fieldName']
  562. );
  563. }
  564. if ($class->isInheritanceTypeSingleTable() || $class->isInheritanceTypeJoined()) {
  565. // Add discriminator columns to SQL
  566. $rootClass = $this->em->getClassMetadata($class->rootEntityName);
  567. $tblAlias = $this->getSQLTableAlias($rootClass->getTableName(), $dqlAlias);
  568. $discrColumn = $rootClass->discriminatorColumn;
  569. $columnAlias = $this->getSQLColumnAlias($discrColumn['name']);
  570. $sqlSelectExpressions[] = $tblAlias . '.' . $discrColumn['name'] . ' AS ' . $columnAlias;
  571. $this->rsm->setDiscriminatorColumn($dqlAlias, $columnAlias);
  572. $this->rsm->addMetaResult($dqlAlias, $columnAlias, $discrColumn['fieldName']);
  573. }
  574. // Add foreign key columns to SQL, if necessary
  575. if ( ! $addMetaColumns && ! $class->containsForeignIdentifier) {
  576. continue;
  577. }
  578. // Add foreign key columns of class and also parent classes
  579. foreach ($class->associationMappings as $assoc) {
  580. if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) {
  581. continue;
  582. } else if ( !$addMetaColumns && !isset($assoc['id'])) {
  583. continue;
  584. }
  585. $owningClass = (isset($assoc['inherited'])) ? $this->em->getClassMetadata($assoc['inherited']) : $class;
  586. $sqlTableAlias = $this->getSQLTableAlias($owningClass->getTableName(), $dqlAlias);
  587. foreach ($assoc['targetToSourceKeyColumns'] as $srcColumn) {
  588. $columnAlias = $this->getSQLColumnAlias($srcColumn);
  589. $sqlSelectExpressions[] = $sqlTableAlias . '.' . $srcColumn . ' AS ' . $columnAlias;
  590. $this->rsm->addMetaResult($dqlAlias, $columnAlias, $srcColumn, (isset($assoc['id']) && $assoc['id'] === true));
  591. }
  592. }
  593. // Add foreign key columns to SQL, if necessary
  594. if ( ! $addMetaColumns) {
  595. continue;
  596. }
  597. // Add foreign key columns of subclasses
  598. foreach ($class->subClasses as $subClassName) {
  599. $subClass = $this->em->getClassMetadata($subClassName);
  600. $sqlTableAlias = $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias);
  601. foreach ($subClass->associationMappings as $assoc) {
  602. // Skip if association is inherited
  603. if (isset($assoc['inherited'])) continue;
  604. if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) continue;
  605. foreach ($assoc['targetToSourceKeyColumns'] as $srcColumn) {
  606. $columnAlias = $this->getSQLColumnAlias($srcColumn);
  607. $sqlSelectExpressions[] = $sqlTableAlias . '.' . $srcColumn . ' AS ' . $columnAlias;
  608. $this->rsm->addMetaResult($dqlAlias, $columnAlias, $srcColumn);
  609. }
  610. }
  611. }
  612. }
  613. $sql .= implode(', ', $sqlSelectExpressions);
  614. return $sql;
  615. }
  616. /**
  617. * Walks down a FromClause AST node, thereby generating the appropriate SQL.
  618. *
  619. * @return string The SQL.
  620. */
  621. public function walkFromClause($fromClause)
  622. {
  623. $identificationVarDecls = $fromClause->identificationVariableDeclarations;
  624. $sqlParts = array();
  625. foreach ($identificationVarDecls as $identificationVariableDecl) {
  626. $sql = $this->walkRangeVariableDeclaration($identificationVariableDecl->rangeVariableDeclaration);
  627. foreach ($identificationVariableDecl->joins as $join) {
  628. $sql .= $this->walkJoin($join);
  629. }
  630. if ($identificationVariableDecl->indexBy) {
  631. $alias = $identificationVariableDecl->indexBy->simpleStateFieldPathExpression->identificationVariable;
  632. $field = $identificationVariableDecl->indexBy->simpleStateFieldPathExpression->field;
  633. if (isset($this->scalarFields[$alias][$field])) {
  634. $this->rsm->addIndexByScalar($this->scalarFields[$alias][$field]);
  635. } else {
  636. $this->rsm->addIndexBy(
  637. $identificationVariableDecl->indexBy->simpleStateFieldPathExpression->identificationVariable,
  638. $identificationVariableDecl->indexBy->simpleStateFieldPathExpression->field
  639. );
  640. }
  641. }
  642. $sqlParts[] = $this->platform->appendLockHint($sql, $this->query->getHint(Query::HINT_LOCK_MODE));
  643. }
  644. return ' FROM ' . implode(', ', $sqlParts);
  645. }
  646. /**
  647. * Walks down a RangeVariableDeclaration AST node, thereby generating the appropriate SQL.
  648. *
  649. * @return string
  650. */
  651. public function walkRangeVariableDeclaration($rangeVariableDeclaration)
  652. {
  653. $class = $this->em->getClassMetadata($rangeVariableDeclaration->abstractSchemaName);
  654. $dqlAlias = $rangeVariableDeclaration->aliasIdentificationVariable;
  655. $this->rootAliases[] = $dqlAlias;
  656. $sql = $class->getQuotedTableName($this->platform) . ' '
  657. . $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
  658. if ($class->isInheritanceTypeJoined()) {
  659. $sql .= $this->_generateClassTableInheritanceJoins($class, $dqlAlias);
  660. }
  661. return $sql;
  662. }
  663. /**
  664. * Walks down a JoinAssociationDeclaration AST node, thereby generating the appropriate SQL.
  665. *
  666. * @return string
  667. */
  668. public function walkJoinAssociationDeclaration($joinAssociationDeclaration, $joinType = AST\Join::JOIN_TYPE_INNER)
  669. {
  670. $sql = '';
  671. $associationPathExpression = $joinAssociationDeclaration->joinAssociationPathExpression;
  672. $joinedDqlAlias = $joinAssociationDeclaration->aliasIdentificationVariable;
  673. $indexBy = $joinAssociationDeclaration->indexBy;
  674. $relation = $this->queryComponents[$joinedDqlAlias]['relation'];
  675. $targetClass = $this->em->getClassMetadata($relation['targetEntity']);
  676. $sourceClass = $this->em->getClassMetadata($relation['sourceEntity']);
  677. $targetTableName = $targetClass->getQuotedTableName($this->platform);
  678. $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName(), $joinedDqlAlias);
  679. $sourceTableAlias = $this->getSQLTableAlias($sourceClass->getTableName(), $associationPathExpression->identificationVariable);
  680. // Ensure we got the owning side, since it has all mapping info
  681. $assoc = ( ! $relation['isOwningSide']) ? $targetClass->associationMappings[$relation['mappedBy']] : $relation;
  682. if ($this->query->getHint(Query::HINT_INTERNAL_ITERATION) == true && (!$this->query->getHint(self::HINT_DISTINCT) || isset($this->selectedClasses[$joinedDqlAlias]))) {
  683. if ($relation['type'] == ClassMetadata::ONE_TO_MANY || $relation['type'] == ClassMetadata::MANY_TO_MANY) {
  684. throw QueryException::iterateWithFetchJoinNotAllowed($assoc);
  685. }
  686. }
  687. // This condition is not checking ClassMetadata::MANY_TO_ONE, because by definition it cannot
  688. // be the owning side and previously we ensured that $assoc is always the owning side of the associations.
  689. // The owning side is necessary at this point because only it contains the JoinColumn information.
  690. switch (true) {
  691. case ($assoc['type'] & ClassMetadata::TO_ONE):
  692. $conditions = array();
  693. foreach ($assoc['joinColumns'] as $joinColumn) {
  694. $quotedSourceColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform);
  695. $quotedTargetColumn = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $targetClass, $this->platform);
  696. if ($relation['isOwningSide']) {
  697. $conditions[] = $sourceTableAlias . '.' . $quotedSourceColumn . ' = ' . $targetTableAlias . '.' . $quotedTargetColumn;
  698. continue;
  699. }
  700. $conditions[] = $sourceTableAlias . '.' . $quotedTargetColumn . ' = ' . $targetTableAlias . '.' . $quotedSourceColumn;
  701. }
  702. // Apply remaining inheritance restrictions
  703. $discrSql = $this->_generateDiscriminatorColumnConditionSQL(array($joinedDqlAlias));
  704. if ($discrSql) {
  705. $conditions[] = $discrSql;
  706. }
  707. // Apply the filters
  708. $filterExpr = $this->generateFilterConditionSQL($targetClass, $targetTableAlias);
  709. if ($filterExpr) {
  710. $conditions[] = $filterExpr;
  711. }
  712. $sql .= $targetTableName . ' ' . $targetTableAlias . ' ON ' . implode(' AND ', $conditions);
  713. break;
  714. case ($assoc['type'] == ClassMetadata::MANY_TO_MANY):
  715. // Join relation table
  716. $joinTable = $assoc['joinTable'];
  717. $joinTableAlias = $this->getSQLTableAlias($joinTable['name'], $joinedDqlAlias);
  718. $joinTableName = $sourceClass->getQuotedJoinTableName($assoc, $this->platform);
  719. $conditions = array();
  720. $relationColumns = ($relation['isOwningSide'])
  721. ? $assoc['joinTable']['joinColumns']
  722. : $assoc['joinTable']['inverseJoinColumns'];
  723. foreach ($relationColumns as $joinColumn) {
  724. $quotedSourceColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform);
  725. $quotedTargetColumn = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $targetClass, $this->platform);
  726. $conditions[] = $sourceTableAlias . '.' . $quotedTargetColumn . ' = ' . $joinTableAlias . '.' . $quotedSourceColumn;
  727. }
  728. $sql .= $joinTableName . ' ' . $joinTableAlias . ' ON ' . implode(' AND ', $conditions);
  729. // Join target table
  730. $sql .= ($joinType == AST\Join::JOIN_TYPE_LEFT || $joinType == AST\Join::JOIN_TYPE_LEFTOUTER) ? ' LEFT JOIN ' : ' INNER JOIN ';
  731. $conditions = array();
  732. $relationColumns = ($relation['isOwningSide'])
  733. ? $assoc['joinTable']['inverseJoinColumns']
  734. : $assoc['joinTable']['joinColumns'];
  735. foreach ($relationColumns as $joinColumn) {
  736. $quotedSourceColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform);
  737. $quotedTargetColumn = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $targetClass, $this->platform);
  738. $conditions[] = $targetTableAlias . '.' . $quotedTargetColumn . ' = ' . $joinTableAlias . '.' . $quotedSourceColumn;
  739. }
  740. // Apply remaining inheritance restrictions
  741. $discrSql = $this->_generateDiscriminatorColumnConditionSQL(array($joinedDqlAlias));
  742. if ($discrSql) {
  743. $conditions[] = $discrSql;
  744. }
  745. // Apply the filters
  746. $filterExpr = $this->generateFilterConditionSQL($targetClass, $targetTableAlias);
  747. if ($filterExpr) {
  748. $conditions[] = $filterExpr;
  749. }
  750. $sql .= $targetTableName . ' ' . $targetTableAlias . ' ON ' . implode(' AND ', $conditions);
  751. break;
  752. }
  753. // FIXME: these should either be nested or all forced to be left joins (DDC-XXX)
  754. if ($targetClass->isInheritanceTypeJoined()) {
  755. $sql .= $this->_generateClassTableInheritanceJoins($targetClass, $joinedDqlAlias);
  756. }
  757. // Apply the indexes
  758. if ($indexBy) {
  759. // For Many-To-One or One-To-One associations this obviously makes no sense, but is ignored silently.
  760. $this->rsm->addIndexBy(
  761. $indexBy->simpleStateFieldPathExpression->identificationVariable,
  762. $indexBy->simpleStateFieldPathExpression->field
  763. );
  764. } else if (isset($relation['indexBy'])) {
  765. $this->rsm->addIndexBy($joinedDqlAlias, $relation['indexBy']);
  766. }
  767. return $sql;
  768. }
  769. /**
  770. * Walks down a FunctionNode AST node, thereby generating the appropriate SQL.
  771. *
  772. * @return string The SQL.
  773. */
  774. public function walkFunction($function)
  775. {
  776. return $function->getSql($this);
  777. }
  778. /**
  779. * Walks down an OrderByClause AST node, thereby generating the appropriate SQL.
  780. *
  781. * @param OrderByClause
  782. * @return string The SQL.
  783. */
  784. public function walkOrderByClause($orderByClause)
  785. {
  786. $orderByItems = array_map(array($this, 'walkOrderByItem'), $orderByClause->orderByItems);
  787. if (($collectionOrderByItems = $this->_generateOrderedCollectionOrderByItems()) !== '') {
  788. $orderByItems = array_merge($orderByItems, (array) $collectionOrderByItems);
  789. }
  790. return ' ORDER BY ' . implode(', ', $orderByItems);
  791. }
  792. /**
  793. * Walks down an OrderByItem AST node, thereby generating the appropriate SQL.
  794. *
  795. * @param OrderByItem
  796. * @return string The SQL.
  797. */
  798. public function walkOrderByItem($orderByItem)
  799. {
  800. $expr = $orderByItem->expression;
  801. $sql = ($expr instanceof AST\Node)
  802. ? $expr->dispatch($this)
  803. : $this->walkResultVariable($this->queryComponents[$expr]['token']['value']);
  804. return $sql . ' ' . strtoupper($orderByItem->type);
  805. }
  806. /**
  807. * Walks down a HavingClause AST node, thereby generating the appropriate SQL.
  808. *
  809. * @param HavingClause
  810. * @return string The SQL.
  811. */
  812. public function walkHavingClause($havingClause)
  813. {
  814. return ' HAVING ' . $this->walkConditionalExpression($havingClause->conditionalExpression);
  815. }
  816. /**
  817. * Walks down a Join AST node and creates the corresponding SQL.
  818. *
  819. * @return string The SQL.
  820. */
  821. public function walkJoin($join)
  822. {
  823. $joinType = $join->joinType;
  824. $joinDeclaration = $join->joinAssociationDeclaration;
  825. $sql = ($joinType == AST\Join::JOIN_TYPE_LEFT || $joinType == AST\Join::JOIN_TYPE_LEFTOUTER)
  826. ? ' LEFT JOIN '
  827. : ' INNER JOIN ';
  828. switch (true) {
  829. case ($joinDeclaration instanceof \Doctrine\ORM\Query\AST\RangeVariableDeclaration):
  830. $class = $this->em->getClassMetadata($joinDeclaration->abstractSchemaName);
  831. $condExprConjunction = $class->isInheritanceTypeJoined() && $joinType != AST\Join::JOIN_TYPE_LEFT && $joinType != AST\Join::JOIN_TYPE_LEFTOUTER
  832. ? ' AND '
  833. : ' ON ';
  834. $sql .= $this->walkRangeVariableDeclaration($joinDeclaration)
  835. . $condExprConjunction . '(' . $this->walkConditionalExpression($join->conditionalExpression) . ')';
  836. break;
  837. case ($joinDeclaration instanceof \Doctrine\ORM\Query\AST\JoinAssociationDeclaration):
  838. $sql .= $this->walkJoinAssociationDeclaration($joinDeclaration, $joinType);
  839. // Handle WITH clause
  840. if (($condExpr = $join->conditionalExpression) !== null) {
  841. // Phase 2 AST optimization: Skip processment of ConditionalExpression
  842. // if only one ConditionalTerm is defined
  843. $sql .= ' AND (' . $this->walkConditionalExpression($condExpr) . ')';
  844. }
  845. break;
  846. }
  847. return $sql;
  848. }
  849. /**
  850. * Walks down a CaseExpression AST node and generates the corresponding SQL.
  851. *
  852. * @param CoalesceExpression|NullIfExpression|GeneralCaseExpression|SimpleCaseExpression $expression
  853. * @return string The SQL.
  854. */
  855. public function walkCaseExpression($expression)
  856. {
  857. switch (true) {
  858. case ($expression instanceof AST\CoalesceExpression):
  859. return $this->walkCoalesceExpression($expression);
  860. case ($expression instanceof AST\NullIfExpression):
  861. return $this->walkNullIfExpression($expression);
  862. case ($expression instanceof AST\GeneralCaseExpression):
  863. return $this->walkGeneralCaseExpression($expression);
  864. case ($expression instanceof AST\SimpleCaseExpression):
  865. return $this->walkSimpleCaseExpression($expression);
  866. default:
  867. return '';
  868. }
  869. }
  870. /**
  871. * Walks down a CoalesceExpression AST node and generates the corresponding SQL.
  872. *
  873. * @param CoalesceExpression $coalesceExpression
  874. * @return string The SQL.
  875. */
  876. public function walkCoalesceExpression($coalesceExpression)
  877. {
  878. $sql = 'COALESCE(';
  879. $scalarExpressions = array();
  880. foreach ($coalesceExpression->scalarExpressions as $scalarExpression) {
  881. $scalarExpressions[] = $this->walkSimpleArithmeticExpression($scalarExpression);
  882. }
  883. $sql .= implode(', ', $scalarExpressions) . ')';
  884. return $sql;
  885. }
  886. /**
  887. * Walks down a NullIfExpression AST node and generates the corresponding SQL.
  888. *
  889. * @param NullIfExpression $nullIfExpression
  890. * @return string The SQL.
  891. */
  892. public function walkNullIfExpression($nullIfExpression)
  893. {
  894. $firstExpression = is_string($nullIfExpression->firstExpression)
  895. ? $this->conn->quote($nullIfExpression->firstExpression)
  896. : $this->walkSimpleArithmeticExpression($nullIfExpression->firstExpression);
  897. $secondExpression = is_string($nullIfExpression->secondExpression)
  898. ? $this->conn->quote($nullIfExpression->secondExpression)
  899. : $this->walkSimpleArithmeticExpression($nullIfExpression->secondExpression);
  900. return 'NULLIF(' . $firstExpression . ', ' . $secondExpression . ')';
  901. }
  902. /**
  903. * Walks down a GeneralCaseExpression AST node and generates the corresponding SQL.
  904. *
  905. * @param GeneralCaseExpression $generalCaseExpression
  906. * @return string The SQL.
  907. */
  908. public function walkGeneralCaseExpression(AST\GeneralCaseExpression $generalCaseExpression)
  909. {
  910. $sql = 'CASE';
  911. foreach ($generalCaseExpression->whenClauses as $whenClause) {
  912. $sql .= ' WHEN ' . $this->walkConditionalExpression($whenClause->caseConditionExpression);
  913. $sql .= ' THEN ' . $this->walkSimpleArithmeticExpression($whenClause->thenScalarExpression);
  914. }
  915. $sql .= ' ELSE ' . $this->walkSimpleArithmeticExpression($generalCaseExpression->elseScalarExpression) . ' END';
  916. return $sql;
  917. }
  918. /**
  919. * Walks down a SimpleCaseExpression AST node and generates the corresponding SQL.
  920. *
  921. * @param SimpleCaseExpression $simpleCaseExpression
  922. * @return string The SQL.
  923. */
  924. public function walkSimpleCaseExpression($simpleCaseExpression)
  925. {
  926. $sql = 'CASE ' . $this->walkStateFieldPathExpression($simpleCaseExpression->caseOperand);
  927. foreach ($simpleCaseExpression->simpleWhenClauses as $simpleWhenClause) {
  928. $sql .= ' WHEN ' . $this->walkSimpleArithmeticExpression($simpleWhenClause->caseScalarExpression);
  929. $sql .= ' THEN ' . $this->walkSimpleArithmeticExpression($simpleWhenClause->thenScalarExpression);
  930. }
  931. $sql .= ' ELSE ' . $this->walkSimpleArithmeticExpression($simpleCaseExpression->elseScalarExpression) . ' END';
  932. return $sql;
  933. }
  934. /**
  935. * Walks down a SelectExpression AST node and generates the corresponding SQL.
  936. *
  937. * @param SelectExpression $selectExpression
  938. * @return string The SQL.
  939. */
  940. public function walkSelectExpression($selectExpression)
  941. {
  942. $sql = '';
  943. $expr = $selectExpression->expression;
  944. $hidden = $selectExpression->hiddenAliasResultVariable;
  945. switch (true) {
  946. case ($expr instanceof AST\PathExpression):
  947. if ($expr->type !== AST\PathExpression::TYPE_STATE_FIELD) {
  948. throw QueryException::invalidPathExpression($expr);
  949. }
  950. $fieldName = $expr->field;
  951. $dqlAlias = $expr->identificationVariable;
  952. $qComp = $this->queryComponents[$dqlAlias];
  953. $class = $qComp['metadata'];
  954. $resultAlias = $selectExpression->fieldIdentificationVariable ?: $fieldName;
  955. $tableName = ($class->isInheritanceTypeJoined())
  956. ? $this->em->getUnitOfWork()->getEntityPersister($class->name)->getOwningTable($fieldName)
  957. : $class->getTableName();
  958. $sqlTableAlias = $this->getSQLTableAlias($tableName, $dqlAlias);
  959. $columnName = $this->quoteStrategy->getColumnName($fieldName, $class, $this->platform);
  960. $columnAlias = $this->getSQLColumnAlias($class->fieldMappings[$fieldName]['columnName']);
  961. $col = $sqlTableAlias . '.' . $columnName;
  962. $fieldType = $class->getTypeOfField($fieldName);
  963. if (isset($class->fieldMappings[$fieldName]['requireSQLConversion'])) {
  964. $type = Type::getType($fieldType);
  965. $col = $type->convertToPHPValueSQL($col, $this->conn->getDatabasePlatform());
  966. }
  967. $sql .= $col . ' AS ' . $columnAlias;
  968. $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
  969. if ( ! $hidden) {
  970. $this->rsm->addScalarResult($columnAlias, $resultAlias, $fieldType);
  971. $this->scalarFields[$dqlAlias][$fieldName] = $columnAlias;
  972. }
  973. break;
  974. case ($expr instanceof AST\AggregateExpression):
  975. case ($expr instanceof AST\Functions\FunctionNode):
  976. case ($expr instanceof AST\SimpleArithmeticExpression):
  977. case ($expr instanceof AST\ArithmeticTerm):
  978. case ($expr instanceof AST\ArithmeticFactor):
  979. case ($expr instanceof AST\Literal):
  980. case ($expr instanceof AST\NullIfExpression):
  981. case ($expr instanceof AST\CoalesceExpression):
  982. case ($expr instanceof AST\GeneralCaseExpression):
  983. case ($expr instanceof AST\SimpleCaseExpression):
  984. $columnAlias = $this->getSQLColumnAlias('sclr');
  985. $resultAlias = $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
  986. $sql .= $expr->dispatch($this) . ' AS ' . $columnAlias;
  987. $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
  988. if ( ! $hidden) {
  989. // We cannot resolve field type here; assume 'string'.
  990. $this->rsm->addScalarResult($columnAlias, $resultAlias, 'string');
  991. }
  992. break;
  993. case ($expr instanceof AST\Subselect):
  994. $columnAlias = $this->getSQLColumnAlias('sclr');
  995. $resultAlias = $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
  996. $sql .= '(' . $this->walkSubselect($expr) . ') AS ' . $columnAlias;
  997. $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
  998. if ( ! $hidden) {
  999. // We cannot resolve field type here; assume 'string'.
  1000. $this->rsm->addScalarResult($columnAlias, $resultAlias, 'string');
  1001. }
  1002. break;
  1003. default:
  1004. // IdentificationVariable or PartialObjectExpression
  1005. if ($expr instanceof AST\PartialObjectExpression) {
  1006. $dqlAlias = $expr->identificationVariable;
  1007. $partialFieldSet = $expr->partialFieldSet;
  1008. } else {
  1009. $dqlAlias = $expr;
  1010. $partialFieldSet = array();
  1011. }
  1012. $queryComp = $this->queryComponents[$dqlAlias];
  1013. $class = $queryComp['metadata'];
  1014. $resultAlias = $selectExpression->fieldIdentificationVariable ?: null;
  1015. if ( ! isset($this->selectedClasses[$dqlAlias])) {
  1016. $this->selectedClasses[$dqlAlias] = array(
  1017. 'class' => $class,
  1018. 'dqlAlias' => $dqlAlias,
  1019. 'resultAlias' => $resultAlias
  1020. );
  1021. }
  1022. $sqlParts = array();
  1023. // Select all fields from the queried class
  1024. foreach ($class->fieldMappings as $fieldName => $mapping) {
  1025. if ($partialFieldSet && ! in_array($fieldName, $partialFieldSet)) {
  1026. continue;
  1027. }
  1028. $tableName = (isset($mapping['inherited']))
  1029. ? $this->em->getClassMetadata($mapping['inherited'])->getTableName()
  1030. : $class->getTableName();
  1031. $sqlTableAlias = $this->getSQLTableAlias($tableName, $dqlAlias);
  1032. $columnAlias = $this->getSQLColumnAlias($mapping['columnName']);
  1033. $quotedColumnName = $this->quoteStrategy->getColumnName($fieldName, $class, $this->platform);
  1034. $col = $sqlTableAlias . '.' . $quotedColumnName;
  1035. if (isset($class->fieldMappings[$fieldName]['requireSQLConversion'])) {
  1036. $type = Type::getType($class->getTypeOfField($fieldName));
  1037. $col = $type->convertToPHPValueSQL($col, $this->platform);
  1038. }
  1039. $sqlParts[] = $col . ' AS '. $columnAlias;
  1040. $this->scalarResultAliasMap[$resultAlias][] = $columnAlias;
  1041. $this->rsm->addFieldResult($dqlAlias, $columnAlias, $fieldName, $class->name);
  1042. }
  1043. // Add any additional fields of subclasses (excluding inherited fields)
  1044. // 1) on Single Table Inheritance: always, since its marginal overhead
  1045. // 2) on Class Table Inheritance only if partial objects are disallowed,
  1046. // since it requires outer joining subtables.
  1047. if ($class->isInheritanceTypeSingleTable() || ! $this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD)) {
  1048. foreach ($class->subClasses as $subClassName) {
  1049. $subClass = $this->em->getClassMetadata($subClassName);
  1050. $sqlTableAlias = $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias);
  1051. foreach ($subClass->fieldMappings as $fieldName => $mapping) {
  1052. if (isset($mapping['inherited']) || $partialFieldSet && !in_array($fieldName, $partialFieldSet)) {
  1053. continue;
  1054. }
  1055. $columnAlias = $this->getSQLColumnAlias($mapping['columnName']);
  1056. $quotedColumnName = $this->quoteStrategy->get

Large files files are truncated, but you can click here to view the full file