Query.php 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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. if ($this->_state === self::STATE_CLEAN) {
  176. return $this->_parserResult;
  177. }
  178. // Check query cache.
  179. if ($this->_useQueryCache && ($queryCache = $this->getQueryCacheDriver())) {
  180. $hash = $this->_getQueryCacheId();
  181. $cached = $this->_expireQueryCache ? false : $queryCache->fetch($hash);
  182. if ($cached === false) {
  183. // Cache miss.
  184. $parser = new Parser($this);
  185. $this->_parserResult = $parser->parse();
  186. $queryCache->save($hash, $this->_parserResult, $this->_queryCacheTTL);
  187. } else {
  188. // Cache hit.
  189. $this->_parserResult = $cached;
  190. }
  191. } else {
  192. $parser = new Parser($this);
  193. $this->_parserResult = $parser->parse();
  194. }
  195. $this->_state = self::STATE_CLEAN;
  196. return $this->_parserResult;
  197. }
  198. /**
  199. * {@inheritdoc}
  200. */
  201. protected function _doExecute()
  202. {
  203. $executor = $this->_parse()->getSqlExecutor();
  204. // Prepare parameters
  205. $paramMappings = $this->_parserResult->getParameterMappings();
  206. if (count($paramMappings) != count($this->_params)) {
  207. throw QueryException::invalidParameterNumber();
  208. }
  209. $sqlParams = $types = array();
  210. foreach ($this->_params as $key => $value) {
  211. if ( ! isset($paramMappings[$key])) {
  212. throw QueryException::unknownParameter($key);
  213. }
  214. if (isset($this->_paramTypes[$key])) {
  215. foreach ($paramMappings[$key] as $position) {
  216. $types[$position] = $this->_paramTypes[$key];
  217. }
  218. }
  219. if (is_object($value) && $this->_em->getMetadataFactory()->hasMetadataFor(get_class($value))) {
  220. if ($this->_em->getUnitOfWork()->getEntityState($value) == UnitOfWork::STATE_MANAGED) {
  221. $idValues = $this->_em->getUnitOfWork()->getEntityIdentifier($value);
  222. } else {
  223. $class = $this->_em->getClassMetadata(get_class($value));
  224. $idValues = $class->getIdentifierValues($value);
  225. }
  226. $sqlPositions = $paramMappings[$key];
  227. $cSqlPos = count($sqlPositions);
  228. $cIdValues = count($idValues);
  229. $idValues = array_values($idValues);
  230. for ($i = 0; $i < $cSqlPos; $i++) {
  231. $sqlParams[$sqlPositions[$i]] = $idValues[ ($i % $cIdValues) ];
  232. }
  233. } else {
  234. foreach ($paramMappings[$key] as $position) {
  235. $sqlParams[$position] = $value;
  236. }
  237. }
  238. }
  239. if ($sqlParams) {
  240. ksort($sqlParams);
  241. $sqlParams = array_values($sqlParams);
  242. }
  243. if ($this->_resultSetMapping === null) {
  244. $this->_resultSetMapping = $this->_parserResult->getResultSetMapping();
  245. }
  246. return $executor->execute($this->_em->getConnection(), $sqlParams, $types);
  247. }
  248. /**
  249. * Defines a cache driver to be used for caching queries.
  250. *
  251. * @param Doctrine_Cache_Interface|null $driver Cache driver
  252. * @return Query This query instance.
  253. */
  254. public function setQueryCacheDriver($queryCache)
  255. {
  256. $this->_queryCache = $queryCache;
  257. return $this;
  258. }
  259. /**
  260. * Defines whether the query should make use of a query cache, if available.
  261. *
  262. * @param boolean $bool
  263. * @return @return Query This query instance.
  264. */
  265. public function useQueryCache($bool)
  266. {
  267. $this->_useQueryCache = $bool;
  268. return $this;
  269. }
  270. /**
  271. * Returns the cache driver used for query caching.
  272. *
  273. * @return CacheDriver The cache driver used for query caching or NULL, if this
  274. * Query does not use query caching.
  275. */
  276. public function getQueryCacheDriver()
  277. {
  278. if ($this->_queryCache) {
  279. return $this->_queryCache;
  280. } else {
  281. return $this->_em->getConfiguration()->getQueryCacheImpl();
  282. }
  283. }
  284. /**
  285. * Defines how long the query cache will be active before expire.
  286. *
  287. * @param integer $timeToLive How long the cache entry is valid
  288. * @return Query This query instance.
  289. */
  290. public function setQueryCacheLifetime($timeToLive)
  291. {
  292. if ($timeToLive !== null) {
  293. $timeToLive = (int) $timeToLive;
  294. }
  295. $this->_queryCacheTTL = $timeToLive;
  296. return $this;
  297. }
  298. /**
  299. * Retrieves the lifetime of resultset cache.
  300. *
  301. * @return int
  302. */
  303. public function getQueryCacheLifetime()
  304. {
  305. return $this->_queryCacheTTL;
  306. }
  307. /**
  308. * Defines if the query cache is active or not.
  309. *
  310. * @param boolean $expire Whether or not to force query cache expiration.
  311. * @return Query This query instance.
  312. */
  313. public function expireQueryCache($expire = true)
  314. {
  315. $this->_expireQueryCache = $expire;
  316. return $this;
  317. }
  318. /**
  319. * Retrieves if the query cache is active or not.
  320. *
  321. * @return bool
  322. */
  323. public function getExpireQueryCache()
  324. {
  325. return $this->_expireQueryCache;
  326. }
  327. /**
  328. * @override
  329. */
  330. public function free()
  331. {
  332. parent::free();
  333. $this->_dql = null;
  334. $this->_state = self::STATE_CLEAN;
  335. }
  336. /**
  337. * Sets a DQL query string.
  338. *
  339. * @param string $dqlQuery DQL Query
  340. * @return Doctrine\ORM\AbstractQuery
  341. */
  342. public function setDQL($dqlQuery)
  343. {
  344. if ($dqlQuery !== null) {
  345. $this->_dql = $dqlQuery;
  346. $this->_state = self::STATE_DIRTY;
  347. }
  348. return $this;
  349. }
  350. /**
  351. * Returns the DQL query that is represented by this query object.
  352. *
  353. * @return string DQL query
  354. */
  355. public function getDQL()
  356. {
  357. return $this->_dql;
  358. }
  359. /**
  360. * Returns the state of this query object
  361. * By default the type is Doctrine_ORM_Query_Abstract::STATE_CLEAN but if it appears any unprocessed DQL
  362. * part, it is switched to Doctrine_ORM_Query_Abstract::STATE_DIRTY.
  363. *
  364. * @see AbstractQuery::STATE_CLEAN
  365. * @see AbstractQuery::STATE_DIRTY
  366. *
  367. * @return integer Return the query state
  368. */
  369. public function getState()
  370. {
  371. return $this->_state;
  372. }
  373. /**
  374. * Method to check if an arbitrary piece of DQL exists
  375. *
  376. * @param string $dql Arbitrary piece of DQL to check for
  377. * @return boolean
  378. */
  379. public function contains($dql)
  380. {
  381. return stripos($this->getDQL(), $dql) === false ? false : true;
  382. }
  383. /**
  384. * Sets the position of the first result to retrieve (the "offset").
  385. *
  386. * @param integer $firstResult The first result to return.
  387. * @return Query This query object.
  388. */
  389. public function setFirstResult($firstResult)
  390. {
  391. $this->_firstResult = $firstResult;
  392. $this->_state = self::STATE_DIRTY;
  393. return $this;
  394. }
  395. /**
  396. * Gets the position of the first result the query object was set to retrieve (the "offset").
  397. * Returns NULL if {@link setFirstResult} was not applied to this query.
  398. *
  399. * @return integer The position of the first result.
  400. */
  401. public function getFirstResult()
  402. {
  403. return $this->_firstResult;
  404. }
  405. /**
  406. * Sets the maximum number of results to retrieve (the "limit").
  407. *
  408. * @param integer $maxResults
  409. * @return Query This query object.
  410. */
  411. public function setMaxResults($maxResults)
  412. {
  413. $this->_maxResults = $maxResults;
  414. $this->_state = self::STATE_DIRTY;
  415. return $this;
  416. }
  417. /**
  418. * Gets the maximum number of results the query object was set to retrieve (the "limit").
  419. * Returns NULL if {@link setMaxResults} was not applied to this query.
  420. *
  421. * @return integer Maximum number of results.
  422. */
  423. public function getMaxResults()
  424. {
  425. return $this->_maxResults;
  426. }
  427. /**
  428. * Executes the query and returns an IterableResult that can be used to incrementally
  429. * iterated over the result.
  430. *
  431. * @param array $params The query parameters.
  432. * @param integer $hydrationMode The hydration mode to use.
  433. * @return IterableResult
  434. */
  435. public function iterate(array $params = array(), $hydrationMode = self::HYDRATE_OBJECT)
  436. {
  437. $this->setHint(self::HINT_INTERNAL_ITERATION, true);
  438. return parent::iterate($params, $hydrationMode);
  439. }
  440. /**
  441. * {@inheritdoc}
  442. */
  443. public function setHint($name, $value)
  444. {
  445. $this->_state = self::STATE_DIRTY;
  446. return parent::setHint($name, $value);
  447. }
  448. /**
  449. * {@inheritdoc}
  450. */
  451. public function setHydrationMode($hydrationMode)
  452. {
  453. $this->_state = self::STATE_DIRTY;
  454. return parent::setHydrationMode($hydrationMode);
  455. }
  456. /**
  457. * Set the lock mode for this Query.
  458. *
  459. * @see Doctrine\DBAL\LockMode
  460. * @param int $lockMode
  461. * @return Query
  462. */
  463. public function setLockMode($lockMode)
  464. {
  465. if ($lockMode == LockMode::PESSIMISTIC_READ || $lockMode == LockMode::PESSIMISTIC_WRITE) {
  466. if (!$this->_em->getConnection()->isTransactionActive()) {
  467. throw TransactionRequiredException::transactionRequired();
  468. }
  469. }
  470. $this->setHint(self::HINT_LOCK_MODE, $lockMode);
  471. return $this;
  472. }
  473. /**
  474. * Get the current lock mode for this query.
  475. *
  476. * @return int
  477. */
  478. public function getLockMode()
  479. {
  480. $lockMode = $this->getHint(self::HINT_LOCK_MODE);
  481. if (!$lockMode) {
  482. return LockMode::NONE;
  483. }
  484. return $lockMode;
  485. }
  486. /**
  487. * Generate a cache id for the query cache - reusing the Result-Cache-Id generator.
  488. *
  489. * The query cache
  490. *
  491. * @return string
  492. */
  493. protected function _getQueryCacheId()
  494. {
  495. ksort($this->_hints);
  496. return md5(
  497. $this->getDql() . var_export($this->_hints, true) .
  498. '&firstResult=' . $this->_firstResult . '&maxResult=' . $this->_maxResults .
  499. '&hydrationMode='.$this->_hydrationMode.'DOCTRINE_QUERY_CACHE_SALT'
  500. );
  501. }
  502. /**
  503. * Cleanup Query resource when clone is called.
  504. *
  505. * @return void
  506. */
  507. public function __clone()
  508. {
  509. parent::__clone();
  510. $this->_state = self::STATE_DIRTY;
  511. }
  512. }