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

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

https://github.com/kadryjanek/doctrine2
PHP | 2189 lines | 1275 code | 427 blank | 487 comment | 150 complexity | bd98dfdec714e594ac0fca722b96056a MD5 | raw file

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

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