QueryBuilder.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  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. }