AbstractQuery.php 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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\Types\Type,
  21. Doctrine\ORM\Query\QueryException;
  22. /**
  23. * Base contract for ORM queries. Base class for Query and NativeQuery.
  24. *
  25. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  26. * @link www.doctrine-project.org
  27. * @since 2.0
  28. * @version $Revision$
  29. * @author Benjamin Eberlei <kontakt@beberlei.de>
  30. * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
  31. * @author Jonathan Wage <jonwage@gmail.com>
  32. * @author Roman Borschel <roman@code-factory.org>
  33. * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
  34. */
  35. abstract class AbstractQuery
  36. {
  37. /* Hydration mode constants */
  38. /**
  39. * Hydrates an object graph. This is the default behavior.
  40. */
  41. const HYDRATE_OBJECT = 1;
  42. /**
  43. * Hydrates an array graph.
  44. */
  45. const HYDRATE_ARRAY = 2;
  46. /**
  47. * Hydrates a flat, rectangular result set with scalar values.
  48. */
  49. const HYDRATE_SCALAR = 3;
  50. /**
  51. * Hydrates a single scalar value.
  52. */
  53. const HYDRATE_SINGLE_SCALAR = 4;
  54. /**
  55. * Very simple object hydrator (optimized for performance).
  56. */
  57. const HYDRATE_SIMPLEOBJECT = 5;
  58. /**
  59. * @var array The parameter map of this query.
  60. */
  61. protected $_params = array();
  62. /**
  63. * @var array The parameter type map of this query.
  64. */
  65. protected $_paramTypes = array();
  66. /**
  67. * @var ResultSetMapping The user-specified ResultSetMapping to use.
  68. */
  69. protected $_resultSetMapping;
  70. /**
  71. * @var \Doctrine\ORM\EntityManager The entity manager used by this query object.
  72. */
  73. protected $_em;
  74. /**
  75. * @var array The map of query hints.
  76. */
  77. protected $_hints = array();
  78. /**
  79. * @var integer The hydration mode.
  80. */
  81. protected $_hydrationMode = self::HYDRATE_OBJECT;
  82. /**
  83. * The locally set cache driver used for caching result sets of this query.
  84. *
  85. * @var CacheDriver
  86. */
  87. protected $_resultCacheDriver;
  88. /**
  89. * Boolean flag for whether or not to cache the results of this query.
  90. *
  91. * @var boolean
  92. */
  93. protected $_useResultCache;
  94. /**
  95. * @var string The id to store the result cache entry under.
  96. */
  97. protected $_resultCacheId;
  98. /**
  99. * @var boolean Boolean value that indicates whether or not expire the result cache.
  100. */
  101. protected $_expireResultCache = false;
  102. /**
  103. * @var int Result Cache lifetime.
  104. */
  105. protected $_resultCacheTTL;
  106. /**
  107. * Initializes a new instance of a class derived from <tt>AbstractQuery</tt>.
  108. *
  109. * @param \Doctrine\ORM\EntityManager $entityManager
  110. */
  111. public function __construct(EntityManager $em)
  112. {
  113. $this->_em = $em;
  114. }
  115. /**
  116. * Retrieves the associated EntityManager of this Query instance.
  117. *
  118. * @return \Doctrine\ORM\EntityManager
  119. */
  120. public function getEntityManager()
  121. {
  122. return $this->_em;
  123. }
  124. /**
  125. * Frees the resources used by the query object.
  126. *
  127. * Resets Parameters, Parameter Types and Query Hints.
  128. *
  129. * @return void
  130. */
  131. public function free()
  132. {
  133. $this->_params = array();
  134. $this->_paramTypes = array();
  135. $this->_hints = array();
  136. }
  137. /**
  138. * Get all defined parameters.
  139. *
  140. * @return array The defined query parameters.
  141. */
  142. public function getParameters()
  143. {
  144. return $this->_params;
  145. }
  146. /**
  147. * Get all defined parameter types.
  148. *
  149. * @return array The defined query parameter types.
  150. */
  151. public function getParameterTypes()
  152. {
  153. return $this->_paramTypes;
  154. }
  155. /**
  156. * Gets a query parameter.
  157. *
  158. * @param mixed $key The key (index or name) of the bound parameter.
  159. * @return mixed The value of the bound parameter.
  160. */
  161. public function getParameter($key)
  162. {
  163. return isset($this->_params[$key]) ? $this->_params[$key] : null;
  164. }
  165. /**
  166. * Gets a query parameter type.
  167. *
  168. * @param mixed $key The key (index or name) of the bound parameter.
  169. * @return mixed The parameter type of the bound parameter.
  170. */
  171. public function getParameterType($key)
  172. {
  173. return isset($this->_paramTypes[$key]) ? $this->_paramTypes[$key] : null;
  174. }
  175. /**
  176. * Gets the SQL query that corresponds to this query object.
  177. * The returned SQL syntax depends on the connection driver that is used
  178. * by this query object at the time of this method call.
  179. *
  180. * @return string SQL query
  181. */
  182. abstract public function getSQL();
  183. /**
  184. * Sets a query parameter.
  185. *
  186. * @param string|integer $key The parameter position or name.
  187. * @param mixed $value The parameter value.
  188. * @param string $type The parameter type. If specified, the given value will be run through
  189. * the type conversion of this type. This is usually not needed for
  190. * strings and numeric types.
  191. * @return \Doctrine\ORM\AbstractQuery This query instance.
  192. */
  193. public function setParameter($key, $value, $type = null)
  194. {
  195. if ($type === null) {
  196. $type = Query\ParameterTypeInferer::inferType($value);
  197. }
  198. $this->_paramTypes[$key] = $type;
  199. $this->_params[$key] = $value;
  200. return $this;
  201. }
  202. /**
  203. * Sets a collection of query parameters.
  204. *
  205. * @param array $params
  206. * @param array $types
  207. * @return \Doctrine\ORM\AbstractQuery This query instance.
  208. */
  209. public function setParameters(array $params, array $types = array())
  210. {
  211. foreach ($params as $key => $value) {
  212. if (isset($types[$key])) {
  213. $this->setParameter($key, $value, $types[$key]);
  214. } else {
  215. $this->setParameter($key, $value);
  216. }
  217. }
  218. return $this;
  219. }
  220. /**
  221. * Sets the ResultSetMapping that should be used for hydration.
  222. *
  223. * @param ResultSetMapping $rsm
  224. * @return \Doctrine\ORM\AbstractQuery
  225. */
  226. public function setResultSetMapping(Query\ResultSetMapping $rsm)
  227. {
  228. $this->_resultSetMapping = $rsm;
  229. return $this;
  230. }
  231. /**
  232. * Defines a cache driver to be used for caching result sets.
  233. *
  234. * @param \Doctrine\Common\Cache\Cache $driver Cache driver
  235. * @return \Doctrine\ORM\AbstractQuery
  236. */
  237. public function setResultCacheDriver($resultCacheDriver = null)
  238. {
  239. if ($resultCacheDriver !== null && ! ($resultCacheDriver instanceof \Doctrine\Common\Cache\Cache)) {
  240. throw ORMException::invalidResultCacheDriver();
  241. }
  242. $this->_resultCacheDriver = $resultCacheDriver;
  243. if ($resultCacheDriver) {
  244. $this->_useResultCache = true;
  245. }
  246. return $this;
  247. }
  248. /**
  249. * Returns the cache driver used for caching result sets.
  250. *
  251. * @return \Doctrine\Common\Cache\Cache Cache driver
  252. */
  253. public function getResultCacheDriver()
  254. {
  255. if ($this->_resultCacheDriver) {
  256. return $this->_resultCacheDriver;
  257. } else {
  258. return $this->_em->getConfiguration()->getResultCacheImpl();
  259. }
  260. }
  261. /**
  262. * Set whether or not to cache the results of this query and if so, for
  263. * how long and which ID to use for the cache entry.
  264. *
  265. * @param boolean $bool
  266. * @param integer $timeToLive
  267. * @param string $resultCacheId
  268. * @return \Doctrine\ORM\AbstractQuery This query instance.
  269. */
  270. public function useResultCache($bool, $timeToLive = null, $resultCacheId = null)
  271. {
  272. $this->_useResultCache = $bool;
  273. if ($timeToLive) {
  274. $this->setResultCacheLifetime($timeToLive);
  275. }
  276. if ($resultCacheId) {
  277. $this->_resultCacheId = $resultCacheId;
  278. }
  279. return $this;
  280. }
  281. /**
  282. * Defines how long the result cache will be active before expire.
  283. *
  284. * @param integer $timeToLive How long the cache entry is valid.
  285. * @return \Doctrine\ORM\AbstractQuery This query instance.
  286. */
  287. public function setResultCacheLifetime($timeToLive)
  288. {
  289. if ($timeToLive !== null) {
  290. $timeToLive = (int) $timeToLive;
  291. }
  292. $this->_resultCacheTTL = $timeToLive;
  293. return $this;
  294. }
  295. /**
  296. * Retrieves the lifetime of resultset cache.
  297. *
  298. * @return integer
  299. */
  300. public function getResultCacheLifetime()
  301. {
  302. return $this->_resultCacheTTL;
  303. }
  304. /**
  305. * Defines if the result cache is active or not.
  306. *
  307. * @param boolean $expire Whether or not to force resultset cache expiration.
  308. * @return \Doctrine\ORM\AbstractQuery This query instance.
  309. */
  310. public function expireResultCache($expire = true)
  311. {
  312. $this->_expireResultCache = $expire;
  313. return $this;
  314. }
  315. /**
  316. * Retrieves if the resultset cache is active or not.
  317. *
  318. * @return boolean
  319. */
  320. public function getExpireResultCache()
  321. {
  322. return $this->_expireResultCache;
  323. }
  324. /**
  325. * Change the default fetch mode of an association for this query.
  326. *
  327. * $fetchMode can be one of ClassMetadata::FETCH_EAGER or ClassMetadata::FETCH_LAZY
  328. *
  329. * @param string $class
  330. * @param string $assocName
  331. * @param int $fetchMode
  332. * @return AbstractQuery
  333. */
  334. public function setFetchMode($class, $assocName, $fetchMode)
  335. {
  336. if ($fetchMode !== Mapping\ClassMetadata::FETCH_EAGER) {
  337. $fetchMode = Mapping\ClassMetadata::FETCH_LAZY;
  338. }
  339. $this->_hints['fetchMode'][$class][$assocName] = $fetchMode;
  340. return $this;
  341. }
  342. /**
  343. * Defines the processing mode to be used during hydration / result set transformation.
  344. *
  345. * @param integer $hydrationMode Doctrine processing mode to be used during hydration process.
  346. * One of the Query::HYDRATE_* constants.
  347. * @return \Doctrine\ORM\AbstractQuery This query instance.
  348. */
  349. public function setHydrationMode($hydrationMode)
  350. {
  351. $this->_hydrationMode = $hydrationMode;
  352. return $this;
  353. }
  354. /**
  355. * Gets the hydration mode currently used by the query.
  356. *
  357. * @return integer
  358. */
  359. public function getHydrationMode()
  360. {
  361. return $this->_hydrationMode;
  362. }
  363. /**
  364. * Gets the list of results for the query.
  365. *
  366. * Alias for execute(array(), $hydrationMode = HYDRATE_OBJECT).
  367. *
  368. * @return array
  369. */
  370. public function getResult($hydrationMode = self::HYDRATE_OBJECT)
  371. {
  372. return $this->execute(array(), $hydrationMode);
  373. }
  374. /**
  375. * Gets the array of results for the query.
  376. *
  377. * Alias for execute(array(), HYDRATE_ARRAY).
  378. *
  379. * @return array
  380. */
  381. public function getArrayResult()
  382. {
  383. return $this->execute(array(), self::HYDRATE_ARRAY);
  384. }
  385. /**
  386. * Gets the scalar results for the query.
  387. *
  388. * Alias for execute(array(), HYDRATE_SCALAR).
  389. *
  390. * @return array
  391. */
  392. public function getScalarResult()
  393. {
  394. return $this->execute(array(), self::HYDRATE_SCALAR);
  395. }
  396. /**
  397. * Get exactly one result or null.
  398. *
  399. * @throws NonUniqueResultException
  400. * @param int $hydrationMode
  401. * @return mixed
  402. */
  403. public function getOneOrNullResult($hydrationMode = null)
  404. {
  405. $result = $this->execute(array(), $hydrationMode);
  406. if ($this->_hydrationMode !== self::HYDRATE_SINGLE_SCALAR && ! $result) {
  407. return null;
  408. }
  409. if (is_array($result)) {
  410. if (count($result) > 1) {
  411. throw new NonUniqueResultException;
  412. }
  413. return array_shift($result);
  414. }
  415. return $result;
  416. }
  417. /**
  418. * Gets the single result of the query.
  419. *
  420. * Enforces the presence as well as the uniqueness of the result.
  421. *
  422. * If the result is not unique, a NonUniqueResultException is thrown.
  423. * If there is no result, a NoResultException is thrown.
  424. *
  425. * @param integer $hydrationMode
  426. * @return mixed
  427. * @throws NonUniqueResultException If the query result is not unique.
  428. * @throws NoResultException If the query returned no result.
  429. */
  430. public function getSingleResult($hydrationMode = null)
  431. {
  432. $result = $this->execute(array(), $hydrationMode);
  433. if ($this->_hydrationMode !== self::HYDRATE_SINGLE_SCALAR && ! $result) {
  434. throw new NoResultException;
  435. }
  436. if (is_array($result)) {
  437. if (count($result) > 1) {
  438. throw new NonUniqueResultException;
  439. }
  440. return array_shift($result);
  441. }
  442. return $result;
  443. }
  444. /**
  445. * Gets the single scalar result of the query.
  446. *
  447. * Alias for getSingleResult(HYDRATE_SINGLE_SCALAR).
  448. *
  449. * @return mixed
  450. * @throws QueryException If the query result is not unique.
  451. */
  452. public function getSingleScalarResult()
  453. {
  454. return $this->getSingleResult(self::HYDRATE_SINGLE_SCALAR);
  455. }
  456. /**
  457. * Sets a query hint. If the hint name is not recognized, it is silently ignored.
  458. *
  459. * @param string $name The name of the hint.
  460. * @param mixed $value The value of the hint.
  461. * @return \Doctrine\ORM\AbstractQuery
  462. */
  463. public function setHint($name, $value)
  464. {
  465. $this->_hints[$name] = $value;
  466. return $this;
  467. }
  468. /**
  469. * Gets the value of a query hint. If the hint name is not recognized, FALSE is returned.
  470. *
  471. * @param string $name The name of the hint.
  472. * @return mixed The value of the hint or FALSE, if the hint name is not recognized.
  473. */
  474. public function getHint($name)
  475. {
  476. return isset($this->_hints[$name]) ? $this->_hints[$name] : false;
  477. }
  478. /**
  479. * Return the key value map of query hints that are currently set.
  480. *
  481. * @return array
  482. */
  483. public function getHints()
  484. {
  485. return $this->_hints;
  486. }
  487. /**
  488. * Executes the query and returns an IterableResult that can be used to incrementally
  489. * iterate over the result.
  490. *
  491. * @param array $params The query parameters.
  492. * @param integer $hydrationMode The hydration mode to use.
  493. * @return IterableResult
  494. */
  495. public function iterate(array $params = array(), $hydrationMode = null)
  496. {
  497. if ($hydrationMode !== null) {
  498. $this->setHydrationMode($hydrationMode);
  499. }
  500. if ($params) {
  501. $this->setParameters($params);
  502. }
  503. $stmt = $this->_doExecute();
  504. return $this->_em->newHydrator($this->_hydrationMode)->iterate(
  505. $stmt, $this->_resultSetMapping, $this->_hints
  506. );
  507. }
  508. /**
  509. * Executes the query.
  510. *
  511. * @param array $params Any additional query parameters.
  512. * @param integer $hydrationMode Processing mode to be used during the hydration process.
  513. * @return mixed
  514. */
  515. public function execute($params = array(), $hydrationMode = null)
  516. {
  517. if ($hydrationMode !== null) {
  518. $this->setHydrationMode($hydrationMode);
  519. }
  520. if ($params) {
  521. $this->setParameters($params);
  522. }
  523. // Check result cache
  524. if ($this->_useResultCache && $cacheDriver = $this->getResultCacheDriver()) {
  525. list($key, $hash) = $this->getResultCacheId();
  526. $cached = $this->_expireResultCache ? false : $cacheDriver->fetch($hash);
  527. if ($cached === false || !isset($cached[$key])) {
  528. // Cache miss.
  529. $stmt = $this->_doExecute();
  530. $result = $this->_em->getHydrator($this->_hydrationMode)->hydrateAll(
  531. $stmt, $this->_resultSetMapping, $this->_hints
  532. );
  533. $cacheDriver->save($hash, array($key => $result), $this->_resultCacheTTL);
  534. return $result;
  535. } else {
  536. // Cache hit.
  537. return $cached[$key];
  538. }
  539. }
  540. $stmt = $this->_doExecute();
  541. if (is_numeric($stmt)) {
  542. return $stmt;
  543. }
  544. return $this->_em->getHydrator($this->_hydrationMode)->hydrateAll(
  545. $stmt, $this->_resultSetMapping, $this->_hints
  546. );
  547. }
  548. /**
  549. * Set the result cache id to use to store the result set cache entry.
  550. * If this is not explicitely set by the developer then a hash is automatically
  551. * generated for you.
  552. *
  553. * @param string $id
  554. * @return \Doctrine\ORM\AbstractQuery This query instance.
  555. */
  556. public function setResultCacheId($id)
  557. {
  558. $this->_resultCacheId = $id;
  559. return $this;
  560. }
  561. /**
  562. * Get the result cache id to use to store the result set cache entry.
  563. * Will return the configured id if it exists otherwise a hash will be
  564. * automatically generated for you.
  565. *
  566. * @return array ($key, $hash)
  567. */
  568. protected function getResultCacheId()
  569. {
  570. if ($this->_resultCacheId) {
  571. return array($this->_resultCacheId, $this->_resultCacheId);
  572. } else {
  573. $params = $this->_params;
  574. foreach ($params AS $key => $value) {
  575. if (is_object($value) && $this->_em->getMetadataFactory()->hasMetadataFor(get_class($value))) {
  576. if ($this->_em->getUnitOfWork()->getEntityState($value) == UnitOfWork::STATE_MANAGED) {
  577. $idValues = $this->_em->getUnitOfWork()->getEntityIdentifier($value);
  578. } else {
  579. $class = $this->_em->getClassMetadata(get_class($value));
  580. $idValues = $class->getIdentifierValues($value);
  581. }
  582. $params[$key] = $idValues;
  583. } else {
  584. $params[$key] = $value;
  585. }
  586. }
  587. $sql = $this->getSql();
  588. ksort($this->_hints);
  589. $key = implode(";", (array)$sql) . var_export($params, true) .
  590. var_export($this->_hints, true)."&hydrationMode=".$this->_hydrationMode;
  591. return array($key, md5($key));
  592. }
  593. }
  594. /**
  595. * Executes the query and returns a the resulting Statement object.
  596. *
  597. * @return \Doctrine\DBAL\Driver\Statement The executed database statement that holds the results.
  598. */
  599. abstract protected function _doExecute();
  600. /**
  601. * Cleanup Query resource when clone is called.
  602. *
  603. * @return void
  604. */
  605. public function __clone()
  606. {
  607. $this->_params = array();
  608. $this->_paramTypes = array();
  609. $this->_hints = array();
  610. }
  611. }