PageRenderTime 60ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

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

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