QueryBuilder.php 33KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  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 MIT license. 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\Expression\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. * @param array $types The query parameters types to set.
  244. * @return QueryBuilder This QueryBuilder instance.
  245. */
  246. public function setParameters(array $params, array $types = array())
  247. {
  248. $this->paramTypes = $types;
  249. $this->params = $params;
  250. return $this;
  251. }
  252. /**
  253. * Gets all defined query parameters for the query being constructed.
  254. *
  255. * @return array The currently defined query parameters.
  256. */
  257. public function getParameters()
  258. {
  259. return $this->params;
  260. }
  261. /**
  262. * Gets a (previously set) query parameter of the query being constructed.
  263. *
  264. * @param mixed $key The key (index or name) of the bound parameter.
  265. * @return mixed The value of the bound parameter.
  266. */
  267. public function getParameter($key)
  268. {
  269. return isset($this->params[$key]) ? $this->params[$key] : null;
  270. }
  271. /**
  272. * Sets the position of the first result to retrieve (the "offset").
  273. *
  274. * @param integer $firstResult The first result to return.
  275. * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
  276. */
  277. public function setFirstResult($firstResult)
  278. {
  279. $this->state = self::STATE_DIRTY;
  280. $this->firstResult = $firstResult;
  281. return $this;
  282. }
  283. /**
  284. * Gets the position of the first result the query object was set to retrieve (the "offset").
  285. * Returns NULL if {@link setFirstResult} was not applied to this QueryBuilder.
  286. *
  287. * @return integer The position of the first result.
  288. */
  289. public function getFirstResult()
  290. {
  291. return $this->firstResult;
  292. }
  293. /**
  294. * Sets the maximum number of results to retrieve (the "limit").
  295. *
  296. * @param integer $maxResults The maximum number of results to retrieve.
  297. * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
  298. */
  299. public function setMaxResults($maxResults)
  300. {
  301. $this->state = self::STATE_DIRTY;
  302. $this->maxResults = $maxResults;
  303. return $this;
  304. }
  305. /**
  306. * Gets the maximum number of results the query object was set to retrieve (the "limit").
  307. * Returns NULL if {@link setMaxResults} was not applied to this query builder.
  308. *
  309. * @return integer Maximum number of results.
  310. */
  311. public function getMaxResults()
  312. {
  313. return $this->maxResults;
  314. }
  315. /**
  316. * Either appends to or replaces a single, generic query part.
  317. *
  318. * The available parts are: 'select', 'from', 'set', 'where',
  319. * 'groupBy', 'having' and 'orderBy'.
  320. *
  321. * @param string $sqlPartName
  322. * @param string $sqlPart
  323. * @param boolean $append
  324. * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
  325. */
  326. public function add($sqlPartName, $sqlPart, $append = false)
  327. {
  328. $isArray = is_array($sqlPart);
  329. $isMultiple = is_array($this->sqlParts[$sqlPartName]);
  330. if ($isMultiple && !$isArray) {
  331. $sqlPart = array($sqlPart);
  332. }
  333. $this->state = self::STATE_DIRTY;
  334. if ($append) {
  335. if ($sqlPartName == "orderBy" || $sqlPartName == "groupBy" || $sqlPartName == "select" || $sqlPartName == "set") {
  336. foreach ($sqlPart as $part) {
  337. $this->sqlParts[$sqlPartName][] = $part;
  338. }
  339. } else if ($isArray && is_array($sqlPart[key($sqlPart)])) {
  340. $key = key($sqlPart);
  341. $this->sqlParts[$sqlPartName][$key][] = $sqlPart[$key];
  342. } else if ($isMultiple) {
  343. $this->sqlParts[$sqlPartName][] = $sqlPart;
  344. } else {
  345. $this->sqlParts[$sqlPartName] = $sqlPart;
  346. }
  347. return $this;
  348. }
  349. $this->sqlParts[$sqlPartName] = $sqlPart;
  350. return $this;
  351. }
  352. /**
  353. * Specifies an item that is to be returned in the query result.
  354. * Replaces any previously specified selections, if any.
  355. *
  356. * <code>
  357. * $qb = $conn->createQueryBuilder()
  358. * ->select('u.id', 'p.id')
  359. * ->from('users', 'u')
  360. * ->leftJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id');
  361. * </code>
  362. *
  363. * @param mixed $select The selection expressions.
  364. * @return QueryBuilder This QueryBuilder instance.
  365. */
  366. public function select($select = null)
  367. {
  368. $this->type = self::SELECT;
  369. if (empty($select)) {
  370. return $this;
  371. }
  372. $selects = is_array($select) ? $select : func_get_args();
  373. return $this->add('select', $selects, false);
  374. }
  375. /**
  376. * Adds an item that is to be returned in the query result.
  377. *
  378. * <code>
  379. * $qb = $conn->createQueryBuilder()
  380. * ->select('u.id')
  381. * ->addSelect('p.id')
  382. * ->from('users', 'u')
  383. * ->leftJoin('u', 'phonenumbers', 'u.id = p.user_id');
  384. * </code>
  385. *
  386. * @param mixed $select The selection expression.
  387. * @return QueryBuilder This QueryBuilder instance.
  388. */
  389. public function addSelect($select = null)
  390. {
  391. $this->type = self::SELECT;
  392. if (empty($select)) {
  393. return $this;
  394. }
  395. $selects = is_array($select) ? $select : func_get_args();
  396. return $this->add('select', $selects, true);
  397. }
  398. /**
  399. * Turns the query being built into a bulk delete query that ranges over
  400. * a certain table.
  401. *
  402. * <code>
  403. * $qb = $conn->createQueryBuilder()
  404. * ->delete('users', 'u')
  405. * ->where('u.id = :user_id');
  406. * ->setParameter(':user_id', 1);
  407. * </code>
  408. *
  409. * @param string $delete The table whose rows are subject to the deletion.
  410. * @param string $alias The table alias used in the constructed query.
  411. * @return QueryBuilder This QueryBuilder instance.
  412. */
  413. public function delete($delete = null, $alias = null)
  414. {
  415. $this->type = self::DELETE;
  416. if ( ! $delete) {
  417. return $this;
  418. }
  419. return $this->add('from', array(
  420. 'table' => $delete,
  421. 'alias' => $alias
  422. ));
  423. }
  424. /**
  425. * Turns the query being built into a bulk update query that ranges over
  426. * a certain table
  427. *
  428. * <code>
  429. * $qb = $conn->createQueryBuilder()
  430. * ->update('users', 'u')
  431. * ->set('u.password', md5('password'))
  432. * ->where('u.id = ?');
  433. * </code>
  434. *
  435. * @param string $update The table whose rows are subject to the update.
  436. * @param string $alias The table alias used in the constructed query.
  437. * @return QueryBuilder This QueryBuilder instance.
  438. */
  439. public function update($update = null, $alias = null)
  440. {
  441. $this->type = self::UPDATE;
  442. if ( ! $update) {
  443. return $this;
  444. }
  445. return $this->add('from', array(
  446. 'table' => $update,
  447. 'alias' => $alias
  448. ));
  449. }
  450. /**
  451. * Create and add a query root corresponding to the table identified by the
  452. * given alias, forming a cartesian product with any existing query roots.
  453. *
  454. * <code>
  455. * $qb = $conn->createQueryBuilder()
  456. * ->select('u.id')
  457. * ->from('users', 'u')
  458. * </code>
  459. *
  460. * @param string $from The table
  461. * @param string $alias The alias of the table
  462. * @return QueryBuilder This QueryBuilder instance.
  463. */
  464. public function from($from, $alias)
  465. {
  466. return $this->add('from', array(
  467. 'table' => $from,
  468. 'alias' => $alias
  469. ), true);
  470. }
  471. /**
  472. * Creates and adds a join to the query.
  473. *
  474. * <code>
  475. * $qb = $conn->createQueryBuilder()
  476. * ->select('u.name')
  477. * ->from('users', 'u')
  478. * ->join('u', 'phonenumbers', 'p', 'p.is_primary = 1');
  479. * </code>
  480. *
  481. * @param string $fromAlias The alias that points to a from clause
  482. * @param string $join The table name to join
  483. * @param string $alias The alias of the join table
  484. * @param string $condition The condition for the join
  485. * @return QueryBuilder This QueryBuilder instance.
  486. */
  487. public function join($fromAlias, $join, $alias, $condition = null)
  488. {
  489. return $this->innerJoin($fromAlias, $join, $alias, $condition);
  490. }
  491. /**
  492. * Creates and adds a join to the query.
  493. *
  494. * <code>
  495. * $qb = $conn->createQueryBuilder()
  496. * ->select('u.name')
  497. * ->from('users', 'u')
  498. * ->innerJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
  499. * </code>
  500. *
  501. * @param string $fromAlias The alias that points to a from clause
  502. * @param string $join The table name to join
  503. * @param string $alias The alias of the join table
  504. * @param string $condition The condition for the join
  505. * @return QueryBuilder This QueryBuilder instance.
  506. */
  507. public function innerJoin($fromAlias, $join, $alias, $condition = null)
  508. {
  509. return $this->add('join', array(
  510. $fromAlias => array(
  511. 'joinType' => 'inner',
  512. 'joinTable' => $join,
  513. 'joinAlias' => $alias,
  514. 'joinCondition' => $condition
  515. )
  516. ), true);
  517. }
  518. /**
  519. * Creates and adds a left join to the query.
  520. *
  521. * <code>
  522. * $qb = $conn->createQueryBuilder()
  523. * ->select('u.name')
  524. * ->from('users', 'u')
  525. * ->leftJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
  526. * </code>
  527. *
  528. * @param string $fromAlias The alias that points to a from clause
  529. * @param string $join The table name to join
  530. * @param string $alias The alias of the join table
  531. * @param string $condition The condition for the join
  532. * @return QueryBuilder This QueryBuilder instance.
  533. */
  534. public function leftJoin($fromAlias, $join, $alias, $condition = null)
  535. {
  536. return $this->add('join', array(
  537. $fromAlias => array(
  538. 'joinType' => 'left',
  539. 'joinTable' => $join,
  540. 'joinAlias' => $alias,
  541. 'joinCondition' => $condition
  542. )
  543. ), true);
  544. }
  545. /**
  546. * Creates and adds a right join to the query.
  547. *
  548. * <code>
  549. * $qb = $conn->createQueryBuilder()
  550. * ->select('u.name')
  551. * ->from('users', 'u')
  552. * ->rightJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
  553. * </code>
  554. *
  555. * @param string $fromAlias The alias that points to a from clause
  556. * @param string $join The table name to join
  557. * @param string $alias The alias of the join table
  558. * @param string $condition The condition for the join
  559. * @return QueryBuilder This QueryBuilder instance.
  560. */
  561. public function rightJoin($fromAlias, $join, $alias, $condition = null)
  562. {
  563. return $this->add('join', array(
  564. $fromAlias => array(
  565. 'joinType' => 'right',
  566. 'joinTable' => $join,
  567. 'joinAlias' => $alias,
  568. 'joinCondition' => $condition
  569. )
  570. ), true);
  571. }
  572. /**
  573. * Sets a new value for a column in a bulk update query.
  574. *
  575. * <code>
  576. * $qb = $conn->createQueryBuilder()
  577. * ->update('users', 'u')
  578. * ->set('u.password', md5('password'))
  579. * ->where('u.id = ?');
  580. * </code>
  581. *
  582. * @param string $key The column to set.
  583. * @param string $value The value, expression, placeholder, etc.
  584. * @return QueryBuilder This QueryBuilder instance.
  585. */
  586. public function set($key, $value)
  587. {
  588. return $this->add('set', $key .' = ' . $value, true);
  589. }
  590. /**
  591. * Specifies one or more restrictions to the query result.
  592. * Replaces any previously specified restrictions, if any.
  593. *
  594. * <code>
  595. * $qb = $conn->createQueryBuilder()
  596. * ->select('u.name')
  597. * ->from('users', 'u')
  598. * ->where('u.id = ?');
  599. *
  600. * // You can optionally programatically build and/or expressions
  601. * $qb = $conn->createQueryBuilder();
  602. *
  603. * $or = $qb->expr()->orx();
  604. * $or->add($qb->expr()->eq('u.id', 1));
  605. * $or->add($qb->expr()->eq('u.id', 2));
  606. *
  607. * $qb->update('users', 'u')
  608. * ->set('u.password', md5('password'))
  609. * ->where($or);
  610. * </code>
  611. *
  612. * @param mixed $predicates The restriction predicates.
  613. * @return QueryBuilder This QueryBuilder instance.
  614. */
  615. public function where($predicates)
  616. {
  617. if ( ! (func_num_args() == 1 && $predicates instanceof CompositeExpression) ) {
  618. $predicates = new CompositeExpression(CompositeExpression::TYPE_AND, func_get_args());
  619. }
  620. return $this->add('where', $predicates);
  621. }
  622. /**
  623. * Adds one or more restrictions to the query results, forming a logical
  624. * conjunction with any previously specified restrictions.
  625. *
  626. * <code>
  627. * $qb = $conn->createQueryBuilder()
  628. * ->select('u')
  629. * ->from('users', 'u')
  630. * ->where('u.username LIKE ?')
  631. * ->andWhere('u.is_active = 1');
  632. * </code>
  633. *
  634. * @param mixed $where The query restrictions.
  635. * @return QueryBuilder This QueryBuilder instance.
  636. * @see where()
  637. */
  638. public function andWhere($where)
  639. {
  640. $where = $this->getQueryPart('where');
  641. $args = func_get_args();
  642. if ($where instanceof CompositeExpression && $where->getType() === CompositeExpression::TYPE_AND) {
  643. $where->addMultiple($args);
  644. } else {
  645. array_unshift($args, $where);
  646. $where = new CompositeExpression(CompositeExpression::TYPE_AND, $args);
  647. }
  648. return $this->add('where', $where, true);
  649. }
  650. /**
  651. * Adds one or more restrictions to the query results, forming a logical
  652. * disjunction with any previously specified restrictions.
  653. *
  654. * <code>
  655. * $qb = $em->createQueryBuilder()
  656. * ->select('u.name')
  657. * ->from('users', 'u')
  658. * ->where('u.id = 1')
  659. * ->orWhere('u.id = 2');
  660. * </code>
  661. *
  662. * @param mixed $where The WHERE statement
  663. * @return QueryBuilder $qb
  664. * @see where()
  665. */
  666. public function orWhere($where)
  667. {
  668. $where = $this->getQueryPart('where');
  669. $args = func_get_args();
  670. if ($where instanceof CompositeExpression && $where->getType() === CompositeExpression::TYPE_OR) {
  671. $where->addMultiple($args);
  672. } else {
  673. array_unshift($args, $where);
  674. $where = new CompositeExpression(CompositeExpression::TYPE_OR, $args);
  675. }
  676. return $this->add('where', $where, true);
  677. }
  678. /**
  679. * Specifies a grouping over the results of the query.
  680. * Replaces any previously specified groupings, if any.
  681. *
  682. * <code>
  683. * $qb = $conn->createQueryBuilder()
  684. * ->select('u.name')
  685. * ->from('users', 'u')
  686. * ->groupBy('u.id');
  687. * </code>
  688. *
  689. * @param mixed $groupBy The grouping expression.
  690. * @return QueryBuilder This QueryBuilder instance.
  691. */
  692. public function groupBy($groupBy)
  693. {
  694. if (empty($groupBy)) {
  695. return $this;
  696. }
  697. $groupBy = is_array($groupBy) ? $groupBy : func_get_args();
  698. return $this->add('groupBy', $groupBy, false);
  699. }
  700. /**
  701. * Adds a grouping expression to the query.
  702. *
  703. * <code>
  704. * $qb = $conn->createQueryBuilder()
  705. * ->select('u.name')
  706. * ->from('users', 'u')
  707. * ->groupBy('u.lastLogin');
  708. * ->addGroupBy('u.createdAt')
  709. * </code>
  710. *
  711. * @param mixed $groupBy The grouping expression.
  712. * @return QueryBuilder This QueryBuilder instance.
  713. */
  714. public function addGroupBy($groupBy)
  715. {
  716. if (empty($groupBy)) {
  717. return $this;
  718. }
  719. $groupBy = is_array($groupBy) ? $groupBy : func_get_args();
  720. return $this->add('groupBy', $groupBy, true);
  721. }
  722. /**
  723. * Specifies a restriction over the groups of the query.
  724. * Replaces any previous having restrictions, if any.
  725. *
  726. * @param mixed $having The restriction over the groups.
  727. * @return QueryBuilder This QueryBuilder instance.
  728. */
  729. public function having($having)
  730. {
  731. if ( ! (func_num_args() == 1 && $having instanceof CompositeExpression)) {
  732. $having = new CompositeExpression(CompositeExpression::TYPE_AND, func_get_args());
  733. }
  734. return $this->add('having', $having);
  735. }
  736. /**
  737. * Adds a restriction over the groups of the query, forming a logical
  738. * conjunction with any existing having restrictions.
  739. *
  740. * @param mixed $having The restriction to append.
  741. * @return QueryBuilder This QueryBuilder instance.
  742. */
  743. public function andHaving($having)
  744. {
  745. $having = $this->getQueryPart('having');
  746. $args = func_get_args();
  747. if ($having instanceof CompositeExpression && $having->getType() === CompositeExpression::TYPE_AND) {
  748. $having->addMultiple($args);
  749. } else {
  750. array_unshift($args, $having);
  751. $having = new CompositeExpression(CompositeExpression::TYPE_AND, $args);
  752. }
  753. return $this->add('having', $having);
  754. }
  755. /**
  756. * Adds a restriction over the groups of the query, forming a logical
  757. * disjunction with any existing having restrictions.
  758. *
  759. * @param mixed $having The restriction to add.
  760. * @return QueryBuilder This QueryBuilder instance.
  761. */
  762. public function orHaving($having)
  763. {
  764. $having = $this->getQueryPart('having');
  765. $args = func_get_args();
  766. if ($having instanceof CompositeExpression && $having->getType() === CompositeExpression::TYPE_OR) {
  767. $having->addMultiple($args);
  768. } else {
  769. array_unshift($args, $having);
  770. $having = new CompositeExpression(CompositeExpression::TYPE_OR, $args);
  771. }
  772. return $this->add('having', $having);
  773. }
  774. /**
  775. * Specifies an ordering for the query results.
  776. * Replaces any previously specified orderings, if any.
  777. *
  778. * @param string $sort The ordering expression.
  779. * @param string $order The ordering direction.
  780. * @return QueryBuilder This QueryBuilder instance.
  781. */
  782. public function orderBy($sort, $order = null)
  783. {
  784. return $this->add('orderBy', $sort . ' ' . (! $order ? 'ASC' : $order), false);
  785. }
  786. /**
  787. * Adds an ordering to the query results.
  788. *
  789. * @param string $sort The ordering expression.
  790. * @param string $order The ordering direction.
  791. * @return QueryBuilder This QueryBuilder instance.
  792. */
  793. public function addOrderBy($sort, $order = null)
  794. {
  795. return $this->add('orderBy', $sort . ' ' . (! $order ? 'ASC' : $order), true);
  796. }
  797. /**
  798. * Get a query part by its name.
  799. *
  800. * @param string $queryPartName
  801. * @return mixed $queryPart
  802. */
  803. public function getQueryPart($queryPartName)
  804. {
  805. return $this->sqlParts[$queryPartName];
  806. }
  807. /**
  808. * Get all query parts.
  809. *
  810. * @return array $sqlParts
  811. */
  812. public function getQueryParts()
  813. {
  814. return $this->sqlParts;
  815. }
  816. /**
  817. * Reset SQL parts
  818. *
  819. * @param array $queryPartNames
  820. * @return QueryBuilder
  821. */
  822. public function resetQueryParts($queryPartNames = null)
  823. {
  824. if (is_null($queryPartNames)) {
  825. $queryPartNames = array_keys($this->sqlParts);
  826. }
  827. foreach ($queryPartNames as $queryPartName) {
  828. $this->resetQueryPart($queryPartName);
  829. }
  830. return $this;
  831. }
  832. /**
  833. * Reset single SQL part
  834. *
  835. * @param string $queryPartName
  836. * @return QueryBuilder
  837. */
  838. public function resetQueryPart($queryPartName)
  839. {
  840. $this->sqlParts[$queryPartName] = is_array($this->sqlParts[$queryPartName])
  841. ? array() : null;
  842. $this->state = self::STATE_DIRTY;
  843. return $this;
  844. }
  845. private function getSQLForSelect()
  846. {
  847. $query = 'SELECT ' . implode(', ', $this->sqlParts['select']) . ' FROM ';
  848. $fromClauses = array();
  849. $joinsPending = true;
  850. $joinAliases = array();
  851. // Loop through all FROM clauses
  852. foreach ($this->sqlParts['from'] as $from) {
  853. $fromClause = $from['table'] . ' ' . $from['alias'];
  854. if ($joinsPending && isset($this->sqlParts['join'][$from['alias']])) {
  855. foreach ($this->sqlParts['join'] as $joins) {
  856. foreach ($joins as $join) {
  857. $fromClause .= ' ' . strtoupper($join['joinType'])
  858. . ' JOIN ' . $join['joinTable'] . ' ' . $join['joinAlias']
  859. . ' ON ' . ((string) $join['joinCondition']);
  860. $joinAliases[$join['joinAlias']] = true;
  861. }
  862. }
  863. $joinsPending = false;
  864. }
  865. $fromClauses[$from['alias']] = $fromClause;
  866. }
  867. // loop through all JOIN clauses for validation purpose
  868. $knownAliases = array_merge($fromClauses,$joinAliases);
  869. foreach ($this->sqlParts['join'] as $fromAlias => $joins) {
  870. if ( ! isset($knownAliases[$fromAlias]) ) {
  871. throw QueryException::unknownAlias($fromAlias, array_keys($knownAliases));
  872. }
  873. }
  874. $query .= implode(', ', $fromClauses)
  875. . ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : '')
  876. . ($this->sqlParts['groupBy'] ? ' GROUP BY ' . implode(', ', $this->sqlParts['groupBy']) : '')
  877. . ($this->sqlParts['having'] !== null ? ' HAVING ' . ((string) $this->sqlParts['having']) : '')
  878. . ($this->sqlParts['orderBy'] ? ' ORDER BY ' . implode(', ', $this->sqlParts['orderBy']) : '');
  879. return ($this->maxResults === null && $this->firstResult == null)
  880. ? $query
  881. : $this->connection->getDatabasePlatform()->modifyLimitQuery($query, $this->maxResults, $this->firstResult);
  882. }
  883. /**
  884. * Converts this instance into an UPDATE string in SQL.
  885. *
  886. * @return string
  887. */
  888. private function getSQLForUpdate()
  889. {
  890. $table = $this->sqlParts['from']['table'] . ($this->sqlParts['from']['alias'] ? ' ' . $this->sqlParts['from']['alias'] : '');
  891. $query = 'UPDATE ' . $table
  892. . ' SET ' . implode(", ", $this->sqlParts['set'])
  893. . ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : '');
  894. return $query;
  895. }
  896. /**
  897. * Converts this instance into a DELETE string in SQL.
  898. *
  899. * @return string
  900. */
  901. private function getSQLForDelete()
  902. {
  903. $table = $this->sqlParts['from']['table'] . ($this->sqlParts['from']['alias'] ? ' ' . $this->sqlParts['from']['alias'] : '');
  904. $query = 'DELETE FROM ' . $table . ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : '');
  905. return $query;
  906. }
  907. /**
  908. * Gets a string representation of this QueryBuilder which corresponds to
  909. * the final SQL query being constructed.
  910. *
  911. * @return string The string representation of this QueryBuilder.
  912. */
  913. public function __toString()
  914. {
  915. return $this->getSQL();
  916. }
  917. /**
  918. * Create a new named parameter and bind the value $value to it.
  919. *
  920. * This method provides a shortcut for PDOStatement::bindValue
  921. * when using prepared statements.
  922. *
  923. * The parameter $value specifies the value that you want to bind. If
  924. * $placeholder is not provided bindValue() will automatically create a
  925. * placeholder for you. An automatic placeholder will be of the name
  926. * ':dcValue1', ':dcValue2' etc.
  927. *
  928. * For more information see {@link http://php.net/pdostatement-bindparam}
  929. *
  930. * Example:
  931. * <code>
  932. * $value = 2;
  933. * $q->eq( 'id', $q->bindValue( $value ) );
  934. * $stmt = $q->executeQuery(); // executed with 'id = 2'
  935. * </code>
  936. *
  937. * @license New BSD License
  938. * @link http://www.zetacomponents.org
  939. * @param mixed $value
  940. * @param mixed $type
  941. * @param string $placeHolder the name to bind with. The string must start with a colon ':'.
  942. * @return string the placeholder name used.
  943. */
  944. public function createNamedParameter( $value, $type = \PDO::PARAM_STR, $placeHolder = null )
  945. {
  946. if ( $placeHolder === null ) {
  947. $this->boundCounter++;
  948. $placeHolder = ":dcValue" . $this->boundCounter;
  949. }
  950. $this->setParameter(substr($placeHolder, 1), $value, $type);
  951. return $placeHolder;
  952. }
  953. /**
  954. * Create a new positional parameter and bind the given value to it.
  955. *
  956. * Attention: If you are using positional parameters with the query builder you have
  957. * to be very careful to bind all parameters in the order they appear in the SQL
  958. * statement , otherwise they get bound in the wrong order which can lead to serious
  959. * bugs in your code.
  960. *
  961. * Example:
  962. * <code>
  963. * $qb = $conn->createQueryBuilder();
  964. * $qb->select('u.*')
  965. * ->from('users', 'u')
  966. * ->where('u.username = ' . $qb->createPositionalParameter('Foo', PDO::PARAM_STR))
  967. * ->orWhere('u.username = ' . $qb->createPositionalParameter('Bar', PDO::PARAM_STR))
  968. * </code>
  969. *
  970. * @param mixed $value
  971. * @param mixed $type
  972. * @return string
  973. */
  974. public function createPositionalParameter($value, $type = \PDO::PARAM_STR)
  975. {
  976. $this->boundCounter++;
  977. $this->setParameter($this->boundCounter, $value, $type);
  978. return "?";
  979. }
  980. }