PageRenderTime 29ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/chives/doctrine2
PHP | 2306 lines | 1273 code | 426 blank | 607 comment | 151 complexity | 05c6614576dbae890645cf47497d251f MD5 | raw 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. * Counters for generating unique column aliases.
  50. *
  51. * @var integer
  52. */
  53. private $aliasCounter = 0;
  54. /**
  55. * Counters for generating unique table aliases.
  56. *
  57. * @var integer
  58. */
  59. private $tableAliasCounter = 0;
  60. /**
  61. * Counters for generating unique scalar result.
  62. *
  63. * @var integer
  64. */
  65. private $scalarResultCounter = 1;
  66. /**
  67. * Counters for generating unique parameter indexes.
  68. *
  69. * @var integer
  70. */
  71. private $sqlParamIndex = 0;
  72. /**
  73. * Counters for generating indexes.
  74. *
  75. * @var integer
  76. */
  77. private $newObjectCounter = 0;
  78. /**
  79. * @var ParserResult
  80. */
  81. private $parserResult;
  82. /**
  83. * @var EntityManager
  84. */
  85. private $em;
  86. /**
  87. * @var \Doctrine\DBAL\Connection
  88. */
  89. private $conn;
  90. /**
  91. * @var 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 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 Connection
  174. */
  175. public function getConnection()
  176. {
  177. return $this->conn;
  178. }
  179. /**
  180. * Gets the EntityManager used by the walker.
  181. *
  182. * @return 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. * @return array
  193. */
  194. public function getQueryComponent($dqlAlias)
  195. {
  196. return $this->queryComponents[$dqlAlias];
  197. }
  198. /**
  199. * Return internal queryComponents array
  200. *
  201. * @return array
  202. */
  203. public function getQueryComponents()
  204. {
  205. return $this->queryComponents;
  206. }
  207. /**
  208. * Set or override a query component for a given dql alias.
  209. *
  210. * @param string $dqlAlias The DQL alias.
  211. * @param array $queryComponent
  212. */
  213. public function setQueryComponent($dqlAlias, array $queryComponent)
  214. {
  215. $requiredKeys = array('metadata', 'parent', 'relation', 'map', 'nestingLevel', 'token');
  216. if (array_diff($requiredKeys, array_keys($queryComponent))) {
  217. throw QueryException::invalidQueryComponent($dqlAlias);
  218. }
  219. $this->queryComponents[$dqlAlias] = $queryComponent;
  220. }
  221. /**
  222. * Gets an executor that can be used to execute the result of this walker.
  223. *
  224. * @return AbstractExecutor
  225. */
  226. public function getExecutor($AST)
  227. {
  228. switch (true) {
  229. case ($AST instanceof AST\DeleteStatement):
  230. $primaryClass = $this->em->getClassMetadata($AST->deleteClause->abstractSchemaName);
  231. return ($primaryClass->isInheritanceTypeJoined())
  232. ? new Exec\MultiTableDeleteExecutor($AST, $this)
  233. : new Exec\SingleTableDeleteUpdateExecutor($AST, $this);
  234. case ($AST instanceof AST\UpdateStatement):
  235. $primaryClass = $this->em->getClassMetadata($AST->updateClause->abstractSchemaName);
  236. return ($primaryClass->isInheritanceTypeJoined())
  237. ? new Exec\MultiTableUpdateExecutor($AST, $this)
  238. : new Exec\SingleTableDeleteUpdateExecutor($AST, $this);
  239. default:
  240. return new Exec\SingleSelectExecutor($AST, $this);
  241. }
  242. }
  243. /**
  244. * Generates a unique, short SQL table alias.
  245. *
  246. * @param string $tableName Table name
  247. * @param string $dqlAlias The DQL alias.
  248. * @return string Generated table alias.
  249. */
  250. public function getSQLTableAlias($tableName, $dqlAlias = '')
  251. {
  252. $tableName .= ($dqlAlias) ? '@[' . $dqlAlias . ']' : '';
  253. if ( ! isset($this->tableAliasMap[$tableName])) {
  254. $this->tableAliasMap[$tableName] = strtolower(substr($tableName, 0, 1)) . $this->tableAliasCounter++ . '_';
  255. }
  256. return $this->tableAliasMap[$tableName];
  257. }
  258. /**
  259. * Forces the SqlWalker to use a specific alias for a table name, rather than
  260. * generating an alias on its own.
  261. *
  262. * @param string $tableName
  263. * @param string $alias
  264. * @param string $dqlAlias
  265. * @return string
  266. */
  267. public function setSQLTableAlias($tableName, $alias, $dqlAlias = '')
  268. {
  269. $tableName .= ($dqlAlias) ? '@[' . $dqlAlias . ']' : '';
  270. $this->tableAliasMap[$tableName] = $alias;
  271. return $alias;
  272. }
  273. /**
  274. * Gets an SQL column alias for a column name.
  275. *
  276. * @param string $columnName
  277. * @return string
  278. */
  279. public function getSQLColumnAlias($columnName)
  280. {
  281. return $this->quoteStrategy->getColumnAlias($columnName, $this->aliasCounter++, $this->platform);
  282. }
  283. /**
  284. * Generates the SQL JOINs that are necessary for Class Table Inheritance
  285. * for the given class.
  286. *
  287. * @param ClassMetadata $class The class for which to generate the joins.
  288. * @param string $dqlAlias The DQL alias of the class.
  289. * @return string The SQL.
  290. */
  291. private function _generateClassTableInheritanceJoins($class, $dqlAlias)
  292. {
  293. $sql = '';
  294. $baseTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
  295. // INNER JOIN parent class tables
  296. foreach ($class->parentClasses as $parentClassName) {
  297. $parentClass = $this->em->getClassMetadata($parentClassName);
  298. $tableAlias = $this->getSQLTableAlias($parentClass->getTableName(), $dqlAlias);
  299. // If this is a joined association we must use left joins to preserve the correct result.
  300. $sql .= isset($this->queryComponents[$dqlAlias]['relation']) ? ' LEFT ' : ' INNER ';
  301. $sql .= 'JOIN ' . $this->quoteStrategy->getTableName($parentClass, $this->platform) . ' ' . $tableAlias . ' ON ';
  302. $sqlParts = array();
  303. foreach ($this->quoteStrategy->getIdentifierColumnNames($class, $this->platform) as $columnName) {
  304. $sqlParts[] = $baseTableAlias . '.' . $columnName . ' = ' . $tableAlias . '.' . $columnName;
  305. }
  306. // Add filters on the root class
  307. if ($filterSql = $this->generateFilterConditionSQL($parentClass, $tableAlias)) {
  308. $sqlParts[] = $filterSql;
  309. }
  310. $sql .= implode(' AND ', $sqlParts);
  311. }
  312. // Ignore subclassing inclusion if partial objects is disallowed
  313. if ($this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD)) {
  314. return $sql;
  315. }
  316. // LEFT JOIN child class tables
  317. foreach ($class->subClasses as $subClassName) {
  318. $subClass = $this->em->getClassMetadata($subClassName);
  319. $tableAlias = $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias);
  320. $sql .= ' LEFT JOIN ' . $this->quoteStrategy->getTableName($subClass, $this->platform) . ' ' . $tableAlias . ' ON ';
  321. $sqlParts = array();
  322. foreach ($this->quoteStrategy->getIdentifierColumnNames($subClass, $this->platform) as $columnName) {
  323. $sqlParts[] = $baseTableAlias . '.' . $columnName . ' = ' . $tableAlias . '.' . $columnName;
  324. }
  325. $sql .= implode(' AND ', $sqlParts);
  326. }
  327. return $sql;
  328. }
  329. private function _generateOrderedCollectionOrderByItems()
  330. {
  331. $sqlParts = array();
  332. foreach ($this->selectedClasses as $selectedClass) {
  333. $dqlAlias = $selectedClass['dqlAlias'];
  334. $qComp = $this->queryComponents[$dqlAlias];
  335. if ( ! isset($qComp['relation']['orderBy'])) continue;
  336. foreach ($qComp['relation']['orderBy'] as $fieldName => $orientation) {
  337. $columnName = $this->quoteStrategy->getColumnName($fieldName, $qComp['metadata'], $this->platform);
  338. $tableName = ($qComp['metadata']->isInheritanceTypeJoined())
  339. ? $this->em->getUnitOfWork()->getEntityPersister($qComp['metadata']->name)->getOwningTable($fieldName)
  340. : $qComp['metadata']->getTableName();
  341. $sqlParts[] = $this->getSQLTableAlias($tableName, $dqlAlias) . '.' . $columnName . ' ' . $orientation;
  342. }
  343. }
  344. return implode(', ', $sqlParts);
  345. }
  346. /**
  347. * Generates a discriminator column SQL condition for the class with the given DQL alias.
  348. *
  349. * @param array $dqlAliases List of root DQL aliases to inspect for discriminator restrictions.
  350. * @return string
  351. */
  352. private function _generateDiscriminatorColumnConditionSQL(array $dqlAliases)
  353. {
  354. $sqlParts = array();
  355. foreach ($dqlAliases as $dqlAlias) {
  356. $class = $this->queryComponents[$dqlAlias]['metadata'];
  357. if ( ! $class->isInheritanceTypeSingleTable()) continue;
  358. $conn = $this->em->getConnection();
  359. $values = array();
  360. if ($class->discriminatorValue !== null) { // discrimnators can be 0
  361. $values[] = $conn->quote($class->discriminatorValue);
  362. }
  363. foreach ($class->subClasses as $subclassName) {
  364. $values[] = $conn->quote($this->em->getClassMetadata($subclassName)->discriminatorValue);
  365. }
  366. $sqlParts[] = (($this->useSqlTableAliases) ? $this->getSQLTableAlias($class->getTableName(), $dqlAlias) . '.' : '')
  367. . $class->discriminatorColumn['name'] . ' IN (' . implode(', ', $values) . ')';
  368. }
  369. $sql = implode(' AND ', $sqlParts);
  370. return (count($sqlParts) > 1) ? '(' . $sql . ')' : $sql;
  371. }
  372. /**
  373. * Generates the filter SQL for a given entity and table alias.
  374. *
  375. * @param ClassMetadata $targetEntity Metadata of the target entity.
  376. * @param string $targetTableAlias The table alias of the joined/selected table.
  377. *
  378. * @return string The SQL query part to add to a query.
  379. */
  380. private function generateFilterConditionSQL(ClassMetadata $targetEntity, $targetTableAlias)
  381. {
  382. if (!$this->em->hasFilters()) {
  383. return '';
  384. }
  385. switch($targetEntity->inheritanceType) {
  386. case ClassMetadata::INHERITANCE_TYPE_NONE:
  387. break;
  388. case ClassMetadata::INHERITANCE_TYPE_JOINED:
  389. // The classes in the inheritance will be added to the query one by one,
  390. // but only the root node is getting filtered
  391. if ($targetEntity->name !== $targetEntity->rootEntityName) {
  392. return '';
  393. }
  394. break;
  395. case ClassMetadata::INHERITANCE_TYPE_SINGLE_TABLE:
  396. // With STI the table will only be queried once, make sure that the filters
  397. // are added to the root entity
  398. $targetEntity = $this->em->getClassMetadata($targetEntity->rootEntityName);
  399. break;
  400. default:
  401. //@todo: throw exception?
  402. return '';
  403. break;
  404. }
  405. $filterClauses = array();
  406. foreach ($this->em->getFilters()->getEnabledFilters() as $filter) {
  407. if ('' !== $filterExpr = $filter->addFilterConstraint($targetEntity, $targetTableAlias)) {
  408. $filterClauses[] = '(' . $filterExpr . ')';
  409. }
  410. }
  411. return implode(' AND ', $filterClauses);
  412. }
  413. /**
  414. * Walks down a SelectStatement AST node, thereby generating the appropriate SQL.
  415. *
  416. * @return string The SQL.
  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. * Walks down an UpdateStatement AST node, thereby generating the appropriate SQL.
  458. *
  459. * @param UpdateStatement
  460. * @return string The SQL.
  461. */
  462. public function walkUpdateStatement(AST\UpdateStatement $AST)
  463. {
  464. $this->useSqlTableAliases = false;
  465. return $this->walkUpdateClause($AST->updateClause)
  466. . $this->walkWhereClause($AST->whereClause);
  467. }
  468. /**
  469. * Walks down a DeleteStatement AST node, thereby generating the appropriate SQL.
  470. *
  471. * @param DeleteStatement
  472. * @return string The SQL.
  473. */
  474. public function walkDeleteStatement(AST\DeleteStatement $AST)
  475. {
  476. $this->useSqlTableAliases = false;
  477. return $this->walkDeleteClause($AST->deleteClause)
  478. . $this->walkWhereClause($AST->whereClause);
  479. }
  480. /**
  481. * Walks down an IdentificationVariable AST node, thereby generating the appropriate SQL.
  482. * This one differs of ->walkIdentificationVariable() because it generates the entity identifiers.
  483. *
  484. * @param string $identVariable
  485. * @return string
  486. */
  487. public function walkEntityIdentificationVariable($identVariable)
  488. {
  489. $class = $this->queryComponents[$identVariable]['metadata'];
  490. $tableAlias = $this->getSQLTableAlias($class->getTableName(), $identVariable);
  491. $sqlParts = array();
  492. foreach ($this->quoteStrategy->getIdentifierColumnNames($class, $this->platform) as $columnName) {
  493. $sqlParts[] = $tableAlias . '.' . $columnName;
  494. }
  495. return implode(', ', $sqlParts);
  496. }
  497. /**
  498. * Walks down an IdentificationVariable (no AST node associated), thereby generating the SQL.
  499. *
  500. * @param string $identificationVariable
  501. * @param string $fieldName
  502. * @return string The SQL.
  503. */
  504. public function walkIdentificationVariable($identificationVariable, $fieldName = null)
  505. {
  506. $class = $this->queryComponents[$identificationVariable]['metadata'];
  507. if (
  508. $fieldName !== null && $class->isInheritanceTypeJoined() &&
  509. isset($class->fieldMappings[$fieldName]['inherited'])
  510. ) {
  511. $class = $this->em->getClassMetadata($class->fieldMappings[$fieldName]['inherited']);
  512. }
  513. return $this->getSQLTableAlias($class->getTableName(), $identificationVariable);
  514. }
  515. /**
  516. * Walks down a PathExpression AST node, thereby generating the appropriate SQL.
  517. *
  518. * @param mixed
  519. * @return string The SQL.
  520. */
  521. public function walkPathExpression($pathExpr)
  522. {
  523. $sql = '';
  524. switch ($pathExpr->type) {
  525. case AST\PathExpression::TYPE_STATE_FIELD:
  526. $fieldName = $pathExpr->field;
  527. $dqlAlias = $pathExpr->identificationVariable;
  528. $class = $this->queryComponents[$dqlAlias]['metadata'];
  529. if ($this->useSqlTableAliases) {
  530. $sql .= $this->walkIdentificationVariable($dqlAlias, $fieldName) . '.';
  531. }
  532. $sql .= $this->quoteStrategy->getColumnName($fieldName, $class, $this->platform);
  533. break;
  534. case AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION:
  535. // 1- the owning side:
  536. // Just use the foreign key, i.e. u.group_id
  537. $fieldName = $pathExpr->field;
  538. $dqlAlias = $pathExpr->identificationVariable;
  539. $class = $this->queryComponents[$dqlAlias]['metadata'];
  540. if (isset($class->associationMappings[$fieldName]['inherited'])) {
  541. $class = $this->em->getClassMetadata($class->associationMappings[$fieldName]['inherited']);
  542. }
  543. $assoc = $class->associationMappings[$fieldName];
  544. if ( ! $assoc['isOwningSide']) {
  545. throw QueryException::associationPathInverseSideNotSupported();
  546. }
  547. // COMPOSITE KEYS NOT (YET?) SUPPORTED
  548. if (count($assoc['sourceToTargetKeyColumns']) > 1) {
  549. throw QueryException::associationPathCompositeKeyNotSupported();
  550. }
  551. if ($this->useSqlTableAliases) {
  552. $sql .= $this->getSQLTableAlias($class->getTableName(), $dqlAlias) . '.';
  553. }
  554. $sql .= reset($assoc['targetToSourceKeyColumns']);
  555. break;
  556. default:
  557. throw QueryException::invalidPathExpression($pathExpr);
  558. }
  559. return $sql;
  560. }
  561. /**
  562. * Walks down a SelectClause AST node, thereby generating the appropriate SQL.
  563. *
  564. * @param $selectClause
  565. * @return string The SQL.
  566. */
  567. public function walkSelectClause($selectClause)
  568. {
  569. $sql = 'SELECT ' . (($selectClause->isDistinct) ? 'DISTINCT ' : '');
  570. $sqlSelectExpressions = array_filter(array_map(array($this, 'walkSelectExpression'), $selectClause->selectExpressions));
  571. if ($this->query->getHint(Query::HINT_INTERNAL_ITERATION) == true && $selectClause->isDistinct) {
  572. $this->query->setHint(self::HINT_DISTINCT, true);
  573. }
  574. $addMetaColumns = ! $this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD) &&
  575. $this->query->getHydrationMode() == Query::HYDRATE_OBJECT
  576. ||
  577. $this->query->getHydrationMode() != Query::HYDRATE_OBJECT &&
  578. $this->query->getHint(Query::HINT_INCLUDE_META_COLUMNS);
  579. foreach ($this->selectedClasses as $selectedClass) {
  580. $class = $selectedClass['class'];
  581. $dqlAlias = $selectedClass['dqlAlias'];
  582. $resultAlias = $selectedClass['resultAlias'];
  583. // Register as entity or joined entity result
  584. if ($this->queryComponents[$dqlAlias]['relation'] === null) {
  585. $this->rsm->addEntityResult($class->name, $dqlAlias, $resultAlias);
  586. } else {
  587. $this->rsm->addJoinedEntityResult(
  588. $class->name,
  589. $dqlAlias,
  590. $this->queryComponents[$dqlAlias]['parent'],
  591. $this->queryComponents[$dqlAlias]['relation']['fieldName']
  592. );
  593. }
  594. if ($class->isInheritanceTypeSingleTable() || $class->isInheritanceTypeJoined()) {
  595. // Add discriminator columns to SQL
  596. $rootClass = $this->em->getClassMetadata($class->rootEntityName);
  597. $tblAlias = $this->getSQLTableAlias($rootClass->getTableName(), $dqlAlias);
  598. $discrColumn = $rootClass->discriminatorColumn;
  599. $columnAlias = $this->getSQLColumnAlias($discrColumn['name']);
  600. $sqlSelectExpressions[] = $tblAlias . '.' . $discrColumn['name'] . ' AS ' . $columnAlias;
  601. $this->rsm->setDiscriminatorColumn($dqlAlias, $columnAlias);
  602. $this->rsm->addMetaResult($dqlAlias, $columnAlias, $discrColumn['fieldName']);
  603. }
  604. // Add foreign key columns to SQL, if necessary
  605. if ( ! $addMetaColumns && ! $class->containsForeignIdentifier) {
  606. continue;
  607. }
  608. // Add foreign key columns of class and also parent classes
  609. foreach ($class->associationMappings as $assoc) {
  610. if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) {
  611. continue;
  612. } else if ( !$addMetaColumns && !isset($assoc['id'])) {
  613. continue;
  614. }
  615. $owningClass = (isset($assoc['inherited'])) ? $this->em->getClassMetadata($assoc['inherited']) : $class;
  616. $sqlTableAlias = $this->getSQLTableAlias($owningClass->getTableName(), $dqlAlias);
  617. foreach ($assoc['targetToSourceKeyColumns'] as $srcColumn) {
  618. $columnAlias = $this->getSQLColumnAlias($srcColumn);
  619. $sqlSelectExpressions[] = $sqlTableAlias . '.' . $srcColumn . ' AS ' . $columnAlias;
  620. $this->rsm->addMetaResult($dqlAlias, $columnAlias, $srcColumn, (isset($assoc['id']) && $assoc['id'] === true));
  621. }
  622. }
  623. // Add foreign key columns to SQL, if necessary
  624. if ( ! $addMetaColumns) {
  625. continue;
  626. }
  627. // Add foreign key columns of subclasses
  628. foreach ($class->subClasses as $subClassName) {
  629. $subClass = $this->em->getClassMetadata($subClassName);
  630. $sqlTableAlias = $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias);
  631. foreach ($subClass->associationMappings as $assoc) {
  632. // Skip if association is inherited
  633. if (isset($assoc['inherited'])) continue;
  634. if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) continue;
  635. foreach ($assoc['targetToSourceKeyColumns'] as $srcColumn) {
  636. $columnAlias = $this->getSQLColumnAlias($srcColumn);
  637. $sqlSelectExpressions[] = $sqlTableAlias . '.' . $srcColumn . ' AS ' . $columnAlias;
  638. $this->rsm->addMetaResult($dqlAlias, $columnAlias, $srcColumn);
  639. }
  640. }
  641. }
  642. }
  643. $sql .= implode(', ', $sqlSelectExpressions);
  644. return $sql;
  645. }
  646. /**
  647. * Walks down a FromClause AST node, thereby generating the appropriate SQL.
  648. *
  649. * @return string The SQL.
  650. */
  651. public function walkFromClause($fromClause)
  652. {
  653. $identificationVarDecls = $fromClause->identificationVariableDeclarations;
  654. $sqlParts = array();
  655. foreach ($identificationVarDecls as $identificationVariableDecl) {
  656. $sql = $this->walkRangeVariableDeclaration($identificationVariableDecl->rangeVariableDeclaration);
  657. foreach ($identificationVariableDecl->joins as $join) {
  658. $sql .= $this->walkJoin($join);
  659. }
  660. if ($identificationVariableDecl->indexBy) {
  661. $alias = $identificationVariableDecl->indexBy->simpleStateFieldPathExpression->identificationVariable;
  662. $field = $identificationVariableDecl->indexBy->simpleStateFieldPathExpression->field;
  663. if (isset($this->scalarFields[$alias][$field])) {
  664. $this->rsm->addIndexByScalar($this->scalarFields[$alias][$field]);
  665. } else {
  666. $this->rsm->addIndexBy(
  667. $identificationVariableDecl->indexBy->simpleStateFieldPathExpression->identificationVariable,
  668. $identificationVariableDecl->indexBy->simpleStateFieldPathExpression->field
  669. );
  670. }
  671. }
  672. $sqlParts[] = $this->platform->appendLockHint($sql, $this->query->getHint(Query::HINT_LOCK_MODE));
  673. }
  674. return ' FROM ' . implode(', ', $sqlParts);
  675. }
  676. /**
  677. * Walks down a RangeVariableDeclaration AST node, thereby generating the appropriate SQL.
  678. *
  679. * @return string
  680. */
  681. public function walkRangeVariableDeclaration($rangeVariableDeclaration)
  682. {
  683. $class = $this->em->getClassMetadata($rangeVariableDeclaration->abstractSchemaName);
  684. $dqlAlias = $rangeVariableDeclaration->aliasIdentificationVariable;
  685. $this->rootAliases[] = $dqlAlias;
  686. $sql = $class->getQuotedTableName($this->platform) . ' '
  687. . $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
  688. if ($class->isInheritanceTypeJoined()) {
  689. $sql .= $this->_generateClassTableInheritanceJoins($class, $dqlAlias);
  690. }
  691. return $sql;
  692. }
  693. /**
  694. * Walks down a JoinAssociationDeclaration AST node, thereby generating the appropriate SQL.
  695. *
  696. * @return string
  697. */
  698. public function walkJoinAssociationDeclaration($joinAssociationDeclaration, $joinType = AST\Join::JOIN_TYPE_INNER)
  699. {
  700. $sql = '';
  701. $associationPathExpression = $joinAssociationDeclaration->joinAssociationPathExpression;
  702. $joinedDqlAlias = $joinAssociationDeclaration->aliasIdentificationVariable;
  703. $indexBy = $joinAssociationDeclaration->indexBy;
  704. $relation = $this->queryComponents[$joinedDqlAlias]['relation'];
  705. $targetClass = $this->em->getClassMetadata($relation['targetEntity']);
  706. $sourceClass = $this->em->getClassMetadata($relation['sourceEntity']);
  707. $targetTableName = $targetClass->getQuotedTableName($this->platform);
  708. $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName(), $joinedDqlAlias);
  709. $sourceTableAlias = $this->getSQLTableAlias($sourceClass->getTableName(), $associationPathExpression->identificationVariable);
  710. // Ensure we got the owning side, since it has all mapping info
  711. $assoc = ( ! $relation['isOwningSide']) ? $targetClass->associationMappings[$relation['mappedBy']] : $relation;
  712. if ($this->query->getHint(Query::HINT_INTERNAL_ITERATION) == true && (!$this->query->getHint(self::HINT_DISTINCT) || isset($this->selectedClasses[$joinedDqlAlias]))) {
  713. if ($relation['type'] == ClassMetadata::ONE_TO_MANY || $relation['type'] == ClassMetadata::MANY_TO_MANY) {
  714. throw QueryException::iterateWithFetchJoinNotAllowed($assoc);
  715. }
  716. }
  717. // This condition is not checking ClassMetadata::MANY_TO_ONE, because by definition it cannot
  718. // be the owning side and previously we ensured that $assoc is always the owning side of the associations.
  719. // The owning side is necessary at this point because only it contains the JoinColumn information.
  720. switch (true) {
  721. case ($assoc['type'] & ClassMetadata::TO_ONE):
  722. $conditions = array();
  723. foreach ($assoc['joinColumns'] as $joinColumn) {
  724. $quotedSourceColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform);
  725. $quotedTargetColumn = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $targetClass, $this->platform);
  726. if ($relation['isOwningSide']) {
  727. $conditions[] = $sourceTableAlias . '.' . $quotedSourceColumn . ' = ' . $targetTableAlias . '.' . $quotedTargetColumn;
  728. continue;
  729. }
  730. $conditions[] = $sourceTableAlias . '.' . $quotedTargetColumn . ' = ' . $targetTableAlias . '.' . $quotedSourceColumn;
  731. }
  732. // Apply remaining inheritance restrictions
  733. $discrSql = $this->_generateDiscriminatorColumnConditionSQL(array($joinedDqlAlias));
  734. if ($discrSql) {
  735. $conditions[] = $discrSql;
  736. }
  737. // Apply the filters
  738. $filterExpr = $this->generateFilterConditionSQL($targetClass, $targetTableAlias);
  739. if ($filterExpr) {
  740. $conditions[] = $filterExpr;
  741. }
  742. $sql .= $targetTableName . ' ' . $targetTableAlias . ' ON ' . implode(' AND ', $conditions);
  743. break;
  744. case ($assoc['type'] == ClassMetadata::MANY_TO_MANY):
  745. // Join relation table
  746. $joinTable = $assoc['joinTable'];
  747. $joinTableAlias = $this->getSQLTableAlias($joinTable['name'], $joinedDqlAlias);
  748. $joinTableName = $sourceClass->getQuotedJoinTableName($assoc, $this->platform);
  749. $conditions = array();
  750. $relationColumns = ($relation['isOwningSide'])
  751. ? $assoc['joinTable']['joinColumns']
  752. : $assoc['joinTable']['inverseJoinColumns'];
  753. foreach ($relationColumns as $joinColumn) {
  754. $quotedSourceColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform);
  755. $quotedTargetColumn = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $targetClass, $this->platform);
  756. $conditions[] = $sourceTableAlias . '.' . $quotedTargetColumn . ' = ' . $joinTableAlias . '.' . $quotedSourceColumn;
  757. }
  758. $sql .= $joinTableName . ' ' . $joinTableAlias . ' ON ' . implode(' AND ', $conditions);
  759. // Join target table
  760. $sql .= ($joinType == AST\Join::JOIN_TYPE_LEFT || $joinType == AST\Join::JOIN_TYPE_LEFTOUTER) ? ' LEFT JOIN ' : ' INNER JOIN ';
  761. $conditions = array();
  762. $relationColumns = ($relation['isOwningSide'])
  763. ? $assoc['joinTable']['inverseJoinColumns']
  764. : $assoc['joinTable']['joinColumns'];
  765. foreach ($relationColumns as $joinColumn) {
  766. $quotedSourceColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform);
  767. $quotedTargetColumn = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $targetClass, $this->platform);
  768. $conditions[] = $targetTableAlias . '.' . $quotedTargetColumn . ' = ' . $joinTableAlias . '.' . $quotedSourceColumn;
  769. }
  770. // Apply remaining inheritance restrictions
  771. $discrSql = $this->_generateDiscriminatorColumnConditionSQL(array($joinedDqlAlias));
  772. if ($discrSql) {
  773. $conditions[] = $discrSql;
  774. }
  775. // Apply the filters
  776. $filterExpr = $this->generateFilterConditionSQL($targetClass, $targetTableAlias);
  777. if ($filterExpr) {
  778. $conditions[] = $filterExpr;
  779. }
  780. $sql .= $targetTableName . ' ' . $targetTableAlias . ' ON ' . implode(' AND ', $conditions);
  781. break;
  782. }
  783. // FIXME: these should either be nested or all forced to be left joins (DDC-XXX)
  784. if ($targetClass->isInheritanceTypeJoined()) {
  785. $sql .= $this->_generateClassTableInheritanceJoins($targetClass, $joinedDqlAlias);
  786. }
  787. // Apply the indexes
  788. if ($indexBy) {
  789. // For Many-To-One or One-To-One associations this obviously makes no sense, but is ignored silently.
  790. $this->rsm->addIndexBy(
  791. $indexBy->simpleStateFieldPathExpression->identificationVariable,
  792. $indexBy->simpleStateFieldPathExpression->field
  793. );
  794. } else if (isset($relation['indexBy'])) {
  795. $this->rsm->addIndexBy($joinedDqlAlias, $relation['indexBy']);
  796. }
  797. return $sql;
  798. }
  799. /**
  800. * Walks down a FunctionNode AST node, thereby generating the appropriate SQL.
  801. *
  802. * @return string The SQL.
  803. */
  804. public function walkFunction($function)
  805. {
  806. return $function->getSql($this);
  807. }
  808. /**
  809. * Walks down an OrderByClause AST node, thereby generating the appropriate SQL.
  810. *
  811. * @param OrderByClause
  812. * @return string The SQL.
  813. */
  814. public function walkOrderByClause($orderByClause)
  815. {
  816. $orderByItems = array_map(array($this, 'walkOrderByItem'), $orderByClause->orderByItems);
  817. if (($collectionOrderByItems = $this->_generateOrderedCollectionOrderByItems()) !== '') {
  818. $orderByItems = array_merge($orderByItems, (array) $collectionOrderByItems);
  819. }
  820. return ' ORDER BY ' . implode(', ', $orderByItems);
  821. }
  822. /**
  823. * Walks down an OrderByItem AST node, thereby generating the appropriate SQL.
  824. *
  825. * @param OrderByItem
  826. * @return string The SQL.
  827. */
  828. public function walkOrderByItem($orderByItem)
  829. {
  830. $expr = $orderByItem->expression;
  831. $sql = ($expr instanceof AST\Node)
  832. ? $expr->dispatch($this)
  833. : $this->walkResultVariable($this->queryComponents[$expr]['token']['value']);
  834. return $sql . ' ' . strtoupper($orderByItem->type);
  835. }
  836. /**
  837. * Walks down a HavingClause AST node, thereby generating the appropriate SQL.
  838. *
  839. * @param HavingClause
  840. * @return string The SQL.
  841. */
  842. public function walkHavingClause($havingClause)
  843. {
  844. return ' HAVING ' . $this->walkConditionalExpression($havingClause->conditionalExpression);
  845. }
  846. /**
  847. * Walks down a Join AST node and creates the corresponding SQL.
  848. *
  849. * @return string The SQL.
  850. */
  851. public function walkJoin($join)
  852. {
  853. $joinType = $join->joinType;
  854. $joinDeclaration = $join->joinAssociationDeclaration;
  855. $sql = ($joinType == AST\Join::JOIN_TYPE_LEFT || $joinType == AST\Join::JOIN_TYPE_LEFTOUTER)
  856. ? ' LEFT JOIN '
  857. : ' INNER JOIN ';
  858. switch (true) {
  859. case ($joinDeclaration instanceof \Doctrine\ORM\Query\AST\RangeVariableDeclaration):
  860. $class = $this->em->getClassMetadata($joinDeclaration->abstractSchemaName);
  861. $condExprConjunction = $class->isInheritanceTypeJoined() && $joinType != AST\Join::JOIN_TYPE_LEFT && $joinType != AST\Join::JOIN_TYPE_LEFTOUTER
  862. ? ' AND '
  863. : ' ON ';
  864. $sql .= $this->walkRangeVariableDeclaration($joinDeclaration)
  865. . $condExprConjunction . '(' . $this->walkConditionalExpression($join->conditionalExpression) . ')';
  866. break;
  867. case ($joinDeclaration instanceof \Doctrine\ORM\Query\AST\JoinAssociationDeclaration):
  868. $sql .= $this->walkJoinAssociationDeclaration($joinDeclaration, $joinType);
  869. // Handle WITH clause
  870. if (($condExpr = $join->conditionalExpression) !== null) {
  871. // Phase 2 AST optimization: Skip processment of ConditionalExpression
  872. // if only one ConditionalTerm is defined
  873. $sql .= ' AND (' . $this->walkConditionalExpression($condExpr) . ')';
  874. }
  875. break;
  876. }
  877. return $sql;
  878. }
  879. /**
  880. * Walks down a CaseExpression AST node and generates the corresponding SQL.
  881. *
  882. * @param CoalesceExpression|NullIfExpression|GeneralCaseExpression|SimpleCaseExpression $expression
  883. * @return string The SQL.
  884. */
  885. public function walkCaseExpression($expression)
  886. {
  887. switch (true) {
  888. case ($expression instanceof AST\CoalesceExpression):
  889. return $this->walkCoalesceExpression($expression);
  890. case ($expression instanceof AST\NullIfExpression):
  891. return $this->walkNullIfExpression($expression);
  892. case ($expression instanceof AST\GeneralCaseExpression):
  893. return $this->walkGeneralCaseExpression($expression);
  894. case ($expression instanceof AST\SimpleCaseExpression):
  895. return $this->walkSimpleCaseExpression($expression);
  896. default:
  897. return '';
  898. }
  899. }
  900. /**
  901. * Walks down a CoalesceExpression AST node and generates the corresponding SQL.
  902. *
  903. * @param CoalesceExpression $coalesceExpression
  904. * @return string The SQL.
  905. */
  906. public function walkCoalesceExpression($coalesceExpression)
  907. {
  908. $sql = 'COALESCE(';
  909. $scalarExpressions = array();
  910. foreach ($coalesceExpression->scalarExpressions as $scalarExpression) {
  911. $scalarExpressions[] = $this->walkSimpleArithmeticExpression($scalarExpression);
  912. }
  913. $sql .= implode(', ', $scalarExpressions) . ')';
  914. return $sql;
  915. }
  916. /**
  917. * Walks down a NullIfExpression AST node and generates the corresponding SQL.
  918. *
  919. * @param NullIfExpression $nullIfExpression
  920. * @return string The SQL.
  921. */
  922. public function walkNullIfExpression($nullIfExpression)
  923. {
  924. $firstExpression = is_string($nullIfExpression->firstExpression)
  925. ? $this->conn->quote($nullIfExpression->firstExpression)
  926. : $this->walkSimpleArithmeticExpression($nullIfExpression->firstExpression);
  927. $secondExpression = is_string($nullIfExpression->secondExpression)
  928. ? $this->conn->quote($nullIfExpression->secondExpression)
  929. : $this->walkSimpleArithmeticExpression($nullIfExpression->secondExpression);
  930. return 'NULLIF(' . $firstExpression . ', ' . $secondExpression . ')';
  931. }
  932. /**
  933. * Walks down a GeneralCaseExpression AST node and generates the corresponding SQL.
  934. *
  935. * @param GeneralCaseExpression $generalCaseExpression
  936. * @return string The SQL.
  937. */
  938. public function walkGeneralCaseExpression(AST\GeneralCaseExpression $generalCaseExpression)
  939. {
  940. $sql = 'CASE';
  941. foreach ($generalCaseExpression->whenClauses as $whenClause) {
  942. $sql .= ' WHEN ' . $this->walkConditionalExpression($whenClause->caseConditionExpression);
  943. $sql .= ' THEN ' . $this->walkSimpleArithmeticExpression($whenClause->thenScalarExpression);
  944. }
  945. $sql .= ' ELSE ' . $this->walkSimpleArithmeticExpression($generalCaseExpression->elseScalarExpression) . ' END';
  946. return $sql;
  947. }
  948. /**
  949. * Walks down a SimpleCaseExpression AST node and generates the corresponding SQL.
  950. *
  951. * @param SimpleCaseExpression $simpleCaseExpression
  952. * @return string The SQL.
  953. */
  954. public function walkSimpleCaseExpression($simpleCaseExpression)
  955. {
  956. $sql = 'CASE ' . $this->walkStateFieldPathExpression($simpleCaseExpression->caseOperand);
  957. foreach ($simpleCaseExpression->simpleWhenClauses as $simpleWhenClause) {
  958. $sql .= ' WHEN ' . $this->walkSimpleArithmeticExpression($simpleWhenClause->caseScalarExpression);
  959. $sql .= ' THEN ' . $this->walkSimpleArithmeticExpression($simpleWhenClause->thenScalarExpression);
  960. }
  961. $sql .= ' ELSE ' . $this->walkSimpleArithmeticExpression($simpleCaseExpression->elseScalarExpression) . ' END';
  962. return $sql;
  963. }
  964. /**
  965. * Walks down a SelectExpression AST node and generates the corresponding SQL.
  966. *
  967. * @param SelectExpression $selectExpression
  968. * @return string The SQL.
  969. */
  970. public function walkSelectExpression($selectExpression)
  971. {
  972. $sql = '';
  973. $expr = $selectExpression->expression;
  974. $hidden = $selectExpression->hiddenAliasResultVariable;
  975. switch (true) {
  976. case ($expr instanceof AST\PathExpression):
  977. if ($expr->type !== AST\PathExpression::TYPE_STATE_FIELD) {
  978. throw QueryException::invalidPathExpression($expr);
  979. }
  980. $fieldName = $expr->field;
  981. $dqlAlias = $expr->identificationVariable;
  982. $qComp = $this->queryComponents[$dqlAlias];
  983. $class = $qComp['metadata'];
  984. $resultAlias = $selectExpression->fieldIdentificationVariable ?: $fieldName;
  985. $tableName = ($class->isInheritanceTypeJoined())
  986. ? $this->em->getUnitOfWork()->getEntityPersister($class->name)->getOwningTable($fieldName)
  987. : $class->getTableName();
  988. $sqlTableAlias = $this->getSQLTableAlias($tableName, $dqlAlias);
  989. $columnName = $this->quoteStrategy->getColumnName($fieldName, $class, $this->platform);
  990. $columnAlias = $this->getSQLColumnAlias($class->fieldMappings[$fieldName]['columnName']);
  991. $col = $sqlTableAlias . '.' . $columnName;
  992. $fieldType = $class->getTypeOfField($fieldName);
  993. if (isset($class->fieldMappings[$fieldName]['requireSQLConversion'])) {
  994. $type = Type::getType($fieldType);
  995. $col = $type->convertToPHPValueSQL($col, $this->conn->getDatabasePlatform());
  996. }
  997. $sql .= $col . ' AS ' . $columnAlias;
  998. $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
  999. if ( ! $hidden) {
  1000. $this->rsm->addScalarResult($columnAlias, $resultAlias, $fieldType);
  1001. $this->scalarFields[$dqlAlias][$fieldName] = $columnAlias;
  1002. }
  1003. break;
  1004. case ($expr instanceof AST\AggregateExpression):
  1005. case ($expr instanceof AST\Functions\FunctionNode):
  1006. case ($expr instanceof AST\SimpleArithmeticExpression):
  1007. case ($expr instanceof AST\ArithmeticTerm):
  1008. case ($expr instanceof AST\ArithmeticFactor):
  1009. case ($expr instanceof AST\Literal):
  1010. case ($expr instanceof AST\NullIfExpression):
  1011. case ($expr instanceof AST\CoalesceExpression):
  1012. case ($expr instanceof AST\GeneralCaseExpression):
  1013. case ($expr instanceof AST\SimpleCaseExpression):
  1014. $columnAlias = $this->getSQLColumnAlias('sclr');
  1015. $resultAlias = $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
  1016. $sql .= $expr->dispatch($this) . ' AS ' . $columnAlias;
  1017. $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
  1018. if ( ! $hidden) {
  1019. // We cannot resolve field type here; assume 'string'.
  1020. $this->rsm->addScalarResult($columnAlias, $resultAlias, 'string');
  1021. }
  1022. break;
  1023. case ($expr instanceof AST\Subselect):
  1024. $columnAlias = $this->getSQLColumnAlias('sclr');
  1025. $resultAlias = $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
  1026. $sql .= '(' . $this->walkSubselect($expr) . ') AS ' . $columnAlias;
  1027. $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
  1028. if ( ! $hidden) {
  1029. // We cannot resolve field type here; assume 'string'.
  1030. $this->rsm->addScalarResult($columnAlias, $resultAlias, 'string');
  1031. }
  1032. break;
  1033. case ($expr instanceof AST\NewObjectExpression):
  1034. $sql .= $this->walkNewObject($expr);
  1035. break;
  1036. default:
  1037. // IdentificationVariable or PartialObjectExpression
  1038. if ($expr instanceof AST\PartialObjectExpression) {
  1039. $dqlAlias = $expr->identificationVariable;
  1040. $partialFieldSet = $expr->partialFieldSet;
  1041. } else {
  1042. $dqlAlias = $expr;
  1043. $partialFieldSet = array();
  1044. }
  1045. $queryComp = $this->queryComponents[$dqlAlias];
  1046. $class = $queryComp['metadata'];
  1047. $resultAlias = $selectExpression->fieldIdentificationVariable ?: null;
  1048. if ( ! isset($this->selectedClasses[$dqlAlias])) {
  1049. $this->selectedClasses[$dqlAlias] = array(
  1050. 'class' => $class,
  1051. 'dqlAlias' => $dqlAlias,
  1052. 'resultAlias' => $resultAlias
  1053. );
  1054. }
  1055. $sqlParts = array();
  1056. // Select all fields from the queried class
  1057. foreach ($class->fieldMappings as $fieldName => $mapping) {
  1058. if ($partialFieldSet && ! in_array($fieldName, $partialFieldSet)) {
  1059. continue;
  1060. }
  1061. $tableName = (isset($mapping['inherited']))
  1062. ? $this->em->getClassMetadata($mapping['inherited'])->getTableName()
  1063. : $class->getTableName();
  1064. $sqlTableAlias = $this->getSQLTableAlias($tableName, $dqlAlias);
  1065. $columnAlias = $this->getSQLColumnAlias($mapping['columnName']);
  1066. $quotedColumnName = $this->quoteStrategy->getColumnName($fieldName, $class, $this->platform);
  1067. $col = $sqlTableAlias . '.' . $quotedColumnName;
  1068. if (isset($class->fieldMappings[$fieldName]['requireSQLConversion'])) {
  1069. $type = Type::getType($class->getTypeOfField($fieldName));
  1070. $col = $type->convertToPHPValueSQL($col, $this->platform);
  1071. }
  1072. $sqlParts[] = $col . ' AS '. $columnAlias;
  1073. $this->scalarResultAliasMap[$resultAlias][] = $columnAlias;
  1074. $this->rsm->addFieldResult($dqlAlias, $columnAlias, $fieldName, $class->name);
  1075. }
  1076. // Add any additional fields of subclasses (excluding inherited fields)
  1077. // 1) on Single Table Inheritance: always, since its marginal overhead
  1078. // 2) on Class Table Inheritance only if partial objects are disallowed,
  1079. // since it requires outer joining subtables.
  1080. if ($class->isInheritanceTypeSingleTable() || ! $this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD)) {
  1081. foreach ($class->subClasses as $subClassName) {
  1082. $subClass = $this->em->getClassMetadata($subClassName);
  1083. $sqlTableAlias = $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias);
  1084. foreach ($subClass->fieldMappings as $fieldName => $mapping) {
  1085. if (isset($mapping['inherited']) || $partialFieldSet && !in_array($fieldName, $partialFieldSet)) {
  1086. continue;
  1087. }
  1088. $columnAlias = $this->getSQLColumnAlias($mapping['columnName']);
  1089. $quotedColumnName = $this->quoteStrategy->getColumnName($fieldName, $subClass, $this->platform);
  1090. $col = $sqlTableAlias . '.' . $quotedColumnName;
  1091. if (isset($subClass->fieldMappings[$fieldName]['requireSQLConversion'])) {
  1092. $type = Type::getType($subClass->getTypeOfField($fieldName));
  1093. $col = $type->convertToPHPValueSQL($col, $this->platform);
  1094. }
  1095. $sqlParts[] = $col . ' AS ' . $columnAlias;
  1096. $this->scalarResultAliasMap[$resultAlias][] = $columnAlias;
  1097. $this->rsm->addFieldResult($dqlAlias, $columnAlias, $fieldName, $subClassName);
  1098. }
  1099. }
  1100. }
  1101. $sql .= implode(', ', $sqlParts);
  1102. }
  1103. return $sql;
  1104. }
  1105. /**
  1106. * Walks down a QuantifiedExpression AST node, thereby generating the appropriate SQL.
  1107. *
  1108. * @param QuantifiedExpression
  1109. * @return string The SQL.
  1110. */
  1111. public function walkQuantifiedExpression($qExpr)
  1112. {
  1113. return ' ' . strtoupper($qExpr->type) . '(' . $this->walkSubselect($qExpr->subselect) . ')';
  1114. }
  1115. /**
  1116. * Walks down a Subselect AST node, thereby generating the appropriate SQL.
  1117. *
  1118. * @param Subselect
  1119. * @return string The SQL.
  1120. */
  1121. public function walkSubselect($subselect)
  1122. {
  1123. $useAliasesBefore = $this->useSqlTableAliases;
  1124. $rootAliasesBefore = $this->rootAliases;
  1125. $this->rootAliases = array(); // reset the rootAliases for the subselect
  1126. $this->useSqlTableAliases = true;
  1127. $sql = $this->walkSimpleSelectClause($subselect->simpleSelectClause);
  1128. $sql .= $this->walkSubselectFromClause($subselect->subselectFromClause);
  1129. $sql .= $this->walkWhereClause($subselect->whereClause);
  1130. $sql .= $subselect->groupByClause ? $this->walkGroupByClause($subselect->groupByClause) : '';
  1131. $sql .= $subselect->havingClause ? $this->walkHavingClause($subselect->havingClause) : '';
  1132. $sql .= $subselect->orderByClause ? $this->walkOrderByClause($subselect->orderByClause) : '';
  1133. $this->rootAliases = $rootAliasesBefore; // put the main aliases back
  1134. $this->useSqlTableAliases = $useAliasesBefore;
  1135. return $sql;
  1136. }
  1137. /**
  1138. * Walks down a SubselectFromClause AST node, thereby generating the appropriate SQL.
  1139. *
  1140. * @param SubselectFromClause
  1141. * @return string The SQL.
  1142. */
  1143. public function walkSubselectFromClause($subselectFromClause)
  1144. {
  1145. $identificationVarDecls = $subselectFromClause->identificationVariableDeclarations;
  1146. $sqlParts = array ();
  1147. foreach ($identificationVarDecls as $subselectIdVarDecl) {
  1148. $sql = $this->walkRangeVariableDeclaration($subselectIdVarDecl->rangeVariableDeclaration);
  1149. foreach ($subselectIdVarDecl->joins as $join) {
  1150. $sql .= $this->walkJoin($join);
  1151. }
  1152. $sqlParts[] = $this->platform->appendLockHint($sql, $this->query->getHint(Query::HINT_LOCK_MODE));
  1153. }
  1154. return ' FROM ' . implode(', ', $sqlParts);
  1155. }
  1156. /**
  1157. * Walks down a SimpleSelectClause AST node, thereby generating the appropriate SQL.
  1158. *
  1159. * @param SimpleSelectClause
  1160. * @return string The SQL.
  1161. */
  1162. public function walkSimpleSelectClause($simpleSelectClause)
  1163. {
  1164. return 'SELECT' . ($simpleSelectClause->isDistinct ? ' DISTINCT' : '')
  1165. . $this->walkSimpleSelectExpression($simpleSelectClause->simpleSelectExpression);
  1166. }
  1167. /**
  1168. * @param AST\NewObjectExpression
  1169. * @return string The SQL.
  1170. */
  1171. public function walkNewObject($newObjectExpression)
  1172. {
  1173. $sqlSelectExpressions = array();
  1174. $objIndex = $this->newObjectCounter++;
  1175. foreach ($newObjectExpression->args as $argIndex => $e) {
  1176. $resultAlias = $this->scalarResultCounter++;
  1177. $columnAlias = $this->getSQLColumnAlias('sclr');
  1178. switch (true) {
  1179. case ($e instanceof AST\NewObjectExpression):
  1180. $sqlSelectExpressions[] = $e->dispatch($this);
  1181. break;
  1182. default:
  1183. $sqlSelectExpressions[] = trim($e->dispatch($this)) . ' AS ' . $columnAlias;
  1184. break;
  1185. }
  1186. switch (true) {
  1187. case ($e instanceof AST\PathExpression):
  1188. $fieldName = $e->field;
  1189. $dqlAlias = $e->identificationVariable;
  1190. $qComp = $this->queryComponents[$dqlAlias];
  1191. $class = $qComp['metadata'];
  1192. $fieldType = $class->getTypeOfField($fieldName);
  1193. break;
  1194. case ($e instanceof AST\Literal):
  1195. switch ($e->type) {
  1196. case AST\Literal::BOOLEAN:
  1197. $fieldType = 'boolean';
  1198. break;
  1199. case AST\Literal::NUMERIC:
  1200. $fieldType = is_float($e->value) ? 'float' : 'integer';
  1201. break;
  1202. }
  1203. break;
  1204. default:
  1205. $fieldType = 'string';
  1206. break;
  1207. }
  1208. $this->scalarResultAliasMap[$resultAlias] = $columnAlias;
  1209. $this->rsm->addScalarResult($columnAlias, $resultAlias, $fieldType);
  1210. $this->rsm->newObjectMappings[$columnAlias] = array(
  1211. 'className' => $newObjectExpression->className,
  1212. 'objIndex' => $objIndex,
  1213. 'argIndex' => $argIndex
  1214. );
  1215. }
  1216. return implode(', ', $sqlSelectExpressions);
  1217. }
  1218. /**
  1219. * Walks down a SimpleSelectExpression AST node, thereby generating the appropriate SQL.
  1220. *
  1221. * @param SimpleSelectExpression
  1222. * @return string The SQL.
  1223. */
  1224. public function walkSimpleSelectExpression($simpleSelectExpression)
  1225. {
  1226. $expr = $simpleSelectExpression->expression;
  1227. $sql = ' ';
  1228. switch (true) {
  1229. case ($expr instanceof AST\PathExpression):
  1230. $sql .= $this->walkPathExpression($expr);
  1231. break;
  1232. case ($expr instanceof AST\AggregateExpression):
  1233. $alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
  1234. $sql .= $this->walkAggregateExpression($expr) . ' AS dctrn__' . $alias;
  1235. break;
  1236. case ($expr instanceof AST\Subselect):
  1237. $alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
  1238. $columnAlias = 'sclr' . $this->aliasCounter++;
  1239. $this->scalarResultAliasMap[$alias] = $columnAlias;
  1240. $sql .= '(' . $this->walkSubselect($expr) . ') AS ' . $columnAlias;
  1241. break;
  1242. case ($expr instanceof AST\Functions\FunctionNode):
  1243. case ($expr instanceof AST\SimpleArithmeticExpression):
  1244. case ($expr instanceof AST\ArithmeticTerm):
  1245. case ($expr instanceof AST\ArithmeticFactor):
  1246. case ($expr instanceof AST\Literal):
  1247. case ($expr instanceof AST\NullIfExpression):
  1248. case ($expr instanceof AST\CoalesceExpression):
  1249. case ($expr instanceof AST\GeneralCaseExpression):
  1250. case ($expr instanceof AST\SimpleCaseExpression):
  1251. $alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++;
  1252. $columnAlias = $this->getSQLColumnAlias('sclr');
  1253. $this->scalarResultAliasMap[$alias] = $columnAlias;
  1254. $sql .= $expr->dispatch($this) . ' AS ' . $columnAlias;
  1255. break;
  1256. default: // IdentificationVariable
  1257. $sql .= $this->walkEntityIdentificationVariable($expr);
  1258. break;
  1259. }
  1260. return $sql;
  1261. }
  1262. /**
  1263. * Walks down an AggregateExpression AST node, thereby generating the appropriate SQL.
  1264. *
  1265. * @param AggregateExpression
  1266. * @return string The SQL.
  1267. */
  1268. public function walkAggregateExpression($aggExpression)
  1269. {
  1270. return $aggExpression->functionName . '(' . ($aggExpression->isDistinct ? 'DISTINCT ' : '')
  1271. . $this->walkSimpleArithmeticExpression($aggExpression->pathExpression) . ')';
  1272. }
  1273. /**
  1274. * Walks down a GroupByClause AST node, thereby generating the appropriate SQL.
  1275. *
  1276. * @param GroupByClause
  1277. * @return string The SQL.
  1278. */
  1279. public function walkGroupByClause($groupByClause)
  1280. {
  1281. $sqlParts = array();
  1282. foreach ($groupByClause->groupByItems as $groupByItem) {
  1283. $sqlParts[] = $this->walkGroupByItem($groupByItem);
  1284. }
  1285. return ' GROUP BY ' . implode(', ', $sqlParts);
  1286. }
  1287. /**
  1288. * Walks down a GroupByItem AST node, thereby generating the appropriate SQL.
  1289. *
  1290. * @param GroupByItem
  1291. * @return string The SQL.
  1292. */
  1293. public function walkGroupByItem($groupByItem)
  1294. {
  1295. // StateFieldPathExpression
  1296. if ( ! is_string($groupByItem)) {
  1297. return $this->walkPathExpression($groupByItem);
  1298. }
  1299. // ResultVariable
  1300. if (isset($this->queryComponents[$groupByItem]['resultVariable'])) {
  1301. return $this->walkResultVariable($groupByItem);
  1302. }
  1303. // IdentificationVariable
  1304. $sqlParts = array();
  1305. foreach ($this->queryComponents[$groupByItem]['metadata']->fieldNames as $field) {
  1306. $item = new AST\PathExpression(AST\PathExpression::TYPE_STATE_FIELD, $groupByItem, $field);
  1307. $item->type = AST\PathExpression::TYPE_STATE_FIELD;
  1308. $sqlParts[] = $this->walkPathExpression($item);
  1309. }
  1310. foreach ($this->queryComponents[$groupByItem]['metadata']->associationMappings as $mapping) {
  1311. if ($mapping['isOwningSide'] && $mapping['type'] & ClassMetadataInfo::TO_ONE) {
  1312. $item = new AST\PathExpression(AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, $groupByItem, $mapping['fieldName']);
  1313. $item->type = AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION;
  1314. $sqlParts[] = $this->walkPathExpression($item);
  1315. }
  1316. }
  1317. return implode(', ', $sqlParts);
  1318. }
  1319. /**
  1320. * Walks down a DeleteClause AST node, thereby generating the appropriate SQL.
  1321. *
  1322. * @param DeleteClause
  1323. * @return string The SQL.
  1324. */
  1325. public function walkDeleteClause(AST\DeleteClause $deleteClause)
  1326. {
  1327. $class = $this->em->getClassMetadata($deleteClause->abstractSchemaName);
  1328. $tableName = $class->getTableName();
  1329. $sql = 'DELETE FROM ' . $this->quoteStrategy->getTableName($class, $this->platform);
  1330. $this->setSQLTableAlias($tableName, $tableName, $deleteClause->aliasIdentificationVariable);
  1331. $this->rootAliases[] = $deleteClause->aliasIdentificationVariable;
  1332. return $sql;
  1333. }
  1334. /**
  1335. * Walks down an UpdateClause AST node, thereby generating the appropriate SQL.
  1336. *
  1337. * @param UpdateClause
  1338. * @return string The SQL.
  1339. */
  1340. public function walkUpdateClause($updateClause)
  1341. {
  1342. $class = $this->em->getClassMetadata($updateClause->abstractSchemaName);
  1343. $tableName = $class->getTableName();
  1344. $sql = 'UPDATE ' . $this->quoteStrategy->getTableName($class, $this->platform);
  1345. $this->setSQLTableAlias($tableName, $tableName, $updateClause->aliasIdentificationVariable);
  1346. $this->rootAliases[] = $updateClause->aliasIdentificationVariable;
  1347. $sql .= ' SET ' . implode(', ', array_map(array($this, 'walkUpdateItem'), $updateClause->updateItems));
  1348. return $sql;
  1349. }
  1350. /**
  1351. * Walks down an UpdateItem AST node, thereby generating the appropriate SQL.
  1352. *
  1353. * @param UpdateItem
  1354. * @return string The SQL.
  1355. */
  1356. public function walkUpdateItem($updateItem)
  1357. {
  1358. $useTableAliasesBefore = $this->useSqlTableAliases;
  1359. $this->useSqlTableAliases = false;
  1360. $sql = $this->walkPathExpression($updateItem->pathExpression) . ' = ';
  1361. $newValue = $updateItem->newValue;
  1362. switch (true) {
  1363. case ($newValue instanceof AST\Node):
  1364. $sql .= $newValue->dispatch($this);
  1365. break;
  1366. case ($newValue === null):
  1367. $sql .= 'NULL';
  1368. break;
  1369. default:
  1370. $sql .= $this->conn->quote($newValue);
  1371. break;
  1372. }
  1373. $this->useSqlTableAliases = $useTableAliasesBefore;
  1374. return $sql;
  1375. }
  1376. /**
  1377. * Walks down a WhereClause AST node, thereby generating the appropriate SQL.
  1378. * WhereClause or not, the appropriate discriminator sql is added.
  1379. *
  1380. * @param WhereClause
  1381. * @return string The SQL.
  1382. */
  1383. public function walkWhereClause($whereClause)
  1384. {
  1385. $condSql = null !== $whereClause ? $this->walkConditionalExpression($whereClause->conditionalExpression) : '';
  1386. $discrSql = $this->_generateDiscriminatorColumnConditionSql($this->rootAliases);
  1387. if ($this->em->hasFilters()) {
  1388. $filterClauses = array();
  1389. foreach ($this->rootAliases as $dqlAlias) {
  1390. $class = $this->queryComponents[$dqlAlias]['metadata'];
  1391. $tableAlias = $this->getSQLTableAlias($class->table['name'], $dqlAlias);
  1392. if ($filterExpr = $this->generateFilterConditionSQL($class, $tableAlias)) {
  1393. $filterClauses[] = $filterExpr;
  1394. }
  1395. }
  1396. if (count($filterClauses)) {
  1397. if ($condSql) {
  1398. $condSql = '(' . $condSql . ') AND ';
  1399. }
  1400. $condSql .= implode(' AND ', $filterClauses);
  1401. }
  1402. }
  1403. if ($condSql) {
  1404. return ' WHERE ' . (( ! $discrSql) ? $condSql : '(' . $condSql . ') AND ' . $discrSql);
  1405. }
  1406. if ($discrSql) {
  1407. return ' WHERE ' . $discrSql;
  1408. }
  1409. return '';
  1410. }
  1411. /**
  1412. * Walk down a ConditionalExpression AST node, thereby generating the appropriate SQL.
  1413. *
  1414. * @param ConditionalExpression
  1415. * @return string The SQL.
  1416. */
  1417. public function walkConditionalExpression($condExpr)
  1418. {
  1419. // Phase 2 AST optimization: Skip processment of ConditionalExpression
  1420. // if only one ConditionalTerm is defined
  1421. if ( ! ($condExpr instanceof AST\ConditionalExpression)) {
  1422. return $this->walkConditionalTerm($condExpr);
  1423. }
  1424. return implode(' OR ', array_map(array($this, 'walkConditionalTerm'), $condExpr->conditionalTerms));
  1425. }
  1426. /**
  1427. * Walks down a ConditionalTerm AST node, thereby generating the appropriate SQL.
  1428. *
  1429. * @param ConditionalTerm
  1430. * @return string The SQL.
  1431. */
  1432. public function walkConditionalTerm($condTerm)
  1433. {
  1434. // Phase 2 AST optimization: Skip processment of ConditionalTerm
  1435. // if only one ConditionalFactor is defined
  1436. if ( ! ($condTerm instanceof AST\ConditionalTerm)) {
  1437. return $this->walkConditionalFactor($condTerm);
  1438. }
  1439. return implode(' AND ', array_map(array($this, 'walkConditionalFactor'), $condTerm->conditionalFactors));
  1440. }
  1441. /**
  1442. * Walks down a ConditionalFactor AST node, thereby generating the appropriate SQL.
  1443. *
  1444. * @param ConditionalFactor
  1445. * @return string The SQL.
  1446. */
  1447. public function walkConditionalFactor($factor)
  1448. {
  1449. // Phase 2 AST optimization: Skip processment of ConditionalFactor
  1450. // if only one ConditionalPrimary is defined
  1451. return ( ! ($factor instanceof AST\ConditionalFactor))
  1452. ? $this->walkConditionalPrimary($factor)
  1453. : ($factor->not ? 'NOT ' : '') . $this->walkConditionalPrimary($factor->conditionalPrimary);
  1454. }
  1455. /**
  1456. * Walks down a ConditionalPrimary AST node, thereby generating the appropriate SQL.
  1457. *
  1458. * @param ConditionalPrimary
  1459. * @return string The SQL.
  1460. */
  1461. public function walkConditionalPrimary($primary)
  1462. {
  1463. if ($primary->isSimpleConditionalExpression()) {
  1464. return $primary->simpleConditionalExpression->dispatch($this);
  1465. }
  1466. if ($primary->isConditionalExpression()) {
  1467. $condExpr = $primary->conditionalExpression;
  1468. return '(' . $this->walkConditionalExpression($condExpr) . ')';
  1469. }
  1470. }
  1471. /**
  1472. * Walks down an ExistsExpression AST node, thereby generating the appropriate SQL.
  1473. *
  1474. * @param ExistsExpression
  1475. * @return string The SQL.
  1476. */
  1477. public function walkExistsExpression($existsExpr)
  1478. {
  1479. $sql = ($existsExpr->not) ? 'NOT ' : '';
  1480. $sql .= 'EXISTS (' . $this->walkSubselect($existsExpr->subselect) . ')';
  1481. return $sql;
  1482. }
  1483. /**
  1484. * Walks down a CollectionMemberExpression AST node, thereby generating the appropriate SQL.
  1485. *
  1486. * @param CollectionMemberExpression
  1487. * @return string The SQL.
  1488. */
  1489. public function walkCollectionMemberExpression($collMemberExpr)
  1490. {
  1491. $sql = $collMemberExpr->not ? 'NOT ' : '';
  1492. $sql .= 'EXISTS (SELECT 1 FROM ';
  1493. $entityExpr = $collMemberExpr->entityExpression;
  1494. $collPathExpr = $collMemberExpr->collectionValuedPathExpression;
  1495. $fieldName = $collPathExpr->field;
  1496. $dqlAlias = $collPathExpr->identificationVariable;
  1497. $class = $this->queryComponents[$dqlAlias]['metadata'];
  1498. switch (true) {
  1499. // InputParameter
  1500. case ($entityExpr instanceof AST\InputParameter):
  1501. $dqlParamKey = $entityExpr->name;
  1502. $entitySql = '?';
  1503. break;
  1504. // SingleValuedAssociationPathExpression | IdentificationVariable
  1505. case ($entityExpr instanceof AST\PathExpression):
  1506. $entitySql = $this->walkPathExpression($entityExpr);
  1507. break;
  1508. default:
  1509. throw new \BadMethodCallException("Not implemented");
  1510. }
  1511. $assoc = $class->associationMappings[$fieldName];
  1512. if ($assoc['type'] == ClassMetadata::ONE_TO_MANY) {
  1513. $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
  1514. $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName());
  1515. $sourceTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
  1516. $sql .= $this->quoteStrategy->getTableName($targetClass, $this->platform) . ' ' . $targetTableAlias . ' WHERE ';
  1517. $owningAssoc = $targetClass->associationMappings[$assoc['mappedBy']];
  1518. $sqlParts = array();
  1519. foreach ($owningAssoc['targetToSourceKeyColumns'] as $targetColumn => $sourceColumn) {
  1520. $targetColumn = $this->quoteStrategy->getColumnName($class->fieldNames[$targetColumn], $class, $this->platform);
  1521. $sqlParts[] = $sourceTableAlias . '.' . $targetColumn . ' = ' . $targetTableAlias . '.' . $sourceColumn;
  1522. }
  1523. foreach ($this->quoteStrategy->getIdentifierColumnNames($targetClass, $this->platform) as $targetColumnName) {
  1524. if (isset($dqlParamKey)) {
  1525. $this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++);
  1526. }
  1527. $sqlParts[] = $targetTableAlias . '.' . $targetColumnName . ' = ' . $entitySql;
  1528. }
  1529. $sql .= implode(' AND ', $sqlParts);
  1530. } else { // many-to-many
  1531. $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
  1532. $owningAssoc = $assoc['isOwningSide'] ? $assoc : $targetClass->associationMappings[$assoc['mappedBy']];
  1533. $joinTable = $owningAssoc['joinTable'];
  1534. // SQL table aliases
  1535. $joinTableAlias = $this->getSQLTableAlias($joinTable['name']);
  1536. $targetTableAlias = $this->getSQLTableAlias($targetClass->getTableName());
  1537. $sourceTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
  1538. // join to target table
  1539. $sql .= $this->quoteStrategy->getJoinTableName($owningAssoc, $targetClass, $this->platform) . ' ' . $joinTableAlias
  1540. . ' INNER JOIN ' . $this->quoteStrategy->getTableName($targetClass, $this->platform) . ' ' . $targetTableAlias . ' ON ';
  1541. // join conditions
  1542. $joinColumns = $assoc['isOwningSide'] ? $joinTable['inverseJoinColumns'] : $joinTable['joinColumns'];
  1543. $joinSqlParts = array();
  1544. foreach ($joinColumns as $joinColumn) {
  1545. $targetColumn = $this->quoteStrategy->getColumnName($targetClass->fieldNames[$joinColumn['referencedColumnName']], $targetClass, $this->platform);
  1546. $joinSqlParts[] = $joinTableAlias . '.' . $joinColumn['name'] . ' = ' . $targetTableAlias . '.' . $targetColumn;
  1547. }
  1548. $sql .= implode(' AND ', $joinSqlParts);
  1549. $sql .= ' WHERE ';
  1550. $joinColumns = $assoc['isOwningSide'] ? $joinTable['joinColumns'] : $joinTable['inverseJoinColumns'];
  1551. $sqlParts = array();
  1552. foreach ($joinColumns as $joinColumn) {
  1553. $targetColumn = $this->quoteStrategy->getColumnName($class->fieldNames[$joinColumn['referencedColumnName']], $class, $this->platform);
  1554. $sqlParts[] = $joinTableAlias . '.' . $joinColumn['name'] . ' = ' . $sourceTableAlias . '.' . $targetColumn;
  1555. }
  1556. foreach ($this->quoteStrategy->getIdentifierColumnNames($targetClass, $this->platform) as $targetColumnName) {
  1557. if (isset($dqlParamKey)) {
  1558. $this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++);
  1559. }
  1560. $sqlParts[] = $targetTableAlias . '.' . $targetColumnName . ' = ' . $entitySql;
  1561. }
  1562. $sql .= implode(' AND ', $sqlParts);
  1563. }
  1564. return $sql . ')';
  1565. }
  1566. /**
  1567. * Walks down an EmptyCollectionComparisonExpression AST node, thereby generating the appropriate SQL.
  1568. *
  1569. * @param EmptyCollectionComparisonExpression
  1570. * @return string The SQL.
  1571. */
  1572. public function walkEmptyCollectionComparisonExpression($emptyCollCompExpr)
  1573. {
  1574. $sizeFunc = new AST\Functions\SizeFunction('size');
  1575. $sizeFunc->collectionPathExpression = $emptyCollCompExpr->expression;
  1576. return $sizeFunc->getSql($this) . ($emptyCollCompExpr->not ? ' > 0' : ' = 0');
  1577. }
  1578. /**
  1579. * Walks down a NullComparisonExpression AST node, thereby generating the appropriate SQL.
  1580. *
  1581. * @param NullComparisonExpression
  1582. * @return string The SQL.
  1583. */
  1584. public function walkNullComparisonExpression($nullCompExpr)
  1585. {
  1586. $sql = '';
  1587. $innerExpr = $nullCompExpr->expression;
  1588. if ($innerExpr instanceof AST\InputParameter) {
  1589. $dqlParamKey = $innerExpr->name;
  1590. $this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++);
  1591. $sql .= ' ?';
  1592. } else {
  1593. $sql .= $this->walkPathExpression($innerExpr);
  1594. }
  1595. $sql .= ' IS' . ($nullCompExpr->not ? ' NOT' : '') . ' NULL';
  1596. return $sql;
  1597. }
  1598. /**
  1599. * Walks down an InExpression AST node, thereby generating the appropriate SQL.
  1600. *
  1601. * @param InExpression
  1602. * @return string The SQL.
  1603. */
  1604. public function walkInExpression($inExpr)
  1605. {
  1606. $sql = $this->walkArithmeticExpression($inExpr->expression) . ($inExpr->not ? ' NOT' : '') . ' IN (';
  1607. $sql .= ($inExpr->subselect)
  1608. ? $this->walkSubselect($inExpr->subselect)
  1609. : implode(', ', array_map(array($this, 'walkInParameter'), $inExpr->literals));
  1610. $sql .= ')';
  1611. return $sql;
  1612. }
  1613. /**
  1614. * Walks down an InstanceOfExpression AST node, thereby generating the appropriate SQL.
  1615. *
  1616. * @param InstanceOfExpression
  1617. * @return string The SQL.
  1618. */
  1619. public function walkInstanceOfExpression($instanceOfExpr)
  1620. {
  1621. $sql = '';
  1622. $dqlAlias = $instanceOfExpr->identificationVariable;
  1623. $discrClass = $class = $this->queryComponents[$dqlAlias]['metadata'];
  1624. if ($class->discriminatorColumn) {
  1625. $discrClass = $this->em->getClassMetadata($class->rootEntityName);
  1626. }
  1627. if ($this->useSqlTableAliases) {
  1628. $sql .= $this->getSQLTableAlias($discrClass->getTableName(), $dqlAlias) . '.';
  1629. }
  1630. $sql .= $class->discriminatorColumn['name'] . ($instanceOfExpr->not ? ' NOT IN ' : ' IN ');
  1631. $sqlParameterList = array();
  1632. foreach ($instanceOfExpr->value as $parameter) {
  1633. if ($parameter instanceof AST\InputParameter) {
  1634. // We need to modify the parameter value to be its correspondent mapped value
  1635. $dqlParamKey = $parameter->name;
  1636. $dqlParam = $this->query->getParameter($dqlParamKey);
  1637. $paramValue = $this->query->processParameterValue($dqlParam->getValue());
  1638. if ( ! ($paramValue instanceof \Doctrine\ORM\Mapping\ClassMetadata)) {
  1639. throw QueryException::invalidParameterType('ClassMetadata', get_class($paramValue));
  1640. }
  1641. $entityClassName = $paramValue->name;
  1642. } else {
  1643. // Get name from ClassMetadata to resolve aliases.
  1644. $entityClassName = $this->em->getClassMetadata($parameter)->name;
  1645. }
  1646. if ($entityClassName == $class->name) {
  1647. $sqlParameterList[] = $this->conn->quote($class->discriminatorValue);
  1648. } else {
  1649. $discrMap = array_flip($class->discriminatorMap);
  1650. if (!isset($discrMap[$entityClassName])) {
  1651. throw QueryException::instanceOfUnrelatedClass($entityClassName, $class->rootEntityName);
  1652. }
  1653. $sqlParameterList[] = $this->conn->quote($discrMap[$entityClassName]);
  1654. }
  1655. }
  1656. $sql .= '(' . implode(', ', $sqlParameterList) . ')';
  1657. return $sql;
  1658. }
  1659. /**
  1660. * Walks down an InParameter AST node, thereby generating the appropriate SQL.
  1661. *
  1662. * @param InParameter
  1663. * @return string The SQL.
  1664. */
  1665. public function walkInParameter($inParam)
  1666. {
  1667. return $inParam instanceof AST\InputParameter
  1668. ? $this->walkInputParameter($inParam)
  1669. : $this->walkLiteral($inParam);
  1670. }
  1671. /**
  1672. * Walks down a literal that represents an AST node, thereby generating the appropriate SQL.
  1673. *
  1674. * @param mixed
  1675. * @return string The SQL.
  1676. */
  1677. public function walkLiteral($literal)
  1678. {
  1679. switch ($literal->type) {
  1680. case AST\Literal::STRING:
  1681. return $this->conn->quote($literal->value);
  1682. case AST\Literal::BOOLEAN:
  1683. $bool = strtolower($literal->value) == 'true' ? true : false;
  1684. $boolVal = $this->conn->getDatabasePlatform()->convertBooleans($bool);
  1685. return $boolVal;
  1686. case AST\Literal::NUMERIC:
  1687. return $literal->value;
  1688. default:
  1689. throw QueryException::invalidLiteral($literal);
  1690. }
  1691. }
  1692. /**
  1693. * Walks down a BetweenExpression AST node, thereby generating the appropriate SQL.
  1694. *
  1695. * @param BetweenExpression
  1696. * @return string The SQL.
  1697. */
  1698. public function walkBetweenExpression($betweenExpr)
  1699. {
  1700. $sql = $this->walkArithmeticExpression($betweenExpr->expression);
  1701. if ($betweenExpr->not) $sql .= ' NOT';
  1702. $sql .= ' BETWEEN ' . $this->walkArithmeticExpression($betweenExpr->leftBetweenExpression)
  1703. . ' AND ' . $this->walkArithmeticExpression($betweenExpr->rightBetweenExpression);
  1704. return $sql;
  1705. }
  1706. /**
  1707. * Walks down a LikeExpression AST node, thereby generating the appropriate SQL.
  1708. *
  1709. * @param LikeExpression
  1710. * @return string The SQL.
  1711. */
  1712. public function walkLikeExpression($likeExpr)
  1713. {
  1714. $stringExpr = $likeExpr->stringExpression;
  1715. $sql = $stringExpr->dispatch($this) . ($likeExpr->not ? ' NOT' : '') . ' LIKE ';
  1716. if ($likeExpr->stringPattern instanceof AST\InputParameter) {
  1717. $inputParam = $likeExpr->stringPattern;
  1718. $dqlParamKey = $inputParam->name;
  1719. $this->parserResult->addParameterMapping($dqlParamKey, $this->sqlParamIndex++);
  1720. $sql .= '?';
  1721. } elseif ($likeExpr->stringPattern instanceof AST\Functions\FunctionNode ) {
  1722. $sql .= $this->walkFunction($likeExpr->stringPattern);
  1723. } elseif ($likeExpr->stringPattern instanceof AST\PathExpression) {
  1724. $sql .= $this->walkPathExpression($likeExpr->stringPattern);
  1725. } else {
  1726. $sql .= $this->walkLiteral($likeExpr->stringPattern);
  1727. }
  1728. if ($likeExpr->escapeChar) {
  1729. $sql .= ' ESCAPE ' . $this->walkLiteral($likeExpr->escapeChar);
  1730. }
  1731. return $sql;
  1732. }
  1733. /**
  1734. * Walks down a StateFieldPathExpression AST node, thereby generating the appropriate SQL.
  1735. *
  1736. * @param StateFieldPathExpression
  1737. * @return string The SQL.
  1738. */
  1739. public function walkStateFieldPathExpression($stateFieldPathExpression)
  1740. {
  1741. return $this->walkPathExpression($stateFieldPathExpression);
  1742. }
  1743. /**
  1744. * Walks down a ComparisonExpression AST node, thereby generating the appropriate SQL.
  1745. *
  1746. * @param ComparisonExpression
  1747. * @return string The SQL.
  1748. */
  1749. public function walkComparisonExpression($compExpr)
  1750. {
  1751. $leftExpr = $compExpr->leftExpression;
  1752. $rightExpr = $compExpr->rightExpression;
  1753. $sql = '';
  1754. $sql .= ($leftExpr instanceof AST\Node)
  1755. ? $leftExpr->dispatch($this)
  1756. : (is_numeric($leftExpr) ? $leftExpr : $this->conn->quote($leftExpr));
  1757. $sql .= ' ' . $compExpr->operator . ' ';
  1758. $sql .= ($rightExpr instanceof AST\Node)
  1759. ? $rightExpr->dispatch($this)
  1760. : (is_numeric($rightExpr) ? $rightExpr : $this->conn->quote($rightExpr));
  1761. return $sql;
  1762. }
  1763. /**
  1764. * Walks down an InputParameter AST node, thereby generating the appropriate SQL.
  1765. *
  1766. * @param InputParameter
  1767. * @return string The SQL.
  1768. */
  1769. public function walkInputParameter($inputParam)
  1770. {
  1771. $this->parserResult->addParameterMapping($inputParam->name, $this->sqlParamIndex++);
  1772. return '?';
  1773. }
  1774. /**
  1775. * Walks down an ArithmeticExpression AST node, thereby generating the appropriate SQL.
  1776. *
  1777. * @param ArithmeticExpression
  1778. * @return string The SQL.
  1779. */
  1780. public function walkArithmeticExpression($arithmeticExpr)
  1781. {
  1782. return ($arithmeticExpr->isSimpleArithmeticExpression())
  1783. ? $this->walkSimpleArithmeticExpression($arithmeticExpr->simpleArithmeticExpression)
  1784. : '(' . $this->walkSubselect($arithmeticExpr->subselect) . ')';
  1785. }
  1786. /**
  1787. * Walks down an SimpleArithmeticExpression AST node, thereby generating the appropriate SQL.
  1788. *
  1789. * @param SimpleArithmeticExpression
  1790. * @return string The SQL.
  1791. */
  1792. public function walkSimpleArithmeticExpression($simpleArithmeticExpr)
  1793. {
  1794. if ( ! ($simpleArithmeticExpr instanceof AST\SimpleArithmeticExpression)) {
  1795. return $this->walkArithmeticTerm($simpleArithmeticExpr);
  1796. }
  1797. return implode(' ', array_map(array($this, 'walkArithmeticTerm'), $simpleArithmeticExpr->arithmeticTerms));
  1798. }
  1799. /**
  1800. * Walks down an ArithmeticTerm AST node, thereby generating the appropriate SQL.
  1801. *
  1802. * @param mixed
  1803. * @return string The SQL.
  1804. */
  1805. public function walkArithmeticTerm($term)
  1806. {
  1807. if (is_string($term)) {
  1808. return (isset($this->queryComponents[$term]))
  1809. ? $this->walkResultVariable($this->queryComponents[$term]['token']['value'])
  1810. : $term;
  1811. }
  1812. // Phase 2 AST optimization: Skip processment of ArithmeticTerm
  1813. // if only one ArithmeticFactor is defined
  1814. if ( ! ($term instanceof AST\ArithmeticTerm)) {
  1815. return $this->walkArithmeticFactor($term);
  1816. }
  1817. return implode(' ', array_map(array($this, 'walkArithmeticFactor'), $term->arithmeticFactors));
  1818. }
  1819. /**
  1820. * Walks down an ArithmeticFactor that represents an AST node, thereby generating the appropriate SQL.
  1821. *
  1822. * @param mixed
  1823. * @return string The SQL.
  1824. */
  1825. public function walkArithmeticFactor($factor)
  1826. {
  1827. if (is_string($factor)) {
  1828. return $factor;
  1829. }
  1830. // Phase 2 AST optimization: Skip processment of ArithmeticFactor
  1831. // if only one ArithmeticPrimary is defined
  1832. if ( ! ($factor instanceof AST\ArithmeticFactor)) {
  1833. return $this->walkArithmeticPrimary($factor);
  1834. }
  1835. $sign = $factor->isNegativeSigned() ? '-' : ($factor->isPositiveSigned() ? '+' : '');
  1836. return $sign . $this->walkArithmeticPrimary($factor->arithmeticPrimary);
  1837. }
  1838. /**
  1839. * Walks down an ArithmeticPrimary that represents an AST node, thereby generating the appropriate SQL.
  1840. *
  1841. * @param mixed
  1842. * @return string The SQL.
  1843. */
  1844. public function walkArithmeticPrimary($primary)
  1845. {
  1846. if ($primary instanceof AST\SimpleArithmeticExpression) {
  1847. return '(' . $this->walkSimpleArithmeticExpression($primary) . ')';
  1848. }
  1849. if ($primary instanceof AST\Node) {
  1850. return $primary->dispatch($this);
  1851. }
  1852. return $this->walkEntityIdentificationVariable($primary);
  1853. }
  1854. /**
  1855. * Walks down a StringPrimary that represents an AST node, thereby generating the appropriate SQL.
  1856. *
  1857. * @param mixed
  1858. * @return string The SQL.
  1859. */
  1860. public function walkStringPrimary($stringPrimary)
  1861. {
  1862. return (is_string($stringPrimary))
  1863. ? $this->conn->quote($stringPrimary)
  1864. : $stringPrimary->dispatch($this);
  1865. }
  1866. /**
  1867. * Walks down a ResultVriable that represents an AST node, thereby generating the appropriate SQL.
  1868. *
  1869. * @param string $resultVariable
  1870. * @return string The SQL.
  1871. */
  1872. public function walkResultVariable($resultVariable)
  1873. {
  1874. $resultAlias = $this->scalarResultAliasMap[$resultVariable];
  1875. if (is_array($resultAlias)) {
  1876. return implode(', ', $resultAlias);
  1877. }
  1878. return $resultAlias;
  1879. }
  1880. }