SqlWalker.php 76KB

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