QueryBuilder.php 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  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\DBAL\Query;
  20. use Doctrine\DBAL\Query\Expression\CompositeExpression,
  21. Doctrine\DBAL\Connection;
  22. /**
  23. * QueryBuilder class is responsible to dynamically create SQL queries.
  24. *
  25. * Important: Verify that every feature you use will work with your database vendor.
  26. * SQL Query Builder does not attempt to validate the generated SQL at all.
  27. *
  28. * The query builder does no validation whatsoever if certain features even work with the
  29. * underlying database vendor. Limit queries and joins are NOT applied to UPDATE and DELETE statements
  30. * even if some vendors such as MySQL support it.
  31. *
  32. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  33. * @link www.doctrine-project.com
  34. * @since 2.1
  35. * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
  36. * @author Benjamin Eberlei <kontakt@beberlei.de>
  37. */
  38. class QueryBuilder
  39. {
  40. /* The query types. */
  41. const SELECT = 0;
  42. const DELETE = 1;
  43. const UPDATE = 2;
  44. /** The builder states. */
  45. const STATE_DIRTY = 0;
  46. const STATE_CLEAN = 1;
  47. /**
  48. * @var Doctrine\DBAL\Connection DBAL Connection
  49. */
  50. private $connection = null;
  51. /**
  52. * @var array The array of SQL parts collected.
  53. */
  54. private $sqlParts = array(
  55. 'select' => array(),
  56. 'from' => array(),
  57. 'join' => array(),
  58. 'set' => array(),
  59. 'where' => null,
  60. 'groupBy' => array(),
  61. 'having' => null,
  62. 'orderBy' => array()
  63. );
  64. /**
  65. * @var string The complete SQL string for this query.
  66. */
  67. private $sql;
  68. /**
  69. * @var array The query parameters.
  70. */
  71. private $params = array();
  72. /**
  73. * @var array The parameter type map of this query.
  74. */
  75. private $paramTypes = array();
  76. /**
  77. * @var integer The type of query this is. Can be select, update or delete.
  78. */
  79. private $type = self::SELECT;
  80. /**
  81. * @var integer The state of the query object. Can be dirty or clean.
  82. */
  83. private $state = self::STATE_CLEAN;
  84. /**
  85. * @var integer The index of the first result to retrieve.
  86. */
  87. private $firstResult = null;
  88. /**
  89. * @var integer The maximum number of results to retrieve.
  90. */
  91. private $maxResults = null;
  92. /**
  93. * The counter of bound parameters used with {@see bindValue)
  94. *
  95. * @var int
  96. */
  97. private $boundCounter = 0;
  98. /**
  99. * Initializes a new <tt>QueryBuilder</tt>.
  100. *
  101. * @param Doctrine\DBAL\Connection $connection DBAL Connection
  102. */
  103. public function __construct(Connection $connection)
  104. {
  105. $this->connection = $connection;
  106. }
  107. /**
  108. * Gets an ExpressionBuilder used for object-oriented construction of query expressions.
  109. * This producer method is intended for convenient inline usage. Example:
  110. *
  111. * <code>
  112. * $qb = $conn->createQueryBuilder()
  113. * ->select('u')
  114. * ->from('users', 'u')
  115. * ->where($qb->expr()->eq('u.id', 1));
  116. * </code>
  117. *
  118. * For more complex expression construction, consider storing the expression
  119. * builder object in a local variable.
  120. *
  121. * @return Doctrine\DBAL\Query\ExpressionBuilder
  122. */
  123. public function expr()
  124. {
  125. return $this->connection->getExpressionBuilder();
  126. }
  127. /**
  128. * Get the type of the currently built query.
  129. *
  130. * @return integer
  131. */
  132. public function getType()
  133. {
  134. return $this->type;
  135. }
  136. /**
  137. * Get the associated DBAL Connection for this query builder.
  138. *
  139. * @return Doctrine\DBAL\Connection
  140. */
  141. public function getConnection()
  142. {
  143. return $this->connection;
  144. }
  145. /**
  146. * Get the state of this query builder instance.
  147. *
  148. * @return integer Either QueryBuilder::STATE_DIRTY or QueryBuilder::STATE_CLEAN.
  149. */
  150. public function getState()
  151. {
  152. return $this->state;
  153. }
  154. /**
  155. * Execute this query using the bound parameters and their types.
  156. *
  157. * Uses {@see Connection::executeQuery} for select statements and {@see Connection::executeUpdate}
  158. * for insert, update and delete statements.
  159. *
  160. * @return mixed
  161. */
  162. public function execute()
  163. {
  164. if ($this->type == self::SELECT) {
  165. return $this->connection->executeQuery($this->getSQL(), $this->params, $this->paramTypes);
  166. } else {
  167. return $this->connection->executeUpdate($this->getSQL(), $this->params, $this->paramTypes);
  168. }
  169. }
  170. /**
  171. * Get the complete SQL string formed by the current specifications of this QueryBuilder.
  172. *
  173. * <code>
  174. * $qb = $em->createQueryBuilder()
  175. * ->select('u')
  176. * ->from('User', 'u')
  177. * echo $qb->getSQL(); // SELECT u FROM User u
  178. * </code>
  179. *
  180. * @return string The sql query string.
  181. */
  182. public function getSQL()
  183. {
  184. if ($this->sql !== null && $this->state === self::STATE_CLEAN) {
  185. return $this->sql;
  186. }
  187. $sql = '';
  188. switch ($this->type) {
  189. case self::DELETE:
  190. $sql = $this->getSQLForDelete();
  191. break;
  192. case self::UPDATE:
  193. $sql = $this->getSQLForUpdate();
  194. break;
  195. case self::SELECT:
  196. default:
  197. $sql = $this->getSQLForSelect();
  198. break;
  199. }
  200. $this->state = self::STATE_CLEAN;
  201. $this->sql = $sql;
  202. return $sql;
  203. }
  204. /**
  205. * Sets a query parameter for the query being constructed.
  206. *
  207. * <code>
  208. * $qb = $conn->createQueryBuilder()
  209. * ->select('u')
  210. * ->from('users', 'u')
  211. * ->where('u.id = :user_id')
  212. * ->setParameter(':user_id', 1);
  213. * </code>
  214. *
  215. * @param string|integer $key The parameter position or name.
  216. * @param mixed $value The parameter value.
  217. * @param string|null $type PDO::PARAM_*
  218. * @return QueryBuilder This QueryBuilder instance.
  219. */
  220. public function setParameter($key, $value, $type = null)
  221. {
  222. if ($type !== null) {
  223. $this->paramTypes[$key] = $type;
  224. }
  225. $this->params[$key] = $value;
  226. return $this;
  227. }
  228. /**
  229. * Sets a collection of query parameters for the query being constructed.
  230. *
  231. * <code>
  232. * $qb = $conn->createQueryBuilder()
  233. * ->select('u')
  234. * ->from('users', 'u')
  235. * ->where('u.id = :user_id1 OR u.id = :user_id2')
  236. * ->setParameters(array(
  237. * ':user_id1' => 1,
  238. * ':user_id2' => 2
  239. * ));
  240. * </code>
  241. *
  242. * @param array $params The query parameters to set.
  243. * @return QueryBuilder This QueryBuilder instance.
  244. */
  245. public function setParameters(array $params, array $types = array())
  246. {
  247. $this->paramTypes = $types;
  248. $this->params = $params;
  249. return $this;
  250. }
  251. /**
  252. * Gets all defined query parameters for the query being constructed.
  253. *
  254. * @return array The currently defined query parameters.
  255. */
  256. public function getParameters()
  257. {
  258. return $this->params;
  259. }
  260. /**
  261. * Gets a (previously set) query parameter of the query being constructed.
  262. *
  263. * @param mixed $key The key (index or name) of the bound parameter.
  264. * @return mixed The value of the bound parameter.
  265. */
  266. public function getParameter($key)
  267. {
  268. return isset($this->params[$key]) ? $this->params[$key] : null;
  269. }
  270. /**
  271. * Sets the position of the first result to retrieve (the "offset").
  272. *
  273. * @param integer $firstResult The first result to return.
  274. * @return Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
  275. */
  276. public function setFirstResult($firstResult)
  277. {
  278. $this->state = self::STATE_DIRTY;
  279. $this->firstResult = $firstResult;
  280. return $this;
  281. }
  282. /**
  283. * Gets the position of the first result the query object was set to retrieve (the "offset").
  284. * Returns NULL if {@link setFirstResult} was not applied to this QueryBuilder.
  285. *
  286. * @return integer The position of the first result.
  287. */
  288. public function getFirstResult()
  289. {
  290. return $this->firstResult;
  291. }
  292. /**
  293. * Sets the maximum number of results to retrieve (the "limit").
  294. *
  295. * @param integer $maxResults The maximum number of results to retrieve.
  296. * @return Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
  297. */
  298. public function setMaxResults($maxResults)
  299. {
  300. $this->state = self::STATE_DIRTY;
  301. $this->maxResults = $maxResults;
  302. return $this;
  303. }
  304. /**
  305. * Gets the maximum number of results the query object was set to retrieve (the "limit").
  306. * Returns NULL if {@link setMaxResults} was not applied to this query builder.
  307. *
  308. * @return integer Maximum number of results.
  309. */
  310. public function getMaxResults()
  311. {
  312. return $this->maxResults;
  313. }
  314. /**
  315. * Either appends to or replaces a single, generic query part.
  316. *
  317. * The available parts are: 'select', 'from', 'set', 'where',
  318. * 'groupBy', 'having' and 'orderBy'.
  319. *
  320. * @param string $sqlPartName
  321. * @param string $sqlPart
  322. * @param string $append
  323. * @return Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
  324. */
  325. public function add($sqlPartName, $sqlPart, $append = false)
  326. {
  327. $isArray = is_array($sqlPart);
  328. $isMultiple = is_array($this->sqlParts[$sqlPartName]);
  329. if ($isMultiple && !$isArray) {
  330. $sqlPart = array($sqlPart);
  331. }
  332. $this->state = self::STATE_DIRTY;
  333. if ($append) {
  334. if ($sqlPartName == "orderBy" || $sqlPartName == "groupBy" || $sqlPartName == "select" || $sqlPartName == "set") {
  335. foreach ($sqlPart AS $part) {
  336. $this->sqlParts[$sqlPartName][] = $part;
  337. }
  338. } else if ($isArray && is_array($sqlPart[key($sqlPart)])) {
  339. $key = key($sqlPart);
  340. $this->sqlParts[$sqlPartName][$key][] = $sqlPart[$key];
  341. } else if ($isMultiple) {
  342. $this->sqlParts[$sqlPartName][] = $sqlPart;
  343. } else {
  344. $this->sqlParts[$sqlPartName] = $sqlPart;
  345. }
  346. return $this;
  347. }
  348. $this->sqlParts[$sqlPartName] = $sqlPart;
  349. return $this;
  350. }
  351. /**
  352. * Specifies an item that is to be returned in the query result.
  353. * Replaces any previously specified selections, if any.
  354. *
  355. * <code>
  356. * $qb = $conn->createQueryBuilder()
  357. * ->select('u.id', 'p.id')
  358. * ->from('users', 'u')
  359. * ->leftJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id');
  360. * </code>
  361. *
  362. * @param mixed $select The selection expressions.
  363. * @return QueryBuilder This QueryBuilder instance.
  364. */
  365. public function select($select = null)
  366. {
  367. $this->type = self::SELECT;
  368. if (empty($select)) {
  369. return $this;
  370. }
  371. $selects = is_array($select) ? $select : func_get_args();
  372. return $this->add('select', $selects, false);
  373. }
  374. /**
  375. * Adds an item that is to be returned in the query result.
  376. *
  377. * <code>
  378. * $qb = $conn->createQueryBuilder()
  379. * ->select('u.id')
  380. * ->addSelect('p.id')
  381. * ->from('users', 'u')
  382. * ->leftJoin('u', 'phonenumbers', 'u.id = p.user_id');
  383. * </code>
  384. *
  385. * @param mixed $select The selection expression.
  386. * @return QueryBuilder This QueryBuilder instance.
  387. */
  388. public function addSelect($select = null)
  389. {
  390. $this->type = self::SELECT;
  391. if (empty($select)) {
  392. return $this;
  393. }
  394. $selects = is_array($select) ? $select : func_get_args();
  395. return $this->add('select', $selects, true);
  396. }
  397. /**
  398. * Turns the query being built into a bulk delete query that ranges over
  399. * a certain table.
  400. *
  401. * <code>
  402. * $qb = $conn->createQueryBuilder()
  403. * ->delete('users', 'u')
  404. * ->where('u.id = :user_id');
  405. * ->setParameter(':user_id', 1);
  406. * </code>
  407. *
  408. * @param string $delete The table whose rows are subject to the deletion.
  409. * @param string $alias The table alias used in the constructed query.
  410. * @return QueryBuilder This QueryBuilder instance.
  411. */
  412. public function delete($delete = null, $alias = null)
  413. {
  414. $this->type = self::DELETE;
  415. if ( ! $delete) {
  416. return $this;
  417. }
  418. return $this->add('from', array(
  419. 'table' => $delete,
  420. 'alias' => $alias
  421. ));
  422. }
  423. /**
  424. * Turns the query being built into a bulk update query that ranges over
  425. * a certain table
  426. *
  427. * <code>
  428. * $qb = $conn->createQueryBuilder()
  429. * ->update('users', 'u')
  430. * ->set('u.password', md5('password'))
  431. * ->where('u.id = ?');
  432. * </code>
  433. *
  434. * @param string $update The table whose rows are subject to the update.
  435. * @param string $alias The table alias used in the constructed query.
  436. * @return QueryBuilder This QueryBuilder instance.
  437. */
  438. public function update($update = null, $alias = null)
  439. {
  440. $this->type = self::UPDATE;
  441. if ( ! $update) {
  442. return $this;
  443. }
  444. return $this->add('from', array(
  445. 'table' => $update,
  446. 'alias' => $alias
  447. ));
  448. }
  449. /**
  450. * Create and add a query root corresponding to the table identified by the
  451. * given alias, forming a cartesian product with any existing query roots.
  452. *
  453. * <code>
  454. * $qb = $conn->createQueryBuilder()
  455. * ->select('u.id')
  456. * ->from('users', 'u')
  457. * </code>
  458. *
  459. * @param string $from The table
  460. * @param string $alias The alias of the table
  461. * @return QueryBuilder This QueryBuilder instance.
  462. */
  463. public function from($from, $alias)
  464. {
  465. return $this->add('from', array(
  466. 'table' => $from,
  467. 'alias' => $alias
  468. ), true);
  469. }
  470. /**
  471. * Creates and adds a join to the query.
  472. *
  473. * <code>
  474. * $qb = $conn->createQueryBuilder()
  475. * ->select('u.name')
  476. * ->from('users', 'u')
  477. * ->join('u', 'phonenumbers', 'p', 'p.is_primary = 1');
  478. * </code>
  479. *
  480. * @param string $fromAlias The alias that points to a from clause
  481. * @param string $join The table name to join
  482. * @param string $alias The alias of the join table
  483. * @param string $condition The condition for the join
  484. * @return QueryBuilder This QueryBuilder instance.
  485. */
  486. public function join($fromAlias, $join, $alias, $condition = null)
  487. {
  488. return $this->innerJoin($fromAlias, $join, $alias, $condition);
  489. }
  490. /**
  491. * Creates and adds a join to the query.
  492. *
  493. * <code>
  494. * $qb = $conn->createQueryBuilder()
  495. * ->select('u.name')
  496. * ->from('users', 'u')
  497. * ->innerJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
  498. * </code>
  499. *
  500. * @param string $fromAlias The alias that points to a from clause
  501. * @param string $join The table name to join
  502. * @param string $alias The alias of the join table
  503. * @param string $condition The condition for the join
  504. * @return QueryBuilder This QueryBuilder instance.
  505. */
  506. public function innerJoin($fromAlias, $join, $alias, $condition = null)
  507. {
  508. return $this->add('join', array(
  509. $fromAlias => array(
  510. 'joinType' => 'inner',
  511. 'joinTable' => $join,
  512. 'joinAlias' => $alias,
  513. 'joinCondition' => $condition
  514. )
  515. ), true);
  516. }
  517. /**
  518. * Creates and adds a left join to the query.
  519. *
  520. * <code>
  521. * $qb = $conn->createQueryBuilder()
  522. * ->select('u.name')
  523. * ->from('users', 'u')
  524. * ->leftJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
  525. * </code>
  526. *
  527. * @param string $fromAlias The alias that points to a from clause
  528. * @param string $join The table name to join
  529. * @param string $alias The alias of the join table
  530. * @param string $condition The condition for the join
  531. * @return QueryBuilder This QueryBuilder instance.
  532. */
  533. public function leftJoin($fromAlias, $join, $alias, $condition = null)
  534. {
  535. return $this->add('join', array(
  536. $fromAlias => array(
  537. 'joinType' => 'left',
  538. 'joinTable' => $join,
  539. 'joinAlias' => $alias,
  540. 'joinCondition' => $condition
  541. )
  542. ), true);
  543. }
  544. /**
  545. * Creates and adds a right join to the query.
  546. *
  547. * <code>
  548. * $qb = $conn->createQueryBuilder()
  549. * ->select('u.name')
  550. * ->from('users', 'u')
  551. * ->rightJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
  552. * </code>
  553. *
  554. * @param string $fromAlias The alias that points to a from clause
  555. * @param string $join The table name to join
  556. * @param string $alias The alias of the join table
  557. * @param string $condition The condition for the join
  558. * @return QueryBuilder This QueryBuilder instance.
  559. */
  560. public function rightJoin($fromAlias, $join, $alias, $condition = null)
  561. {
  562. return $this->add('join', array(
  563. $fromAlias => array(
  564. 'joinType' => 'right',
  565. 'joinTable' => $join,
  566. 'joinAlias' => $alias,
  567. 'joinCondition' => $condition
  568. )
  569. ), true);
  570. }
  571. /**
  572. * Sets a new value for a column in a bulk update query.
  573. *
  574. * <code>
  575. * $qb = $conn->createQueryBuilder()
  576. * ->update('users', 'u')
  577. * ->set('u.password', md5('password'))
  578. * ->where('u.id = ?');
  579. * </code>
  580. *
  581. * @param string $key The column to set.
  582. * @param string $value The value, expression, placeholder, etc.
  583. * @return QueryBuilder This QueryBuilder instance.
  584. */
  585. public function set($key, $value)
  586. {
  587. return $this->add('set', $key .' = ' . $value, true);
  588. }
  589. /**
  590. * Specifies one or more restrictions to the query result.
  591. * Replaces any previously specified restrictions, if any.
  592. *
  593. * <code>
  594. * $qb = $conn->createQueryBuilder()
  595. * ->select('u.name')
  596. * ->from('users', 'u')
  597. * ->where('u.id = ?');
  598. *
  599. * // You can optionally programatically build and/or expressions
  600. * $qb = $conn->createQueryBuilder();
  601. *
  602. * $or = $qb->expr()->orx();
  603. * $or->add($qb->expr()->eq('u.id', 1));
  604. * $or->add($qb->expr()->eq('u.id', 2));
  605. *
  606. * $qb->update('users', 'u')
  607. * ->set('u.password', md5('password'))
  608. * ->where($or);
  609. * </code>
  610. *
  611. * @param mixed $predicates The restriction predicates.
  612. * @return QueryBuilder This QueryBuilder instance.
  613. */
  614. public function where($predicates)
  615. {
  616. if ( ! (func_num_args() == 1 && $predicates instanceof CompositeExpression) ) {
  617. $predicates = new CompositeExpression(CompositeExpression::TYPE_AND, func_get_args());
  618. }
  619. return $this->add('where', $predicates);
  620. }
  621. /**
  622. * Adds one or more restrictions to the query results, forming a logical
  623. * conjunction with any previously specified restrictions.
  624. *
  625. * <code>
  626. * $qb = $conn->createQueryBuilder()
  627. * ->select('u')
  628. * ->from('users', 'u')
  629. * ->where('u.username LIKE ?')
  630. * ->andWhere('u.is_active = 1');
  631. * </code>
  632. *
  633. * @param mixed $where The query restrictions.
  634. * @return QueryBuilder This QueryBuilder instance.
  635. * @see where()
  636. */
  637. public function andWhere($where)
  638. {
  639. $where = $this->getQueryPart('where');
  640. $args = func_get_args();
  641. if ($where instanceof CompositeExpression && $where->getType() === CompositeExpression::TYPE_AND) {
  642. $where->addMultiple($args);
  643. } else {
  644. array_unshift($args, $where);
  645. $where = new CompositeExpression(CompositeExpression::TYPE_AND, $args);
  646. }
  647. return $this->add('where', $where, true);
  648. }
  649. /**
  650. * Adds one or more restrictions to the query results, forming a logical
  651. * disjunction with any previously specified restrictions.
  652. *
  653. * <code>
  654. * $qb = $em->createQueryBuilder()
  655. * ->select('u.name')
  656. * ->from('users', 'u')
  657. * ->where('u.id = 1')
  658. * ->orWhere('u.id = 2');
  659. * </code>
  660. *
  661. * @param mixed $where The WHERE statement
  662. * @return QueryBuilder $qb
  663. * @see where()
  664. */
  665. public function orWhere($where)
  666. {
  667. $where = $this->getQueryPart('where');
  668. $args = func_get_args();
  669. if ($where instanceof CompositeExpression && $where->getType() === CompositeExpression::TYPE_OR) {
  670. $where->addMultiple($args);
  671. } else {
  672. array_unshift($args, $where);
  673. $where = new CompositeExpression(CompositeExpression::TYPE_OR, $args);
  674. }
  675. return $this->add('where', $where, true);
  676. }
  677. /**
  678. * Specifies a grouping over the results of the query.
  679. * Replaces any previously specified groupings, if any.
  680. *
  681. * <code>
  682. * $qb = $conn->createQueryBuilder()
  683. * ->select('u.name')
  684. * ->from('users', 'u')
  685. * ->groupBy('u.id');
  686. * </code>
  687. *
  688. * @param mixed $groupBy The grouping expression.
  689. * @return QueryBuilder This QueryBuilder instance.
  690. */
  691. public function groupBy($groupBy)
  692. {
  693. if (empty($groupBy)) {
  694. return $this;
  695. }
  696. $groupBy = is_array($groupBy) ? $groupBy : func_get_args();
  697. return $this->add('groupBy', $groupBy, false);
  698. }
  699. /**
  700. * Adds a grouping expression to the query.
  701. *
  702. * <code>
  703. * $qb = $conn->createQueryBuilder()
  704. * ->select('u.name')
  705. * ->from('users', 'u')
  706. * ->groupBy('u.lastLogin');
  707. * ->addGroupBy('u.createdAt')
  708. * </code>
  709. *
  710. * @param mixed $groupBy The grouping expression.
  711. * @return QueryBuilder This QueryBuilder instance.
  712. */
  713. public function addGroupBy($groupBy)
  714. {
  715. if (empty($groupBy)) {
  716. return $this;
  717. }
  718. $groupBy = is_array($groupBy) ? $groupBy : func_get_args();
  719. return $this->add('groupBy', $groupBy, true);
  720. }
  721. /**
  722. * Specifies a restriction over the groups of the query.
  723. * Replaces any previous having restrictions, if any.
  724. *
  725. * @param mixed $having The restriction over the groups.
  726. * @return QueryBuilder This QueryBuilder instance.
  727. */
  728. public function having($having)
  729. {
  730. if ( ! (func_num_args() == 1 && $having instanceof CompositeExpression)) {
  731. $having = new CompositeExpression(CompositeExpression::TYPE_AND, func_get_args());
  732. }
  733. return $this->add('having', $having);
  734. }
  735. /**
  736. * Adds a restriction over the groups of the query, forming a logical
  737. * conjunction with any existing having restrictions.
  738. *
  739. * @param mixed $having The restriction to append.
  740. * @return QueryBuilder This QueryBuilder instance.
  741. */
  742. public function andHaving($having)
  743. {
  744. $having = $this->getQueryPart('having');
  745. $args = func_get_args();
  746. if ($having instanceof CompositeExpression && $having->getType() === CompositeExpression::TYPE_AND) {
  747. $having->addMultiple($args);
  748. } else {
  749. array_unshift($args, $having);
  750. $having = new CompositeExpression(CompositeExpression::TYPE_AND, $args);
  751. }
  752. return $this->add('having', $having);
  753. }
  754. /**
  755. * Adds a restriction over the groups of the query, forming a logical
  756. * disjunction with any existing having restrictions.
  757. *
  758. * @param mixed $having The restriction to add.
  759. * @return QueryBuilder This QueryBuilder instance.
  760. */
  761. public function orHaving($having)
  762. {
  763. $having = $this->getQueryPart('having');
  764. $args = func_get_args();
  765. if ($having instanceof CompositeExpression && $having->getType() === CompositeExpression::TYPE_OR) {
  766. $having->addMultiple($args);
  767. } else {
  768. array_unshift($args, $having);
  769. $having = new CompositeExpression(CompositeExpression::TYPE_OR, $args);
  770. }
  771. return $this->add('having', $having);
  772. }
  773. /**
  774. * Specifies an ordering for the query results.
  775. * Replaces any previously specified orderings, if any.
  776. *
  777. * @param string $sort The ordering expression.
  778. * @param string $order The ordering direction.
  779. * @return QueryBuilder This QueryBuilder instance.
  780. */
  781. public function orderBy($sort, $order = null)
  782. {
  783. return $this->add('orderBy', $sort . ' ' . (! $order ? 'ASC' : $order), false);
  784. }
  785. /**
  786. * Adds an ordering to the query results.
  787. *
  788. * @param string $sort The ordering expression.
  789. * @param string $order The ordering direction.
  790. * @return QueryBuilder This QueryBuilder instance.
  791. */
  792. public function addOrderBy($sort, $order = null)
  793. {
  794. return $this->add('orderBy', $sort . ' ' . (! $order ? 'ASC' : $order), true);
  795. }
  796. /**
  797. * Get a query part by its name.
  798. *
  799. * @param string $queryPartName
  800. * @return mixed $queryPart
  801. */
  802. public function getQueryPart($queryPartName)
  803. {
  804. return $this->sqlParts[$queryPartName];
  805. }
  806. /**
  807. * Get all query parts.
  808. *
  809. * @return array $sqlParts
  810. */
  811. public function getQueryParts()
  812. {
  813. return $this->sqlParts;
  814. }
  815. /**
  816. * Reset SQL parts
  817. *
  818. * @param array $queryPartNames
  819. * @return QueryBuilder
  820. */
  821. public function resetQueryParts($queryPartNames = null)
  822. {
  823. if (is_null($queryPartNames)) {
  824. $queryPartNames = array_keys($this->sqlParts);
  825. }
  826. foreach ($queryPartNames as $queryPartName) {
  827. $this->resetQueryPart($queryPartName);
  828. }
  829. return $this;
  830. }
  831. /**
  832. * Reset single SQL part
  833. *
  834. * @param string $queryPartName
  835. * @return QueryBuilder
  836. */
  837. public function resetQueryPart($queryPartName)
  838. {
  839. $this->sqlParts[$queryPartName] = is_array($this->sqlParts[$queryPartName])
  840. ? array() : null;
  841. $this->state = self::STATE_DIRTY;
  842. return $this;
  843. }
  844. /**
  845. * Converts this instance into a SELECT string in SQL.
  846. *
  847. * @return string
  848. */
  849. private function getSQLForSelect()
  850. {
  851. $query = 'SELECT ' . implode(', ', $this->sqlParts['select']) . ' FROM ';
  852. $fromClauses = array();
  853. // Loop through all FROM clauses
  854. foreach ($this->sqlParts['from'] as $from) {
  855. $fromClause = $from['table'] . ' ' . $from['alias'];
  856. if (isset($this->sqlParts['join'][$from['alias']])) {
  857. foreach ($this->sqlParts['join'][$from['alias']] as $join) {
  858. $fromClause .= ' ' . strtoupper($join['joinType'])
  859. . ' JOIN ' . $join['joinTable'] . ' ' . $join['joinAlias']
  860. . ' ON ' . ((string) $join['joinCondition']);
  861. }
  862. }
  863. $fromClauses[$from['alias']] = $fromClause;
  864. }
  865. // loop through all JOIN clasues for validation purpose
  866. foreach ($this->sqlParts['join'] as $fromAlias => $joins) {
  867. if ( ! isset($fromClauses[$fromAlias]) ) {
  868. throw QueryException::unknownFromAlias($fromAlias, array_keys($fromClauses));
  869. }
  870. }
  871. $query .= implode(', ', $fromClauses)
  872. . ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : '')
  873. . ($this->sqlParts['groupBy'] ? ' GROUP BY ' . implode(', ', $this->sqlParts['groupBy']) : '')
  874. . ($this->sqlParts['having'] !== null ? ' HAVING ' . ((string) $this->sqlParts['having']) : '')
  875. . ($this->sqlParts['orderBy'] ? ' ORDER BY ' . implode(', ', $this->sqlParts['orderBy']) : '');
  876. return ($this->maxResults === null && $this->firstResult == null)
  877. ? $query
  878. : $this->connection->getDatabasePlatform()->modifyLimitQuery($query, $this->maxResults, $this->firstResult);
  879. }
  880. /**
  881. * Converts this instance into an UPDATE string in SQL.
  882. *
  883. * @return string
  884. */
  885. private function getSQLForUpdate()
  886. {
  887. $table = $this->sqlParts['from']['table'] . ($this->sqlParts['from']['alias'] ? ' ' . $this->sqlParts['from']['alias'] : '');
  888. $query = 'UPDATE ' . $table
  889. . ' SET ' . implode(", ", $this->sqlParts['set'])
  890. . ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : '');
  891. return $query;
  892. }
  893. /**
  894. * Converts this instance into a DELETE string in SQL.
  895. *
  896. * @return string
  897. */
  898. private function getSQLForDelete()
  899. {
  900. $table = $this->sqlParts['from']['table'] . ($this->sqlParts['from']['alias'] ? ' ' . $this->sqlParts['from']['alias'] : '');
  901. $query = 'DELETE FROM ' . $table . ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : '');
  902. return $query;
  903. }
  904. /**
  905. * Gets a string representation of this QueryBuilder which corresponds to
  906. * the final SQL query being constructed.
  907. *
  908. * @return string The string representation of this QueryBuilder.
  909. */
  910. public function __toString()
  911. {
  912. return $this->getSQL();
  913. }
  914. /**
  915. * Create a new named parameter and bind the value $value to it.
  916. *
  917. * This method provides a shortcut for PDOStatement::bindValue
  918. * when using prepared statements.
  919. *
  920. * The parameter $value specifies the value that you want to bind. If
  921. * $placeholder is not provided bindValue() will automatically create a
  922. * placeholder for you. An automatic placeholder will be of the name
  923. * ':dcValue1', ':dcValue2' etc.
  924. *
  925. * For more information see {@link http://php.net/pdostatement-bindparam}
  926. *
  927. * Example:
  928. * <code>
  929. * $value = 2;
  930. * $q->eq( 'id', $q->bindValue( $value ) );
  931. * $stmt = $q->executeQuery(); // executed with 'id = 2'
  932. * </code>
  933. *
  934. * @license New BSD License
  935. * @link http://www.zetacomponents.org
  936. * @param mixed $value
  937. * @param mixed $type
  938. * @param string $placeHolder the name to bind with. The string must start with a colon ':'.
  939. * @return string the placeholder name used.
  940. */
  941. public function createNamedParameter( $value, $type = \PDO::PARAM_STR, $placeHolder = null )
  942. {
  943. if ( $placeHolder === null ) {
  944. $this->boundCounter++;
  945. $placeHolder = ":dcValue" . $this->boundCounter;
  946. }
  947. $this->setParameter(substr($placeHolder, 1), $value, $type);
  948. return $placeHolder;
  949. }
  950. /**
  951. * Create a new positional parameter and bind the given value to it.
  952. *
  953. * Attention: If you are using positional parameters with the query builder you have
  954. * to be very careful to bind all parameters in the order they appear in the SQL
  955. * statement , otherwise they get bound in the wrong order which can lead to serious
  956. * bugs in your code.
  957. *
  958. * Example:
  959. * <code>
  960. * $qb = $conn->createQueryBuilder();
  961. * $qb->select('u.*')
  962. * ->from('users', 'u')
  963. * ->where('u.username = ' . $qb->createPositionalParameter('Foo', PDO::PARAM_STR))
  964. * ->orWhere('u.username = ' . $qb->createPositionalParameter('Bar', PDO::PARAM_STR))
  965. * </code>
  966. *
  967. * @param mixed $value
  968. * @param mixed $type
  969. * @return string
  970. */
  971. public function createPositionalParameter($value, $type = \PDO::PARAM_STR)
  972. {
  973. $this->boundCounter++;
  974. $this->setParameter($this->boundCounter, $value, $type);
  975. return "?";
  976. }
  977. }