Query.php 16 KB

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