Query.php 17KB

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