SqlWalker.php 76KB

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