QueryBuilder.php 35 KB

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