QueryBuilder.php 33KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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[] = $fromClause;
  864. }
  865. $query .= implode(', ', $fromClauses)
  866. . ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : '')
  867. . ($this->sqlParts['groupBy'] ? ' GROUP BY ' . implode(', ', $this->sqlParts['groupBy']) : '')
  868. . ($this->sqlParts['having'] !== null ? ' HAVING ' . ((string) $this->sqlParts['having']) : '')
  869. . ($this->sqlParts['orderBy'] ? ' ORDER BY ' . implode(', ', $this->sqlParts['orderBy']) : '');
  870. return ($this->maxResults === null && $this->firstResult == null)
  871. ? $query
  872. : $this->connection->getDatabasePlatform()->modifyLimitQuery($query, $this->maxResults, $this->firstResult);
  873. }
  874. /**
  875. * Converts this instance into an UPDATE string in SQL.
  876. *
  877. * @return string
  878. */
  879. private function getSQLForUpdate()
  880. {
  881. $table = $this->sqlParts['from']['table'] . ($this->sqlParts['from']['alias'] ? ' ' . $this->sqlParts['from']['alias'] : '');
  882. $query = 'UPDATE ' . $table
  883. . ' SET ' . implode(", ", $this->sqlParts['set'])
  884. . ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : '');
  885. return $query;
  886. }
  887. /**
  888. * Converts this instance into a DELETE string in SQL.
  889. *
  890. * @return string
  891. */
  892. private function getSQLForDelete()
  893. {
  894. $table = $this->sqlParts['from']['table'] . ($this->sqlParts['from']['alias'] ? ' ' . $this->sqlParts['from']['alias'] : '');
  895. $query = 'DELETE FROM ' . $table . ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : '');
  896. return $query;
  897. }
  898. /**
  899. * Gets a string representation of this QueryBuilder which corresponds to
  900. * the final SQL query being constructed.
  901. *
  902. * @return string The string representation of this QueryBuilder.
  903. */
  904. public function __toString()
  905. {
  906. return $this->getSQL();
  907. }
  908. /**
  909. * Create a new named parameter and bind the value $value to it.
  910. *
  911. * This method provides a shortcut for PDOStatement::bindValue
  912. * when using prepared statements.
  913. *
  914. * The parameter $value specifies the value that you want to bind. If
  915. * $placeholder is not provided bindValue() will automatically create a
  916. * placeholder for you. An automatic placeholder will be of the name
  917. * ':dcValue1', ':dcValue2' etc.
  918. *
  919. * For more information see {@link http://php.net/pdostatement-bindparam}
  920. *
  921. * Example:
  922. * <code>
  923. * $value = 2;
  924. * $q->eq( 'id', $q->bindValue( $value ) );
  925. * $stmt = $q->executeQuery(); // executed with 'id = 2'
  926. * </code>
  927. *
  928. * @license New BSD License
  929. * @link http://www.zetacomponents.org
  930. * @param mixed $value
  931. * @param mixed $type
  932. * @param string $placeHolder the name to bind with. The string must start with a colon ':'.
  933. * @return string the placeholder name used.
  934. */
  935. public function createNamedParameter( $value, $type = \PDO::PARAM_STR, $placeHolder = null )
  936. {
  937. if ( $placeHolder === null ) {
  938. $this->boundCounter++;
  939. $placeHolder = ":dcValue" . $this->boundCounter;
  940. }
  941. $this->setParameter(substr($placeHolder, 1), $value, $type);
  942. return $placeHolder;
  943. }
  944. /**
  945. * Create a new positional parameter and bind the given value to it.
  946. *
  947. * Attention: If you are using positional parameters with the query builder you have
  948. * to be very careful to bind all parameters in the order they appear in the SQL
  949. * statement , otherwise they get bound in the wrong order which can lead to serious
  950. * bugs in your code.
  951. *
  952. * Example:
  953. * <code>
  954. * $qb = $conn->createQueryBuilder();
  955. * $qb->select('u.*')
  956. * ->from('users', 'u')
  957. * ->where('u.username = ' . $qb->createPositionalParameter('Foo', PDO::PARAM_STR))
  958. * ->orWhere('u.username = ' . $qb->createPositionalParameter('Bar', PDO::PARAM_STR))
  959. * </code>
  960. *
  961. * @param mixed $value
  962. * @param mixed $type
  963. * @return string
  964. */
  965. public function createPositionalParameter($value, $type = \PDO::PARAM_STR)
  966. {
  967. $this->boundCounter++;
  968. $this->setParameter($this->boundCounter, $value, $type);
  969. return "?";
  970. }
  971. }