Query.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the LGPL. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\ORM;
  20. use Doctrine\DBAL\LockMode,
  21. Doctrine\ORM\Query\Parser,
  22. Doctrine\ORM\Query\ParserResult,
  23. Doctrine\ORM\Query\QueryException;
  24. /**
  25. * A Query object represents a DQL query.
  26. *
  27. * @since 1.0
  28. * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
  29. * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
  30. * @author Roman Borschel <roman@code-factory.org>
  31. */
  32. final class Query extends AbstractQuery
  33. {
  34. /* Query STATES */
  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. // End of Caching Stuff
  136. /**
  137. * Initializes a new Query instance.
  138. *
  139. * @param \Doctrine\ORM\EntityManager $entityManager
  140. */
  141. /*public function __construct(EntityManager $entityManager)
  142. {
  143. parent::__construct($entityManager);
  144. }*/
  145. /**
  146. * Gets the SQL query/queries that correspond to this DQL query.
  147. *
  148. * @return mixed The built sql query or an array of all sql queries.
  149. * @override
  150. */
  151. public function getSQL()
  152. {
  153. return $this->_parse()->getSQLExecutor()->getSQLStatements();
  154. }
  155. /**
  156. * Returns the corresponding AST for this DQL query.
  157. *
  158. * @return \Doctrine\ORM\Query\AST\SelectStatement |
  159. * \Doctrine\ORM\Query\AST\UpdateStatement |
  160. * \Doctrine\ORM\Query\AST\DeleteStatement
  161. */
  162. public function getAST()
  163. {
  164. $parser = new Parser($this);
  165. return $parser->getAST();
  166. }
  167. /**
  168. * Parses the DQL query, if necessary, and stores the parser result.
  169. *
  170. * Note: Populates $this->_parserResult as a side-effect.
  171. *
  172. * @return \Doctrine\ORM\Query\ParserResult
  173. */
  174. private function _parse()
  175. {
  176. // Return previous parser result if the query and the filter collection are both clean
  177. if ($this->_state === self::STATE_CLEAN
  178. && $this->_em->isFiltersStateClean()
  179. ) {
  180. return $this->_parserResult;
  181. }
  182. $this->_state = self::STATE_CLEAN;
  183. // Check query cache.
  184. if ( ! ($this->_useQueryCache && ($queryCache = $this->getQueryCacheDriver()))) {
  185. $parser = new Parser($this);
  186. $this->_parserResult = $parser->parse();
  187. return $this->_parserResult;
  188. }
  189. $hash = $this->_getQueryCacheId();
  190. $cached = $this->_expireQueryCache ? false : $queryCache->fetch($hash);
  191. if ($cached instanceof ParserResult) {
  192. // Cache hit.
  193. $this->_parserResult = $cached;
  194. return $this->_parserResult;
  195. }
  196. // Cache miss.
  197. $parser = new Parser($this);
  198. $this->_parserResult = $parser->parse();
  199. $queryCache->save($hash, $this->_parserResult, $this->_queryCacheTTL);
  200. return $this->_parserResult;
  201. }
  202. /**
  203. * {@inheritdoc}
  204. */
  205. protected function _doExecute()
  206. {
  207. $executor = $this->_parse()->getSqlExecutor();
  208. if ($this->_queryCacheProfile) {
  209. $executor->setQueryCacheProfile($this->_queryCacheProfile);
  210. }
  211. // Prepare parameters
  212. $paramMappings = $this->_parserResult->getParameterMappings();
  213. if (count($paramMappings) != count($this->_params)) {
  214. throw QueryException::invalidParameterNumber();
  215. }
  216. list($sqlParams, $types) = $this->processParameterMappings($paramMappings);
  217. if ($this->_resultSetMapping === null) {
  218. $this->_resultSetMapping = $this->_parserResult->getResultSetMapping();
  219. }
  220. return $executor->execute($this->_em->getConnection(), $sqlParams, $types);
  221. }
  222. /**
  223. * Processes query parameter mappings
  224. *
  225. * @param array $paramMappings
  226. * @return array
  227. */
  228. private function processParameterMappings($paramMappings)
  229. {
  230. $sqlParams = $types = array();
  231. foreach ($this->_params as $key => $value) {
  232. if ( ! isset($paramMappings[$key])) {
  233. throw QueryException::unknownParameter($key);
  234. }
  235. if (isset($this->_paramTypes[$key])) {
  236. foreach ($paramMappings[$key] as $position) {
  237. $types[$position] = $this->_paramTypes[$key];
  238. }
  239. }
  240. $sqlPositions = $paramMappings[$key];
  241. // optimized multi value sql positions away for now, they are not allowed in DQL anyways.
  242. $value = array($value);
  243. $countValue = count($value);
  244. for ($i = 0, $l = count($sqlPositions); $i < $l; $i++) {
  245. $sqlParams[$sqlPositions[$i]] = $value[($i % $countValue)];
  246. }
  247. }
  248. if (count($sqlParams) != count($types)) {
  249. throw QueryException::parameterTypeMissmatch();
  250. }
  251. if ($sqlParams) {
  252. ksort($sqlParams);
  253. $sqlParams = array_values($sqlParams);
  254. ksort($types);
  255. $types = array_values($types);
  256. }
  257. return array($sqlParams, $types);
  258. }
  259. /**
  260. * Defines a cache driver to be used for caching queries.
  261. *
  262. * @param Doctrine_Cache_Interface|null $driver Cache driver
  263. * @return Query This query instance.
  264. */
  265. public function setQueryCacheDriver($queryCache)
  266. {
  267. $this->_queryCache = $queryCache;
  268. return $this;
  269. }
  270. /**
  271. * Defines whether the query should make use of a query cache, if available.
  272. *
  273. * @param boolean $bool
  274. * @return @return Query This query instance.
  275. */
  276. public function useQueryCache($bool)
  277. {
  278. $this->_useQueryCache = $bool;
  279. return $this;
  280. }
  281. /**
  282. * Returns the cache driver used for query caching.
  283. *
  284. * @return CacheDriver The cache driver used for query caching or NULL, if this
  285. * Query does not use query caching.
  286. */
  287. public function getQueryCacheDriver()
  288. {
  289. if ($this->_queryCache) {
  290. return $this->_queryCache;
  291. }
  292. return $this->_em->getConfiguration()->getQueryCacheImpl();
  293. }
  294. /**
  295. * Defines how long the query cache will be active before expire.
  296. *
  297. * @param integer $timeToLive How long the cache entry is valid
  298. * @return Query This query instance.
  299. */
  300. public function setQueryCacheLifetime($timeToLive)
  301. {
  302. if ($timeToLive !== null) {
  303. $timeToLive = (int) $timeToLive;
  304. }
  305. $this->_queryCacheTTL = $timeToLive;
  306. return $this;
  307. }
  308. /**
  309. * Retrieves the lifetime of resultset cache.
  310. *
  311. * @return int
  312. */
  313. public function getQueryCacheLifetime()
  314. {
  315. return $this->_queryCacheTTL;
  316. }
  317. /**
  318. * Defines if the query cache is active or not.
  319. *
  320. * @param boolean $expire Whether or not to force query cache expiration.
  321. * @return Query This query instance.
  322. */
  323. public function expireQueryCache($expire = true)
  324. {
  325. $this->_expireQueryCache = $expire;
  326. return $this;
  327. }
  328. /**
  329. * Retrieves if the query cache is active or not.
  330. *
  331. * @return bool
  332. */
  333. public function getExpireQueryCache()
  334. {
  335. return $this->_expireQueryCache;
  336. }
  337. /**
  338. * @override
  339. */
  340. public function free()
  341. {
  342. parent::free();
  343. $this->_dql = null;
  344. $this->_state = self::STATE_CLEAN;
  345. }
  346. /**
  347. * Sets a DQL query string.
  348. *
  349. * @param string $dqlQuery DQL Query
  350. * @return \Doctrine\ORM\AbstractQuery
  351. */
  352. public function setDQL($dqlQuery)
  353. {
  354. if ($dqlQuery !== null) {
  355. $this->_dql = $dqlQuery;
  356. $this->_state = self::STATE_DIRTY;
  357. }
  358. return $this;
  359. }
  360. /**
  361. * Returns the DQL query that is represented by this query object.
  362. *
  363. * @return string DQL query
  364. */
  365. public function getDQL()
  366. {
  367. return $this->_dql;
  368. }
  369. /**
  370. * Returns the state of this query object
  371. * By default the type is Doctrine_ORM_Query_Abstract::STATE_CLEAN but if it appears any unprocessed DQL
  372. * part, it is switched to Doctrine_ORM_Query_Abstract::STATE_DIRTY.
  373. *
  374. * @see AbstractQuery::STATE_CLEAN
  375. * @see AbstractQuery::STATE_DIRTY
  376. *
  377. * @return integer Return the query state
  378. */
  379. public function getState()
  380. {
  381. return $this->_state;
  382. }
  383. /**
  384. * Method to check if an arbitrary piece of DQL exists
  385. *
  386. * @param string $dql Arbitrary piece of DQL to check for
  387. * @return boolean
  388. */
  389. public function contains($dql)
  390. {
  391. return stripos($this->getDQL(), $dql) === false ? false : true;
  392. }
  393. /**
  394. * Sets the position of the first result to retrieve (the "offset").
  395. *
  396. * @param integer $firstResult The first result to return.
  397. * @return Query This query object.
  398. */
  399. public function setFirstResult($firstResult)
  400. {
  401. $this->_firstResult = $firstResult;
  402. $this->_state = self::STATE_DIRTY;
  403. return $this;
  404. }
  405. /**
  406. * Gets the position of the first result the query object was set to retrieve (the "offset").
  407. * Returns NULL if {@link setFirstResult} was not applied to this query.
  408. *
  409. * @return integer The position of the first result.
  410. */
  411. public function getFirstResult()
  412. {
  413. return $this->_firstResult;
  414. }
  415. /**
  416. * Sets the maximum number of results to retrieve (the "limit").
  417. *
  418. * @param integer $maxResults
  419. * @return Query This query object.
  420. */
  421. public function setMaxResults($maxResults)
  422. {
  423. $this->_maxResults = $maxResults;
  424. $this->_state = self::STATE_DIRTY;
  425. return $this;
  426. }
  427. /**
  428. * Gets the maximum number of results the query object was set to retrieve (the "limit").
  429. * Returns NULL if {@link setMaxResults} was not applied to this query.
  430. *
  431. * @return integer Maximum number of results.
  432. */
  433. public function getMaxResults()
  434. {
  435. return $this->_maxResults;
  436. }
  437. /**
  438. * Executes the query and returns an IterableResult that can be used to incrementally
  439. * iterated over the result.
  440. *
  441. * @param array $params The query parameters.
  442. * @param integer $hydrationMode The hydration mode to use.
  443. * @return \Doctrine\ORM\Internal\Hydration\IterableResult
  444. */
  445. public function iterate(array $params = array(), $hydrationMode = self::HYDRATE_OBJECT)
  446. {
  447. $this->setHint(self::HINT_INTERNAL_ITERATION, true);
  448. return parent::iterate($params, $hydrationMode);
  449. }
  450. /**
  451. * {@inheritdoc}
  452. */
  453. public function setHint($name, $value)
  454. {
  455. $this->_state = self::STATE_DIRTY;
  456. return parent::setHint($name, $value);
  457. }
  458. /**
  459. * {@inheritdoc}
  460. */
  461. public function setHydrationMode($hydrationMode)
  462. {
  463. $this->_state = self::STATE_DIRTY;
  464. return parent::setHydrationMode($hydrationMode);
  465. }
  466. /**
  467. * Set the lock mode for this Query.
  468. *
  469. * @see \Doctrine\DBAL\LockMode
  470. * @param int $lockMode
  471. * @return Query
  472. */
  473. public function setLockMode($lockMode)
  474. {
  475. if ($lockMode === LockMode::PESSIMISTIC_READ || $lockMode === LockMode::PESSIMISTIC_WRITE) {
  476. if ( ! $this->_em->getConnection()->isTransactionActive()) {
  477. throw TransactionRequiredException::transactionRequired();
  478. }
  479. }
  480. $this->setHint(self::HINT_LOCK_MODE, $lockMode);
  481. return $this;
  482. }
  483. /**
  484. * Get the current lock mode for this query.
  485. *
  486. * @return int
  487. */
  488. public function getLockMode()
  489. {
  490. $lockMode = $this->getHint(self::HINT_LOCK_MODE);
  491. if ( ! $lockMode) {
  492. return LockMode::NONE;
  493. }
  494. return $lockMode;
  495. }
  496. /**
  497. * Generate a cache id for the query cache - reusing the Result-Cache-Id generator.
  498. *
  499. * The query cache
  500. *
  501. * @return string
  502. */
  503. protected function _getQueryCacheId()
  504. {
  505. ksort($this->_hints);
  506. return md5(
  507. $this->getDql() . var_export($this->_hints, true) .
  508. ($this->_em->hasFilters() ? $this->_em->getFilters()->getHash() : '') .
  509. '&firstResult=' . $this->_firstResult . '&maxResult=' . $this->_maxResults .
  510. '&hydrationMode='.$this->_hydrationMode.'DOCTRINE_QUERY_CACHE_SALT'
  511. );
  512. }
  513. /**
  514. * Cleanup Query resource when clone is called.
  515. *
  516. * @return void
  517. */
  518. public function __clone()
  519. {
  520. parent::__clone();
  521. $this->_state = self::STATE_DIRTY;
  522. }
  523. }