SqlWalker.php 80 KB

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