PageRenderTime 68ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  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->getColumnName($fieldName, $subClass, $this->platform);
  1057. $col = $sqlTableAlias . '.' . $quotedColumnName;
  1058. if (isset($subClass->fieldMappings[$fieldName]['requireSQLConversion'])) {
  1059. $type = Type::getType($subClass->getTypeOfField($fieldName));
  1060. $col = $type->convertToPHPValueSQL($col, $this->platform);
  1061. }
  1062. $sqlParts[] = $col . ' AS ' . $columnAlias;
  1063. $this->scalarResultAliasMap[$resultAlias][] = $columnAlias;
  1064. $this->rsm->addFieldResult($dqlAlias, $columnAlias, $fieldName, $subClassName);
  1065. }
  1066. }
  1067. }
  1068. $sql .= implode(', ', $sqlParts);
  1069. }
  1070. return $sql;
  1071. }
  1072. /**
  1073. * Walks down a QuantifiedExpression AST node, thereby generating the appropriate SQL.
  1074. *
  1075. * @param QuantifiedExpression
  1076. * @return string The SQL.
  1077. */
  1078. public function walkQuantifiedExpression($qExpr)
  1079. {
  1080. return ' ' . strtoupper($qExpr->type) . '(' . $this->walkSubselect($qExpr->subselect) . ')';
  1081. }
  1082. /**
  1083. * Walks down a Subselect AST node, thereby generating the appropriate SQL.
  1084. *
  1085. * @param Subselect
  1086. * @return string The SQL.
  1087. */
  1088. public function walkSubselect($subselect)
  1089. {
  1090. $useAliasesBefore = $this->useSqlTableAliases;
  1091. $rootAliasesBefore = $this->rootAliases;
  1092. $this->rootAliases = array(); // reset the rootAliases for the subselect
  1093. $this->useSqlTableAliases = true;
  1094. $sql = $this->walkSimpleSelectClause($subselect->simpleSelectClause);
  1095. $sql .= $this->walkSubselectFromClause($subselect->subselectFromClause);
  1096. $sql .= $this->walkWhereClause($subselect->whereClause);
  1097. $sql .= $subselect->groupByClause ? $this->walkGroupByClause($subselect->groupByClause) : '';
  1098. $sql .= $subselect->havingClause ? $this->walkHavingClause($subselect->havingClause) : '';
  1099. $sql .= $subselect->orderByClause ? $this->walkOrderByClause($subselect->orderByClause) : '';
  1100. $this->rootAliases = $rootAliasesBefore; // put the main aliases back
  1101. $this->useSqlTableAliases = $useAliasesBefore;
  1102. return $sql;
  1103. }
  1104. /**
  1105. * Walks down a SubselectFromClause AST node, thereby generating the appropriate SQL.
  1106. *
  1107. * @param SubselectFromClause
  1108. * @return string The SQL.
  1109. */
  1110. public function walkSubselectFromClause($subselectFromClause)
  1111. {
  1112. $identificationVarDecls = $subselectFromClause->identificationVariableDeclarations;
  1113. $sqlParts = array ();
  1114. foreach ($identificationVarDecls as $subselectIdVarDecl) {
  1115. $sql = $this->walkRangeVariableDeclaration($subselectIdVarDecl->rangeVariableDeclaration);
  1116. foreach ($subselectIdVarDecl->joins as $join) {
  1117. $sql .= $this->walkJoin($join);
  1118. }
  1119. $sqlParts[] = $this->platform->appendLockHint($sql, $this->query->getHint(Query::HINT_LOCK_MODE));
  1120. }
  1121. return ' FROM ' . implode(', ', $sqlParts);
  1122. }
  1123. /**
  1124. * Walks down a SimpleSelectClause AST node, thereby generating the appropriate SQL.
  1125. *
  1126. * @param SimpleSelectClause
  1127. * @return string The SQL.
  1128. */
  1129. public function walkSimpleSelectClause($simpleSelectClause)
  1130. {
  1131. return 'SELECT' . ($simpleSelectClause->isDistinct ? ' DISTINCT' : '')
  1132. . $this->walkSimpleSelectExpression($simpleSelectClause->simpleSelectExpression);
  1133. }
  1134. /**
  1135. * Walks down a SimpleSelectExpression AST node, thereby generating the appropriate SQL.
  1136. *
  1137. * @param SimpleSelectExpression
  1138. * @return string The SQL.
  1139. */
  1140. public function walkSimpleSelectExpression($simpleSelectExpression)
  1141. {
  1142. $expr = $simpleSelectExpression->expression;
  1143. $sql = ' ';
  1144. switch (true) {
  1145. case ($expr instanceof AST\PathExpression):
  1146. $sql .= $this->walkPathExpression($expr);
  1147. break;
  1148. case ($expr instanceof AST\AggregateExpression):
  1149. $alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
  1150. $sql .= $this->walkAggregateExpression($expr) . ' AS dctrn__' . $alias;
  1151. break;
  1152. case ($expr instanceof AST\Subselect):
  1153. $alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
  1154. $columnAlias = 'sclr' . $this->aliasCounter++;
  1155. $this->scalarResultAliasMap[$alias] = $columnAlias;
  1156. $sql .= '(' . $this->walkSubselect($expr) . ') AS ' . $columnAlias;
  1157. break;
  1158. case ($expr instanceof AST\Functions\FunctionNode):
  1159. case ($expr instanceof AST\SimpleArithmeticExpression):
  1160. case ($expr instanceof AST\ArithmeticTerm):
  1161. case ($expr instanceof AST\ArithmeticFactor):
  1162. case ($expr instanceof AST\Literal):
  1163. case ($expr instanceof AST\NullIfExpression):
  1164. case ($expr instanceof AST\CoalesceExpression):
  1165. case ($expr instanceof AST\GeneralCaseExpression):
  1166. case ($expr instanceof AST\SimpleCaseExpression):
  1167. $alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
  1168. $columnAlias = $this->getSQLColumnAlias('sclr');
  1169. $this->scalarResultAliasMap[$alias] = $columnAlias;
  1170. $sql .= $expr->dispatch($this) . ' AS ' . $columnAlias;
  1171. break;
  1172. default: // IdentificationVariable
  1173. $sql .= $this->walkEntityIdentificationVariable($expr);
  1174. break;
  1175. }
  1176. return $sql;
  1177. }
  1178. /**
  1179. * Walks down an AggregateExpression AST node, thereby generating the appropriate SQL.
  1180. *
  1181. * @param AggregateExpression
  1182. * @return string The SQL.
  1183. */
  1184. public function walkAggregateExpression($aggExpression)
  1185. {
  1186. return $aggExpression->functionName . '(' . ($aggExpression->isDistinct ? 'DISTINCT ' : '')
  1187. . $this->walkSimpleArithmeticExpression($aggExpression->pathExpression) . ')';
  1188. }
  1189. /**
  1190. * Walks down a GroupByClause AST node, thereby generating the appropriate SQL.
  1191. *
  1192. * @param GroupByClause
  1193. * @return string The SQL.
  1194. */
  1195. public function walkGroupByClause($groupByClause)
  1196. {
  1197. $sqlParts = array();
  1198. foreach ($groupByClause->groupByItems as $groupByItem) {
  1199. $sqlParts[] = $this->walkGroupByItem($groupByItem);
  1200. }
  1201. return ' GROUP BY ' . implode(', ', $sqlParts);
  1202. }
  1203. /**
  1204. * Walks down a GroupByItem AST node, thereby generating the appropriate SQL.
  1205. *
  1206. * @param GroupByItem
  1207. * @return string The SQL.
  1208. */
  1209. public function walkGroupByItem($groupByItem)
  1210. {
  1211. // StateFieldPathExpression
  1212. if ( ! is_string($groupByItem)) {
  1213. return $this->walkPathExpression($groupByItem);
  1214. }
  1215. // ResultVariable
  1216. if (isset($this->queryComponents[$groupByItem]['resultVariable'])) {
  1217. return $this->walkResultVariable($groupByItem);
  1218. }
  1219. // IdentificationVariable
  1220. $sqlParts = array();
  1221. foreach ($this->queryComponents[$groupByItem]['metadata']->fieldNames as $field) {
  1222. $item = new AST\PathExpression(AST\PathExpression::TYPE_STATE_FIELD, $groupByItem, $field);
  1223. $item->type = AST\PathExpression::TYPE_STATE_FIELD;
  1224. $sqlParts[] = $this->walkPathExpression($item);
  1225. }
  1226. foreach ($this->queryComponents[$groupByItem]['metadata']->associationMappings as $mapping) {
  1227. if ($mapping['isOwningSide'] && $mapping['type'] & ClassMetadataInfo::TO_ONE) {
  1228. $item = new AST\PathExpression(AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, $groupByItem, $mapping['fieldName']);
  1229. $item->type = AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION;
  1230. $sqlParts[] = $this->walkPathExpression($item);
  1231. }
  1232. }
  1233. return implode(', ', $sqlParts);
  1234. }
  1235. /**
  1236. * Walks down a DeleteClause AST node, thereby generating the appropriate SQL.
  1237. *
  1238. * @param DeleteClause
  1239. * @return string The SQL.
  1240. */
  1241. public function walkDeleteClause(AST\DeleteClause $deleteClause)
  1242. {
  1243. $class = $this->em->getClassMetadata($deleteClause->abstractSchemaName);
  1244. $tableName = $class->getTableName();
  1245. $sql = 'DELETE FROM ' . $this->quoteStrategy->getTableName($class, $this->platform);
  1246. $this->setSQLTableAlias($tableName, $tableName, $deleteClause->aliasIdentificationVariable);
  1247. $this->rootAliases[] = $deleteClause->aliasIdentificationVariable;
  1248. return $sql;
  1249. }
  1250. /**
  1251. * Walks down an UpdateClause AST node, thereby generating the appropriate SQL.
  1252. *
  1253. * @param UpdateClause
  1254. * @return string The SQL.
  1255. */
  1256. public function walkUpdateClause($updateClause)
  1257. {
  1258. $class = $this->em->getClassMetadata($updateClause->abstractSchemaName);
  1259. $tableName = $class->getTableName();
  1260. $sql = 'UPDATE ' . $this->quoteStrategy->getTableName($class, $this->platform);
  1261. $this->setSQLTableAlias($tableName, $tableName, $updateClause->aliasIdentificationVariable);
  1262. $this->rootAliases[] = $updateClause->aliasIdentificationVariable;
  1263. $sql .= ' SET ' . implode(', ', array_map(array($this, 'walkUpdateItem'), $updateClause->updateItems));
  1264. return $sql;
  1265. }
  1266. /**
  1267. * Walks down an UpdateItem AST node, thereby generating the appropriate SQL.
  1268. *
  1269. * @param UpdateItem
  1270. * @return string The SQL.
  1271. */
  1272. public function walkUpdateItem($updateItem)
  1273. {
  1274. $useTableAliasesBefore = $this->useSqlTableAliases;
  1275. $this->useSqlTableAliases = false;
  1276. $sql = $this->walkPathExpression($updateItem->pathExpression) . ' = ';
  1277. $newValue = $updateItem->newValue;
  1278. switch (true) {
  1279. case ($newValue instanceof AST\Node):
  1280. $sql .= $newValue->dispatch($this);
  1281. break;
  1282. case ($newValue === null):
  1283. $sql .= 'NULL';
  1284. break;
  1285. default:
  1286. $sql .= $this->conn->quote($newValue);
  1287. break;
  1288. }
  1289. $this->useSqlTableAliases = $useTableAliasesBefore;
  1290. return $sql;
  1291. }
  1292. /**
  1293. * Walks down a WhereClause AST node, thereby generating the appropriate SQL.
  1294. * WhereClause or not, the appropriate discriminator sql is added.
  1295. *
  1296. * @param WhereClause
  1297. * @return string The SQL.
  1298. */
  1299. public function walkWhereClause($whereClause)
  1300. {
  1301. $condSql = null !== $whereClause ? $this->walkConditionalExpression($whereClause->conditionalExpression) : '';
  1302. $discrSql = $this->_generateDiscriminatorColumnConditionSql($this->rootAliases);
  1303. if ($this->em->hasFilters()) {
  1304. $filterClauses = array();
  1305. foreach ($this->rootAliases as $dqlAlias) {
  1306. $class = $this->queryComponents[$dqlAlias]['metadata'];
  1307. $tableAlias = $this->getSQLTableAlias($class->table['name'], $dqlAlias);
  1308. if ($filterExpr = $this->generateFilterConditionSQL($class, $tableAlias)) {
  1309. $filterClauses[] = $filterExpr;
  1310. }
  1311. }
  1312. if (count($filterClauses)) {
  1313. if ($condSql) {
  1314. $condSql = '(' . $condSql . ') AND ';
  1315. }
  1316. $condSql .= implode(' AND ', $filterClauses);
  1317. }
  1318. }
  1319. if ($condSql) {
  1320. return ' WHERE ' . (( ! $discrSql) ? $condSql : '(' . $condSql . ') AND ' . $discrSql);
  1321. }
  1322. if ($discrSql) {
  1323. return ' WHERE ' . $discrSql;
  1324. }
  1325. return '';
  1326. }
  1327. /**
  1328. * Walk down a ConditionalExpression AST node, thereby generating the appropriate SQL.
  1329. *
  1330. * @param ConditionalExpression
  1331. * @return string The SQL.
  1332. */
  1333. public function walkConditionalExpression($condExpr)
  1334. {
  1335. // Phase 2 AST optimization: Skip processment of ConditionalExpression
  1336. // if only one ConditionalTerm is defined
  1337. if ( ! ($condExpr instanceof AST\ConditionalExpression)) {
  1338. return $this->walkConditionalTerm($condExpr);
  1339. }
  1340. return implode(' OR ', array_map(array($this, 'walkConditionalTerm'), $condExpr->conditionalTerms));
  1341. }
  1342. /**
  1343. * Walks down a ConditionalTerm AST node, thereby generating the appropriate SQL.
  1344. *
  1345. * @param ConditionalTerm
  1346. * @return string The SQL.
  1347. */
  1348. public function walkConditionalTerm($condTerm)
  1349. {
  1350. // Phase 2 AST optimization: Skip processment of ConditionalTerm
  1351. // if only one ConditionalFactor is defined
  1352. if ( ! ($condTerm instanceof AST\ConditionalTerm)) {
  1353. return $this->walkConditionalFactor($condTerm);
  1354. }
  1355. return implode(' AND ', array_map(array($this, 'walkConditionalFactor'), $condTerm->conditionalFactors));
  1356. }
  1357. /**
  1358. * Walks down a ConditionalFactor AST node, thereby generating the appropriate SQL.
  1359. *
  1360. * @param ConditionalFactor
  1361. * @return string The SQL.
  1362. */
  1363. public function walkConditionalFactor($factor)
  1364. {
  1365. // Phase 2 AST optimization: Skip processment of ConditionalFactor
  1366. // if only one ConditionalPrimary is defined
  1367. return ( ! ($factor instanceof AST\ConditionalFactor))
  1368. ? $this->walkConditionalPrimary($factor)
  1369. : ($factor->not ? 'NOT ' : '') . $this->walkConditionalPrimary($factor->conditionalPrimary);
  1370. }
  1371. /**
  1372. * Walks down a ConditionalPrimary AST node, thereby generating the appropriate SQL.
  1373. *
  1374. * @param ConditionalPrimary
  1375. * @return string The SQL.
  1376. */
  1377. public function walkConditionalPrimary($primary)
  1378. {
  1379. if ($primary->isSimpleConditionalExpression()) {
  1380. return $primary->simpleConditionalExpression->dispatch($this);
  1381. }
  1382. if ($primary->isConditionalExpression()) {
  1383. $condExpr = $primary->conditionalExpression;
  1384. return '(' . $this->walkConditionalExpression($condExpr) . ')';
  1385. }
  1386. }
  1387. /**
  1388. * Walks down an ExistsExpression AST node, thereby generating the appropriate SQL.
  1389. *
  1390. * @param ExistsExpression
  1391. * @return string The SQL.
  1392. */
  1393. public function walkExistsExpression($existsExpr)
  1394. {
  1395. $sql = ($existsExpr->not) ? 'NOT ' : '';
  1396. $sql .= 'EXISTS (' . $this->walkSubselect($existsExpr->subselect) . ')';
  1397. return $sql;
  1398. }
  1399. /**
  1400. * Walks down a CollectionMemberExpression AST node, thereby generating the appropriate SQL.
  1401. *
  1402. * @param CollectionMemberExpression
  1403. * @return string The SQL.
  1404. */
  1405. public function walkCollectionMemberExpression($collMemberExpr)
  1406. {
  1407. $sql = $collMemberExpr->not ? 'NOT ' : '';
  1408. $sql .= 'EXISTS (SELECT 1 FROM ';
  1409. $entityExpr = $collMemberExpr->entityExpression;
  1410. $collPathExpr = $collMemberExpr->collectionValuedPathExpression;
  1411. $fieldName = $collPathExpr->field;
  1412. $dqlAlias = $collPathExpr->identificationVariable;
  1413. $class = $this->queryComponents[$dqlAlias]['metadata'];
  1414. switch (true) {
  1415. // InputParameter
  1416. case ($entityExpr instanceof AST\InputParameter):
  1417. $dqlParamKey = $entityExpr->name;
  1418. $entitySql = '?';
  1419. break;
  1420. // SingleValuedAssociationPathExpression | IdentificationVariable
  1421. case ($entityExpr instanceof AST\PathExpression):
  1422. $entitySql = $this->walkPathExpression($entityExpr);
  1423. break;
  1424. default:
  1425. throw new \BadMethodCallException("Not implemented");
  1426. }
  1427. $assoc = $class->associationMappings[$fieldName];
  1428. if ($assoc['type'] == ClassMetadata::ONE_TO_MANY) {
  1429. $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
  1430. $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName());
  1431. $sourceTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
  1432. $sql .= $this->quoteStrategy->getTableName($targetClass, $this->platform) . ' ' . $targetTableAlias . ' WHERE ';
  1433. $owningAssoc = $targetClass->associationMappings[$assoc['mappedBy']];
  1434. $sqlParts = array();
  1435. foreach ($owningAssoc['targetToSourceKeyColumns'] as $targetColumn => $sourceColumn) {
  1436. $targetColumn = $this->quoteStrategy->getColumnName($class->fieldNames[$targetColumn], $class, $this->platform);
  1437. $sqlParts[] = $sourceTableAlias . '.' . $targetColumn . ' = ' . $targetTableAlias . '.' . $sourceColumn;
  1438. }
  1439. foreach ($this->quoteStrategy->getIdentifierColumnNames($targetClass, $this->platform) as $targetColumnName) {
  1440. if (isset($dqlParamKey)) {
  1441. $this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++);
  1442. }
  1443. $sqlParts[] = $targetTableAlias . '.' . $targetColumnName . ' = ' . $entitySql;
  1444. }
  1445. $sql .= implode(' AND ', $sqlParts);
  1446. } else { // many-to-many
  1447. $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
  1448. $owningAssoc = $assoc['isOwningSide'] ? $assoc : $targetClass->associationMappings[$assoc['mappedBy']];
  1449. $joinTable = $owningAssoc['joinTable'];
  1450. // SQL table aliases
  1451. $joinTableAlias = $this->getSQLTableAlias($joinTable['name']);
  1452. $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName());
  1453. $sourceTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
  1454. // join to target table
  1455. $sql .= $this->quoteStrategy->getJoinTableName($owningAssoc, $targetClass, $this->platform) . ' ' . $joinTableAlias
  1456. . ' INNER JOIN ' . $this->quoteStrategy->getTableName($targetClass, $this->platform) . ' ' . $targetTableAlias . ' ON ';
  1457. // join conditions
  1458. $joinColumns = $assoc['isOwningSide'] ? $joinTable['inverseJoinColumns'] : $joinTable['joinColumns'];
  1459. $joinSqlParts = array();
  1460. foreach ($joinColumns as $joinColumn) {
  1461. $targetColumn = $this->quoteStrategy->getColumnName($targetClass->fieldNames[$joinColumn['referencedColumnName']], $targetClass, $this->platform);
  1462. $joinSqlParts[] = $joinTableAlias . '.' . $joinColumn['name'] . ' = ' . $targetTableAlias . '.' . $targetColumn;
  1463. }
  1464. $sql .= implode(' AND ', $joinSqlParts);
  1465. $sql .= ' WHERE ';
  1466. $joinColumns = $assoc['isOwningSide'] ? $joinTable['joinColumns'] : $joinTable['inverseJoinColumns'];
  1467. $sqlParts = array();
  1468. foreach ($joinColumns as $joinColumn) {
  1469. $targetColumn = $this->quoteStrategy->getColumnName($class->fieldNames[$joinColumn['referencedColumnName']], $class, $this->platform);
  1470. $sqlParts[] = $joinTableAlias . '.' . $joinColumn['name'] . ' = ' . $sourceTableAlias . '.' . $targetColumn;
  1471. }
  1472. foreach ($this->quoteStrategy->getIdentifierColumnNames($targetClass, $this->platform) as $targetColumnName) {
  1473. if (isset($dqlParamKey)) {
  1474. $this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++);
  1475. }
  1476. $sqlParts[] = $targetTableAlias . '.' . $targetColumnName . ' = ' . $entitySql;
  1477. }
  1478. $sql .= implode(' AND ', $sqlParts);
  1479. }
  1480. return $sql . ')';
  1481. }
  1482. /**
  1483. * Walks down an EmptyCollectionComparisonExpression AST node, thereby generating the appropriate SQL.
  1484. *
  1485. * @param EmptyCollectionComparisonExpression
  1486. * @return string The SQL.
  1487. */
  1488. public function walkEmptyCollectionComparisonExpression($emptyCollCompExpr)
  1489. {
  1490. $sizeFunc = new AST\Functions\SizeFunction('size');
  1491. $sizeFunc->collectionPathExpression = $emptyCollCompExpr->expression;
  1492. return $sizeFunc->getSql($this) . ($emptyCollCompExpr->not ? ' > 0' : ' = 0');
  1493. }
  1494. /**
  1495. * Walks down a NullComparisonExpression AST node, thereby generating the appropriate SQL.
  1496. *
  1497. * @param NullComparisonExpression
  1498. * @return string The SQL.
  1499. */
  1500. public function walkNullComparisonExpression($nullCompExpr)
  1501. {
  1502. $sql = '';
  1503. $innerExpr = $nullCompExpr->expression;
  1504. if ($innerExpr instanceof AST\InputParameter) {
  1505. $dqlParamKey = $innerExpr->name;
  1506. $this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++);
  1507. $sql .= ' ?';
  1508. } else {
  1509. $sql .= $this->walkPathExpression($innerExpr);
  1510. }
  1511. $sql .= ' IS' . ($nullCompExpr->not ? ' NOT' : '') . ' NULL';
  1512. return $sql;
  1513. }
  1514. /**
  1515. * Walks down an InExpression AST node, thereby generating the appropriate SQL.
  1516. *
  1517. * @param InExpression
  1518. * @return string The SQL.
  1519. */
  1520. public function walkInExpression($inExpr)
  1521. {
  1522. $sql = $this->walkArithmeticExpression($inExpr->expression) . ($inExpr->not ? ' NOT' : '') . ' IN (';
  1523. $sql .= ($inExpr->subselect)
  1524. ? $this->walkSubselect($inExpr->subselect)
  1525. : implode(', ', array_map(array($this, 'walkInParameter'), $inExpr->literals));
  1526. $sql .= ')';
  1527. return $sql;
  1528. }
  1529. /**
  1530. * Walks down an InstanceOfExpression AST node, thereby generating the appropriate SQL.
  1531. *
  1532. * @param InstanceOfExpression
  1533. * @return string The SQL.
  1534. */
  1535. public function walkInstanceOfExpression($instanceOfExpr)
  1536. {
  1537. $sql = '';
  1538. $dqlAlias = $instanceOfExpr->identificationVariable;
  1539. $discrClass = $class = $this->queryComponents[$dqlAlias]['metadata'];
  1540. if ($class->discriminatorColumn) {
  1541. $discrClass = $this->em->getClassMetadata($class->rootEntityName);
  1542. }
  1543. if ($this->useSqlTableAliases) {
  1544. $sql .= $this->getSQLTableAlias($discrClass->getTableName(), $dqlAlias) . '.';
  1545. }
  1546. $sql .= $class->discriminatorColumn['name'] . ($instanceOfExpr->not ? ' NOT IN ' : ' IN ');
  1547. $sqlParameterList = array();
  1548. foreach ($instanceOfExpr->value as $parameter) {
  1549. if ($parameter instanceof AST\InputParameter) {
  1550. // We need to modify the parameter value to be its correspondent mapped value
  1551. $dqlParamKey = $parameter->name;
  1552. $dqlParam = $this->query->getParameter($dqlParamKey);
  1553. $paramValue = $this->query->processParameterValue($dqlParam->getValue());
  1554. if ( ! ($paramValue instanceof \Doctrine\ORM\Mapping\ClassMetadata)) {
  1555. throw QueryException::invalidParameterType('ClassMetadata', get_class($paramValue));
  1556. }
  1557. $entityClassName = $paramValue->name;
  1558. } else {
  1559. // Get name from ClassMetadata to resolve aliases.
  1560. $entityClassName = $this->em->getClassMetadata($parameter)->name;
  1561. }
  1562. if ($entityClassName == $class->name) {
  1563. $sqlParameterList[] = $this->conn->quote($class->discriminatorValue);
  1564. } else {
  1565. $discrMap = array_flip($class->discriminatorMap);
  1566. if (!isset($discrMap[$entityClassName])) {
  1567. throw QueryException::instanceOfUnrelatedClass($entityClassName, $class->rootEntityName);
  1568. }
  1569. $sqlParameterList[] = $this->conn->quote($discrMap[$entityClassName]);
  1570. }
  1571. }
  1572. $sql .= '(' . implode(', ', $sqlParameterList) . ')';
  1573. return $sql;
  1574. }
  1575. /**
  1576. * Walks down an InParameter AST node, thereby generating the appropriate SQL.
  1577. *
  1578. * @param InParameter
  1579. * @return string The SQL.
  1580. */
  1581. public function walkInParameter($inParam)
  1582. {
  1583. return $inParam instanceof AST\InputParameter
  1584. ? $this->walkInputParameter($inParam)
  1585. : $this->walkLiteral($inParam);
  1586. }
  1587. /**
  1588. * Walks down a literal that represents an AST node, thereby generating the appropriate SQL.
  1589. *
  1590. * @param mixed
  1591. * @return string The SQL.
  1592. */
  1593. public function walkLiteral($literal)
  1594. {
  1595. switch ($literal->type) {
  1596. case AST\Literal::STRING:
  1597. return $this->conn->quote($literal->value);
  1598. case AST\Literal::BOOLEAN:
  1599. $bool = strtolower($literal->value) == 'true' ? true : false;
  1600. $boolVal = $this->conn->getDatabasePlatform()->convertBooleans($bool);
  1601. return $boolVal;
  1602. case AST\Literal::NUMERIC:
  1603. return $literal->value;
  1604. default:
  1605. throw QueryException::invalidLiteral($literal);
  1606. }
  1607. }
  1608. /**
  1609. * Walks down a BetweenExpression AST node, thereby generating the appropriate SQL.
  1610. *
  1611. * @param BetweenExpression
  1612. * @return string The SQL.
  1613. */
  1614. public function walkBetweenExpression($betweenExpr)
  1615. {
  1616. $sql = $this->walkArithmeticExpression($betweenExpr->expression);
  1617. if ($betweenExpr->not) $sql .= ' NOT';
  1618. $sql .= ' BETWEEN ' . $this->walkArithmeticExpression($betweenExpr->leftBetweenExpression)
  1619. . ' AND ' . $this->walkArithmeticExpression($betweenExpr->rightBetweenExpression);
  1620. return $sql;
  1621. }
  1622. /**
  1623. * Walks down a LikeExpression AST node, thereby generating the appropriate SQL.
  1624. *
  1625. * @param LikeExpression
  1626. * @return string The SQL.
  1627. */
  1628. public function walkLikeExpression($likeExpr)
  1629. {
  1630. $stringExpr = $likeExpr->stringExpression;
  1631. $sql = $stringExpr->dispatch($this) . ($likeExpr->not ? ' NOT' : '') . ' LIKE ';
  1632. if ($likeExpr->stringPattern instanceof AST\InputParameter) {
  1633. $inputParam = $likeExpr->stringPattern;
  1634. $dqlParamKey = $inputParam->name;
  1635. $this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++);
  1636. $sql .= '?';
  1637. } elseif ($likeExpr->stringPattern instanceof AST\Functions\FunctionNode ) {
  1638. $sql .= $this->walkFunction($likeExpr->stringPattern);
  1639. } elseif ($likeExpr->stringPattern instanceof AST\PathExpression) {
  1640. $sql .= $this->walkPathExpression($likeExpr->stringPattern);
  1641. } else {
  1642. $sql .= $this->walkLiteral($likeExpr->stringPattern);
  1643. }
  1644. if ($likeExpr->escapeChar) {
  1645. $sql .= ' ESCAPE ' . $this->walkLiteral($likeExpr->escapeChar);
  1646. }
  1647. return $sql;
  1648. }
  1649. /**
  1650. * Walks down a StateFieldPathExpression AST node, thereby generating the appropriate SQL.
  1651. *
  1652. * @param StateFieldPathExpression
  1653. * @return string The SQL.
  1654. */
  1655. public function walkStateFieldPathExpression($stateFieldPathExpression)
  1656. {
  1657. return $this->walkPathExpression($stateFieldPathExpression);
  1658. }
  1659. /**
  1660. * Walks down a ComparisonExpression AST node, thereby generating the appropriate SQL.
  1661. *
  1662. * @param ComparisonExpression
  1663. * @return string The SQL.
  1664. */
  1665. public function walkComparisonExpression($compExpr)
  1666. {
  1667. $leftExpr = $compExpr->leftExpression;
  1668. $rightExpr = $compExpr->rightExpression;
  1669. $sql = '';
  1670. $sql .= ($leftExpr instanceof AST\Node)
  1671. ? $leftExpr->dispatch($this)
  1672. : (is_numeric($leftExpr) ? $leftExpr : $this->conn->quote($leftExpr));
  1673. $sql .= ' ' . $compExpr->operator . ' ';
  1674. $sql .= ($rightExpr instanceof AST\Node)
  1675. ? $rightExpr->dispatch($this)
  1676. : (is_numeric($rightExpr) ? $rightExpr : $this->conn->quote($rightExpr));
  1677. return $sql;
  1678. }
  1679. /**
  1680. * Walks down an InputParameter AST node, thereby generating the appropriate SQL.
  1681. *
  1682. * @param InputParameter
  1683. * @return string The SQL.
  1684. */
  1685. public function walkInputParameter($inputParam)
  1686. {
  1687. $this->parserResult->addParameterMapping($inputParam->name, $this->sqlParamIndex++);
  1688. return '?';
  1689. }
  1690. /**
  1691. * Walks down an ArithmeticExpression AST node, thereby generating the appropriate SQL.
  1692. *
  1693. * @param ArithmeticExpression
  1694. * @return string The SQL.
  1695. */
  1696. public function walkArithmeticExpression($arithmeticExpr)
  1697. {
  1698. return ($arithmeticExpr->isSimpleArithmeticExpression())
  1699. ? $this->walkSimpleArithmeticExpression($arithmeticExpr->simpleArithmeticExpression)
  1700. : '(' . $this->walkSubselect($arithmeticExpr->subselect) . ')';
  1701. }
  1702. /**
  1703. * Walks down an SimpleArithmeticExpression AST node, thereby generating the appropriate SQL.
  1704. *
  1705. * @param SimpleArithmeticExpression
  1706. * @return string The SQL.
  1707. */
  1708. public function walkSimpleArithmeticExpression($simpleArithmeticExpr)
  1709. {
  1710. if ( ! ($simpleArithmeticExpr instanceof AST\SimpleArithmeticExpression)) {
  1711. return $this->walkArithmeticTerm($simpleArithmeticExpr);
  1712. }
  1713. return implode(' ', array_map(array($this, 'walkArithmeticTerm'), $simpleArithmeticExpr->arithmeticTerms));
  1714. }
  1715. /**
  1716. * Walks down an ArithmeticTerm AST node, thereby generating the appropriate SQL.
  1717. *
  1718. * @param mixed
  1719. * @return string The SQL.
  1720. */
  1721. public function walkArithmeticTerm($term)
  1722. {
  1723. if (is_string($term)) {
  1724. return (isset($this->queryComponents[$term]))
  1725. ? $this->walkResultVariable($this->queryComponents[$term]['token']['value'])
  1726. : $term;
  1727. }
  1728. // Phase 2 AST optimization: Skip processment of ArithmeticTerm
  1729. // if only one ArithmeticFactor is defined
  1730. if ( ! ($term instanceof AST\ArithmeticTerm)) {
  1731. return $this->walkArithmeticFactor($term);
  1732. }
  1733. return implode(' ', array_map(array($this, 'walkArithmeticFactor'), $term->arithmeticFactors));
  1734. }
  1735. /**
  1736. * Walks down an ArithmeticFactor that represents an AST node, thereby generating the appropriate SQL.
  1737. *
  1738. * @param mixed
  1739. * @return string The SQL.
  1740. */
  1741. public function walkArithmeticFactor($factor)
  1742. {
  1743. if (is_string($factor)) {
  1744. return $factor;
  1745. }
  1746. // Phase 2 AST optimization: Skip processment of ArithmeticFactor
  1747. // if only one ArithmeticPrimary is defined
  1748. if ( ! ($factor instanceof AST\ArithmeticFactor)) {
  1749. return $this->walkArithmeticPrimary($factor);
  1750. }
  1751. $sign = $factor->isNegativeSigned() ? '-' : ($factor->isPositiveSigned() ? '+' : '');
  1752. return $sign . $this->walkArithmeticPrimary($factor->arithmeticPrimary);
  1753. }
  1754. /**
  1755. * Walks down an ArithmeticPrimary that represents an AST node, thereby generating the appropriate SQL.
  1756. *
  1757. * @param mixed
  1758. * @return string The SQL.
  1759. */
  1760. public function walkArithmeticPrimary($primary)
  1761. {
  1762. if ($primary instanceof AST\SimpleArithmeticExpression) {
  1763. return '(' . $this->walkSimpleArithmeticExpression($primary) . ')';
  1764. }
  1765. if ($primary instanceof AST\Node) {
  1766. return $primary->dispatch($this);
  1767. }
  1768. return $this->walkEntityIdentificationVariable($primary);
  1769. }
  1770. /**
  1771. * Walks down a StringPrimary that represents an AST node, thereby generating the appropriate SQL.
  1772. *
  1773. * @param mixed
  1774. * @return string The SQL.
  1775. */
  1776. public function walkStringPrimary($stringPrimary)
  1777. {
  1778. return (is_string($stringPrimary))
  1779. ? $this->conn->quote($stringPrimary)
  1780. : $stringPrimary->dispatch($this);
  1781. }
  1782. /**
  1783. * Walks down a ResultVriable that represents an AST node, thereby generating the appropriate SQL.
  1784. *
  1785. * @param string $resultVariable
  1786. * @return string The SQL.
  1787. */
  1788. public function walkResultVariable($resultVariable)
  1789. {
  1790. $resultAlias = $this->scalarResultAliasMap[$resultVariable];
  1791. if (is_array($resultAlias)) {
  1792. return implode(', ', $resultAlias);
  1793. }
  1794. return $resultAlias;
  1795. }
  1796. }