Query.php 17KB

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