Query.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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;
  20. use Doctrine\Common\Collections\ArrayCollection;
  21. use Doctrine\DBAL\LockMode;
  22. use Doctrine\ORM\Query\Parser;
  23. use Doctrine\ORM\Query\ParserResult;
  24. use Doctrine\ORM\Query\QueryException;
  25. use Doctrine\ORM\Mapping\ClassMetadata;
  26. use Doctrine\ORM\Query\ParameterTypeInferer;
  27. /**
  28. * A Query object represents a DQL query.
  29. *
  30. * @since 1.0
  31. * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
  32. * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
  33. * @author Roman Borschel <roman@code-factory.org>
  34. */
  35. final class Query extends AbstractQuery
  36. {
  37. /**
  38. * A query object is in CLEAN state when it has NO unparsed/unprocessed DQL parts.
  39. */
  40. const STATE_CLEAN = 1;
  41. /**
  42. * A query object is in state DIRTY when it has DQL parts that have not yet been
  43. * parsed/processed. This is automatically defined as DIRTY when addDqlQueryPart
  44. * is called.
  45. */
  46. const STATE_DIRTY = 2;
  47. /* Query HINTS */
  48. /**
  49. * The refresh hint turns any query into a refresh query with the result that
  50. * any local changes in entities are overridden with the fetched values.
  51. *
  52. * @var string
  53. */
  54. const HINT_REFRESH = 'doctrine.refresh';
  55. /**
  56. * Internal hint: is set to the proxy entity that is currently triggered for loading
  57. *
  58. * @var string
  59. */
  60. const HINT_REFRESH_ENTITY = 'doctrine.refresh.entity';
  61. /**
  62. * The forcePartialLoad query hint forces a particular query to return
  63. * partial objects.
  64. *
  65. * @var string
  66. * @todo Rename: HINT_OPTIMIZE
  67. */
  68. const HINT_FORCE_PARTIAL_LOAD = 'doctrine.forcePartialLoad';
  69. /**
  70. * The includeMetaColumns query hint causes meta columns like foreign keys and
  71. * discriminator columns to be selected and returned as part of the query result.
  72. *
  73. * This hint does only apply to non-object queries.
  74. *
  75. * @var string
  76. */
  77. const HINT_INCLUDE_META_COLUMNS = 'doctrine.includeMetaColumns';
  78. /**
  79. * An array of class names that implement \Doctrine\ORM\Query\TreeWalker and
  80. * are iterated and executed after the DQL has been parsed into an AST.
  81. *
  82. * @var string
  83. */
  84. const HINT_CUSTOM_TREE_WALKERS = 'doctrine.customTreeWalkers';
  85. /**
  86. * A string with a class name that implements \Doctrine\ORM\Query\TreeWalker
  87. * and is used for generating the target SQL from any DQL AST tree.
  88. *
  89. * @var string
  90. */
  91. const HINT_CUSTOM_OUTPUT_WALKER = 'doctrine.customOutputWalker';
  92. //const HINT_READ_ONLY = 'doctrine.readOnly';
  93. /**
  94. * @var string
  95. */
  96. const HINT_INTERNAL_ITERATION = 'doctrine.internal.iteration';
  97. /**
  98. * @var string
  99. */
  100. const HINT_LOCK_MODE = 'doctrine.lockMode';
  101. /**
  102. * The current state of this query.
  103. *
  104. * @var integer
  105. */
  106. private $_state = self::STATE_CLEAN;
  107. /**
  108. * Cached DQL query.
  109. *
  110. * @var string
  111. */
  112. private $_dql = null;
  113. /**
  114. * The parser result that holds DQL => SQL information.
  115. *
  116. * @var \Doctrine\ORM\Query\ParserResult
  117. */
  118. private $_parserResult;
  119. /**
  120. * The first result to return (the "offset").
  121. *
  122. * @var integer
  123. */
  124. private $_firstResult = null;
  125. /**
  126. * The maximum number of results to return (the "limit").
  127. *
  128. * @var integer
  129. */
  130. private $_maxResults = null;
  131. /**
  132. * The cache driver used for caching queries.
  133. *
  134. * @var \Doctrine\Common\Cache\Cache|null
  135. */
  136. private $_queryCache;
  137. /**
  138. * Whether or not expire the query cache.
  139. *
  140. * @var boolean
  141. */
  142. private $_expireQueryCache = false;
  143. /**
  144. * The query cache lifetime.
  145. *
  146. * @var int
  147. */
  148. private $_queryCacheTTL;
  149. /**
  150. * Whether to use a query cache, if available. Defaults to TRUE.
  151. *
  152. * @var boolean
  153. */
  154. private $_useQueryCache = true;
  155. /**
  156. * Initializes a new Query instance.
  157. *
  158. * @param \Doctrine\ORM\EntityManager $entityManager
  159. */
  160. /*public function __construct(EntityManager $entityManager)
  161. {
  162. parent::__construct($entityManager);
  163. }*/
  164. /**
  165. * Gets the SQL query/queries that correspond to this DQL query.
  166. *
  167. * @return mixed The built sql query or an array of all sql queries.
  168. *
  169. * @override
  170. */
  171. public function getSQL()
  172. {
  173. return $this->_parse()->getSQLExecutor()->getSQLStatements();
  174. }
  175. /**
  176. * Returns the corresponding AST for this DQL query.
  177. *
  178. * @return \Doctrine\ORM\Query\AST\SelectStatement |
  179. * \Doctrine\ORM\Query\AST\UpdateStatement |
  180. * \Doctrine\ORM\Query\AST\DeleteStatement
  181. */
  182. public function getAST()
  183. {
  184. $parser = new Parser($this);
  185. return $parser->getAST();
  186. }
  187. /**
  188. * Parses the DQL query, if necessary, and stores the parser result.
  189. *
  190. * Note: Populates $this->_parserResult as a side-effect.
  191. *
  192. * @return \Doctrine\ORM\Query\ParserResult
  193. */
  194. private function _parse()
  195. {
  196. // Return previous parser result if the query and the filter collection are both clean
  197. if ($this->_state === self::STATE_CLEAN && $this->_em->isFiltersStateClean()) {
  198. return $this->_parserResult;
  199. }
  200. $this->_state = self::STATE_CLEAN;
  201. // Check query cache.
  202. if ( ! ($this->_useQueryCache && ($queryCache = $this->getQueryCacheDriver()))) {
  203. $parser = new Parser($this);
  204. $this->_parserResult = $parser->parse();
  205. return $this->_parserResult;
  206. }
  207. $hash = $this->_getQueryCacheId();
  208. $cached = $this->_expireQueryCache ? false : $queryCache->fetch($hash);
  209. if ($cached instanceof ParserResult) {
  210. // Cache hit.
  211. $this->_parserResult = $cached;
  212. return $this->_parserResult;
  213. }
  214. // Cache miss.
  215. $parser = new Parser($this);
  216. $this->_parserResult = $parser->parse();
  217. $queryCache->save($hash, $this->_parserResult, $this->_queryCacheTTL);
  218. return $this->_parserResult;
  219. }
  220. /**
  221. * {@inheritdoc}
  222. */
  223. protected function _doExecute()
  224. {
  225. $executor = $this->_parse()->getSqlExecutor();
  226. if ($this->_queryCacheProfile) {
  227. $executor->setQueryCacheProfile($this->_queryCacheProfile);
  228. }
  229. if ($this->_resultSetMapping === null) {
  230. $this->_resultSetMapping = $this->_parserResult->getResultSetMapping();
  231. }
  232. // Prepare parameters
  233. $paramMappings = $this->_parserResult->getParameterMappings();
  234. if (count($paramMappings) != count($this->parameters)) {
  235. throw QueryException::invalidParameterNumber();
  236. }
  237. list($sqlParams, $types) = $this->processParameterMappings($paramMappings);
  238. return $executor->execute($this->_em->getConnection(), $sqlParams, $types);
  239. }
  240. /**
  241. * Processes query parameter mappings.
  242. *
  243. * @param array $paramMappings
  244. *
  245. * @return array
  246. *
  247. * @throws Query\QueryException
  248. */
  249. private function processParameterMappings($paramMappings)
  250. {
  251. $sqlParams = array();
  252. $types = array();
  253. foreach ($this->parameters as $parameter) {
  254. $key = $parameter->getName();
  255. $value = $parameter->getValue();
  256. if ( ! isset($paramMappings[$key])) {
  257. throw QueryException::unknownParameter($key);
  258. }
  259. if (isset($this->_resultSetMapping->metadataParameterMapping[$key]) && $value instanceof ClassMetadata) {
  260. $value = $value->getMetadataValue($this->_resultSetMapping->metadataParameterMapping[$key]);
  261. }
  262. $value = $this->processParameterValue($value);
  263. $type = ($parameter->getValue() === $value)
  264. ? $parameter->getType()
  265. : ParameterTypeInferer::inferType($value);
  266. foreach ($paramMappings[$key] as $position) {
  267. $types[$position] = $type;
  268. }
  269. $sqlPositions = $paramMappings[$key];
  270. // optimized multi value sql positions away for now,
  271. // they are not allowed in DQL anyways.
  272. $value = array($value);
  273. $countValue = count($value);
  274. for ($i = 0, $l = count($sqlPositions); $i < $l; $i++) {
  275. $sqlParams[$sqlPositions[$i]] = $value[($i % $countValue)];
  276. }
  277. }
  278. if (count($sqlParams) != count($types)) {
  279. throw QueryException::parameterTypeMismatch();
  280. }
  281. if ($sqlParams) {
  282. ksort($sqlParams);
  283. $sqlParams = array_values($sqlParams);
  284. ksort($types);
  285. $types = array_values($types);
  286. }
  287. return array($sqlParams, $types);
  288. }
  289. /**
  290. * Defines a cache driver to be used for caching queries.
  291. *
  292. * @param \Doctrine\Common\Cache\Cache|null $queryCache Cache driver.
  293. *
  294. * @return Query This query instance.
  295. */
  296. public function setQueryCacheDriver($queryCache)
  297. {
  298. $this->_queryCache = $queryCache;
  299. return $this;
  300. }
  301. /**
  302. * Defines whether the query should make use of a query cache, if available.
  303. *
  304. * @param boolean $bool
  305. *
  306. * @return Query This query instance.
  307. */
  308. public function useQueryCache($bool)
  309. {
  310. $this->_useQueryCache = $bool;
  311. return $this;
  312. }
  313. /**
  314. * Returns the cache driver used for query caching.
  315. *
  316. * @return \Doctrine\Common\Cache\Cache|null The cache driver used for query caching or NULL, if
  317. * this Query does not use query caching.
  318. */
  319. public function getQueryCacheDriver()
  320. {
  321. if ($this->_queryCache) {
  322. return $this->_queryCache;
  323. }
  324. return $this->_em->getConfiguration()->getQueryCacheImpl();
  325. }
  326. /**
  327. * Defines how long the query cache will be active before expire.
  328. *
  329. * @param integer $timeToLive How long the cache entry is valid.
  330. *
  331. * @return Query This query instance.
  332. */
  333. public function setQueryCacheLifetime($timeToLive)
  334. {
  335. if ($timeToLive !== null) {
  336. $timeToLive = (int) $timeToLive;
  337. }
  338. $this->_queryCacheTTL = $timeToLive;
  339. return $this;
  340. }
  341. /**
  342. * Retrieves the lifetime of resultset cache.
  343. *
  344. * @return int
  345. */
  346. public function getQueryCacheLifetime()
  347. {
  348. return $this->_queryCacheTTL;
  349. }
  350. /**
  351. * Defines if the query cache is active or not.
  352. *
  353. * @param boolean $expire Whether or not to force query cache expiration.
  354. *
  355. * @return Query This query instance.
  356. */
  357. public function expireQueryCache($expire = true)
  358. {
  359. $this->_expireQueryCache = $expire;
  360. return $this;
  361. }
  362. /**
  363. * Retrieves if the query cache is active or not.
  364. *
  365. * @return bool
  366. */
  367. public function getExpireQueryCache()
  368. {
  369. return $this->_expireQueryCache;
  370. }
  371. /**
  372. * @override
  373. */
  374. public function free()
  375. {
  376. parent::free();
  377. $this->_dql = null;
  378. $this->_state = self::STATE_CLEAN;
  379. }
  380. /**
  381. * Sets a DQL query string.
  382. *
  383. * @param string $dqlQuery DQL Query.
  384. *
  385. * @return \Doctrine\ORM\AbstractQuery
  386. */
  387. public function setDQL($dqlQuery)
  388. {
  389. if ($dqlQuery !== null) {
  390. $this->_dql = $dqlQuery;
  391. $this->_state = self::STATE_DIRTY;
  392. }
  393. return $this;
  394. }
  395. /**
  396. * Returns the DQL query that is represented by this query object.
  397. *
  398. * @return string DQL query.
  399. */
  400. public function getDQL()
  401. {
  402. return $this->_dql;
  403. }
  404. /**
  405. * Returns the state of this query object
  406. * By default the type is Doctrine_ORM_Query_Abstract::STATE_CLEAN but if it appears any unprocessed DQL
  407. * part, it is switched to Doctrine_ORM_Query_Abstract::STATE_DIRTY.
  408. *
  409. * @see AbstractQuery::STATE_CLEAN
  410. * @see AbstractQuery::STATE_DIRTY
  411. *
  412. * @return integer The query state.
  413. */
  414. public function getState()
  415. {
  416. return $this->_state;
  417. }
  418. /**
  419. * Method to check if an arbitrary piece of DQL exists
  420. *
  421. * @param string $dql Arbitrary piece of DQL to check for.
  422. *
  423. * @return boolean
  424. */
  425. public function contains($dql)
  426. {
  427. return stripos($this->getDQL(), $dql) === false ? false : true;
  428. }
  429. /**
  430. * Sets the position of the first result to retrieve (the "offset").
  431. *
  432. * @param integer $firstResult The first result to return.
  433. *
  434. * @return Query This query object.
  435. */
  436. public function setFirstResult($firstResult)
  437. {
  438. $this->_firstResult = $firstResult;
  439. $this->_state = self::STATE_DIRTY;
  440. return $this;
  441. }
  442. /**
  443. * Gets the position of the first result the query object was set to retrieve (the "offset").
  444. * Returns NULL if {@link setFirstResult} was not applied to this query.
  445. *
  446. * @return integer The position of the first result.
  447. */
  448. public function getFirstResult()
  449. {
  450. return $this->_firstResult;
  451. }
  452. /**
  453. * Sets the maximum number of results to retrieve (the "limit").
  454. *
  455. * @param integer $maxResults
  456. *
  457. * @return Query This query object.
  458. */
  459. public function setMaxResults($maxResults)
  460. {
  461. $this->_maxResults = $maxResults;
  462. $this->_state = self::STATE_DIRTY;
  463. return $this;
  464. }
  465. /**
  466. * Gets the maximum number of results the query object was set to retrieve (the "limit").
  467. * Returns NULL if {@link setMaxResults} was not applied to this query.
  468. *
  469. * @return integer Maximum number of results.
  470. */
  471. public function getMaxResults()
  472. {
  473. return $this->_maxResults;
  474. }
  475. /**
  476. * Executes the query and returns an IterableResult that can be used to incrementally
  477. * iterated over the result.
  478. *
  479. * @param ArrayCollection|array|null $parameters The query parameters.
  480. * @param integer $hydrationMode The hydration mode to use.
  481. *
  482. * @return \Doctrine\ORM\Internal\Hydration\IterableResult
  483. */
  484. public function iterate($parameters = null, $hydrationMode = self::HYDRATE_OBJECT)
  485. {
  486. $this->setHint(self::HINT_INTERNAL_ITERATION, true);
  487. return parent::iterate($parameters, $hydrationMode);
  488. }
  489. /**
  490. * {@inheritdoc}
  491. */
  492. public function setHint($name, $value)
  493. {
  494. $this->_state = self::STATE_DIRTY;
  495. return parent::setHint($name, $value);
  496. }
  497. /**
  498. * {@inheritdoc}
  499. */
  500. public function setHydrationMode($hydrationMode)
  501. {
  502. $this->_state = self::STATE_DIRTY;
  503. return parent::setHydrationMode($hydrationMode);
  504. }
  505. /**
  506. * Set the lock mode for this Query.
  507. *
  508. * @see \Doctrine\DBAL\LockMode
  509. *
  510. * @param int $lockMode
  511. *
  512. * @return Query
  513. *
  514. * @throws TransactionRequiredException
  515. */
  516. public function setLockMode($lockMode)
  517. {
  518. if (in_array($lockMode, array(LockMode::PESSIMISTIC_READ, LockMode::PESSIMISTIC_WRITE))) {
  519. if ( ! $this->_em->getConnection()->isTransactionActive()) {
  520. throw TransactionRequiredException::transactionRequired();
  521. }
  522. }
  523. $this->setHint(self::HINT_LOCK_MODE, $lockMode);
  524. return $this;
  525. }
  526. /**
  527. * Get the current lock mode for this query.
  528. *
  529. * @return int
  530. */
  531. public function getLockMode()
  532. {
  533. $lockMode = $this->getHint(self::HINT_LOCK_MODE);
  534. if ( ! $lockMode) {
  535. return LockMode::NONE;
  536. }
  537. return $lockMode;
  538. }
  539. /**
  540. * Generate a cache id for the query cache - reusing the Result-Cache-Id generator.
  541. *
  542. * The query cache
  543. *
  544. * @return string
  545. */
  546. protected function _getQueryCacheId()
  547. {
  548. ksort($this->_hints);
  549. return md5(
  550. $this->getDql() . var_export($this->_hints, true) .
  551. ($this->_em->hasFilters() ? $this->_em->getFilters()->getHash() : '') .
  552. '&firstResult=' . $this->_firstResult . '&maxResult=' . $this->_maxResults .
  553. '&hydrationMode='.$this->_hydrationMode.'DOCTRINE_QUERY_CACHE_SALT'
  554. );
  555. }
  556. /**
  557. * Cleanup Query resource when clone is called.
  558. *
  559. * @return void
  560. */
  561. public function __clone()
  562. {
  563. parent::__clone();
  564. $this->_state = self::STATE_DIRTY;
  565. }
  566. }