QueryBuilder.php 40 KB

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