select.inc 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613
  1. <?php
  2. /**
  3. * @addtogroup database
  4. * @{
  5. */
  6. require_once dirname(__FILE__) . '/query.inc';
  7. /**
  8. * Interface for extendable query objects.
  9. *
  10. * "Extenders" follow the "Decorator" OOP design pattern. That is, they wrap
  11. * and "decorate" another object. In our case, they implement the same interface
  12. * as select queries and wrap a select query, to which they delegate almost all
  13. * operations. Subclasses of this class may implement additional methods or
  14. * override existing methods as appropriate. Extenders may also wrap other
  15. * extender objects, allowing for arbitrarily complex "enhanced" queries.
  16. */
  17. interface QueryExtendableInterface {
  18. /**
  19. * Enhance this object by wrapping it in an extender object.
  20. *
  21. * @param $extender_name
  22. * The base name of the extending class. The base name will be checked
  23. * against the current database connection to allow driver-specific subclasses
  24. * as well, using the same logic as the query objects themselves. For example,
  25. * PagerDefault_mysql is the MySQL-specific override for PagerDefault.
  26. * @return QueryExtendableInterface
  27. * The extender object, which now contains a reference to this object.
  28. */
  29. public function extend($extender_name);
  30. }
  31. /**
  32. * Interface definition for a Select Query object.
  33. */
  34. interface SelectQueryInterface extends QueryConditionInterface, QueryAlterableInterface, QueryExtendableInterface, QueryPlaceholderInterface {
  35. /* Alter accessors to expose the query data to alter hooks. */
  36. /**
  37. * Returns a reference to the fields array for this query.
  38. *
  39. * Because this method returns by reference, alter hooks may edit the fields
  40. * array directly to make their changes. If just adding fields, however, the
  41. * use of addField() is preferred.
  42. *
  43. * Note that this method must be called by reference as well:
  44. *
  45. * @code
  46. * $fields =& $query->getFields();
  47. * @endcode
  48. *
  49. * @return
  50. * A reference to the fields array structure.
  51. */
  52. public function &getFields();
  53. /**
  54. * Returns a reference to the expressions array for this query.
  55. *
  56. * Because this method returns by reference, alter hooks may edit the expressions
  57. * array directly to make their changes. If just adding expressions, however, the
  58. * use of addExpression() is preferred.
  59. *
  60. * Note that this method must be called by reference as well:
  61. *
  62. * @code
  63. * $fields =& $query->getExpressions();
  64. * @endcode
  65. *
  66. * @return
  67. * A reference to the expression array structure.
  68. */
  69. public function &getExpressions();
  70. /**
  71. * Returns a reference to the order by array for this query.
  72. *
  73. * Because this method returns by reference, alter hooks may edit the order-by
  74. * array directly to make their changes. If just adding additional ordering
  75. * fields, however, the use of orderBy() is preferred.
  76. *
  77. * Note that this method must be called by reference as well:
  78. *
  79. * @code
  80. * $fields =& $query->getOrderBy();
  81. * @endcode
  82. *
  83. * @return
  84. * A reference to the expression array structure.
  85. */
  86. public function &getOrderBy();
  87. /**
  88. * Returns a reference to the group-by array for this query.
  89. *
  90. * Because this method returns by reference, alter hooks may edit the group-by
  91. * array directly to make their changes. If just adding additional grouping
  92. * fields, however, the use of groupBy() is preferred.
  93. *
  94. * Note that this method must be called by reference as well:
  95. *
  96. * @code
  97. * $fields =& $query->getGroupBy();
  98. * @endcode
  99. *
  100. * @return
  101. * A reference to the group-by array structure.
  102. */
  103. public function &getGroupBy();
  104. /**
  105. * Returns a reference to the tables array for this query.
  106. *
  107. * Because this method returns by reference, alter hooks may edit the tables
  108. * array directly to make their changes. If just adding tables, however, the
  109. * use of the join() methods is preferred.
  110. *
  111. * Note that this method must be called by reference as well:
  112. *
  113. * @code
  114. * $fields =& $query->getTables();
  115. * @endcode
  116. *
  117. * @return
  118. * A reference to the tables array structure.
  119. */
  120. public function &getTables();
  121. /**
  122. * Returns a reference to the union queries for this query. This include
  123. * queries for UNION, UNION ALL, and UNION DISTINCT.
  124. *
  125. * Because this method returns by reference, alter hooks may edit the tables
  126. * array directly to make their changes. If just adding union queries,
  127. * however, the use of the union() method is preferred.
  128. *
  129. * Note that this method must be called by reference as well:
  130. *
  131. * @code
  132. * $fields =& $query->getUnion();
  133. * @endcode
  134. *
  135. * @return
  136. * A reference to the union query array structure.
  137. */
  138. public function &getUnion();
  139. /**
  140. * Compiles and returns an associative array of the arguments for this prepared statement.
  141. *
  142. * @param $queryPlaceholder
  143. * When collecting the arguments of a subquery, the main placeholder
  144. * object should be passed as this parameter.
  145. *
  146. * @return
  147. * An associative array of all placeholder arguments for this query.
  148. */
  149. public function getArguments(QueryPlaceholderInterface $queryPlaceholder = NULL);
  150. /* Query building operations */
  151. /**
  152. * Sets this query to be DISTINCT.
  153. *
  154. * @param $distinct
  155. * TRUE to flag this query DISTINCT, FALSE to disable it.
  156. * @return SelectQueryInterface
  157. * The called object.
  158. */
  159. public function distinct($distinct = TRUE);
  160. /**
  161. * Adds a field to the list to be SELECTed.
  162. *
  163. * @param $table_alias
  164. * The name of the table from which the field comes, as an alias. Generally
  165. * you will want to use the return value of join() here to ensure that it is
  166. * valid.
  167. * @param $field
  168. * The name of the field.
  169. * @param $alias
  170. * The alias for this field. If not specified, one will be generated
  171. * automatically based on the $table_alias and $field. The alias will be
  172. * checked for uniqueness, so the requested alias may not be the alias
  173. * that is assigned in all cases.
  174. * @return
  175. * The unique alias that was assigned for this field.
  176. */
  177. public function addField($table_alias, $field, $alias = NULL);
  178. /**
  179. * Add multiple fields from the same table to be SELECTed.
  180. *
  181. * This method does not return the aliases set for the passed fields. In the
  182. * majority of cases that is not a problem, as the alias will be the field
  183. * name. However, if you do need to know the alias you can call getFields()
  184. * and examine the result to determine what alias was created. Alternatively,
  185. * simply use addField() for the few fields you care about and this method for
  186. * the rest.
  187. *
  188. * @param $table_alias
  189. * The name of the table from which the field comes, as an alias. Generally
  190. * you will want to use the return value of join() here to ensure that it is
  191. * valid.
  192. * @param $fields
  193. * An indexed array of fields present in the specified table that should be
  194. * included in this query. If not specified, $table_alias.* will be generated
  195. * without any aliases.
  196. * @return SelectQueryInterface
  197. * The called object.
  198. */
  199. public function fields($table_alias, array $fields = array());
  200. /**
  201. * Adds an expression to the list of "fields" to be SELECTed.
  202. *
  203. * An expression can be any arbitrary string that is valid SQL. That includes
  204. * various functions, which may in some cases be database-dependent. This
  205. * method makes no effort to correct for database-specific functions.
  206. *
  207. * @param $expression
  208. * The expression string. May contain placeholders.
  209. * @param $alias
  210. * The alias for this expression. If not specified, one will be generated
  211. * automatically in the form "expression_#". The alias will be checked for
  212. * uniqueness, so the requested alias may not be the alias that is assigned
  213. * in all cases.
  214. * @param $arguments
  215. * Any placeholder arguments needed for this expression.
  216. * @return
  217. * The unique alias that was assigned for this expression.
  218. */
  219. public function addExpression($expression, $alias = NULL, $arguments = array());
  220. /**
  221. * Default Join against another table in the database.
  222. *
  223. * This method is a convenience method for innerJoin().
  224. *
  225. * @param $table
  226. * The table against which to join.
  227. * @param $alias
  228. * The alias for the table. In most cases this should be the first letter
  229. * of the table, or the first letter of each "word" in the table.
  230. * @param $condition
  231. * The condition on which to join this table. If the join requires values,
  232. * this clause should use a named placeholder and the value or values to
  233. * insert should be passed in the 4th parameter. For the first table joined
  234. * on a query, this value is ignored as the first table is taken as the base
  235. * table. The token %alias can be used in this string to be replaced with
  236. * the actual alias. This is useful when $alias is modified by the database
  237. * system, for example, when joining the same table more than once.
  238. * @param $arguments
  239. * An array of arguments to replace into the $condition of this join.
  240. * @return
  241. * The unique alias that was assigned for this table.
  242. */
  243. public function join($table, $alias = NULL, $condition = NULL, $arguments = array());
  244. /**
  245. * Inner Join against another table in the database.
  246. *
  247. * @param $table
  248. * The table against which to join.
  249. * @param $alias
  250. * The alias for the table. In most cases this should be the first letter
  251. * of the table, or the first letter of each "word" in the table.
  252. * @param $condition
  253. * The condition on which to join this table. If the join requires values,
  254. * this clause should use a named placeholder and the value or values to
  255. * insert should be passed in the 4th parameter. For the first table joined
  256. * on a query, this value is ignored as the first table is taken as the base
  257. * table. The token %alias can be used in this string to be replaced with
  258. * the actual alias. This is useful when $alias is modified by the database
  259. * system, for example, when joining the same table more than once.
  260. * @param $arguments
  261. * An array of arguments to replace into the $condition of this join.
  262. * @return
  263. * The unique alias that was assigned for this table.
  264. */
  265. public function innerJoin($table, $alias = NULL, $condition = NULL, $arguments = array());
  266. /**
  267. * Left Outer Join against another table in the database.
  268. *
  269. * @param $table
  270. * The table against which to join.
  271. * @param $alias
  272. * The alias for the table. In most cases this should be the first letter
  273. * of the table, or the first letter of each "word" in the table.
  274. * @param $condition
  275. * The condition on which to join this table. If the join requires values,
  276. * this clause should use a named placeholder and the value or values to
  277. * insert should be passed in the 4th parameter. For the first table joined
  278. * on a query, this value is ignored as the first table is taken as the base
  279. * table. The token %alias can be used in this string to be replaced with
  280. * the actual alias. This is useful when $alias is modified by the database
  281. * system, for example, when joining the same table more than once.
  282. * @param $arguments
  283. * An array of arguments to replace into the $condition of this join.
  284. * @return
  285. * The unique alias that was assigned for this table.
  286. */
  287. public function leftJoin($table, $alias = NULL, $condition = NULL, $arguments = array());
  288. /**
  289. * Right Outer Join against another table in the database.
  290. *
  291. * @param $table
  292. * The table against which to join.
  293. * @param $alias
  294. * The alias for the table. In most cases this should be the first letter
  295. * of the table, or the first letter of each "word" in the table.
  296. * @param $condition
  297. * The condition on which to join this table. If the join requires values,
  298. * this clause should use a named placeholder and the value or values to
  299. * insert should be passed in the 4th parameter. For the first table joined
  300. * on a query, this value is ignored as the first table is taken as the base
  301. * table. The token %alias can be used in this string to be replaced with
  302. * the actual alias. This is useful when $alias is modified by the database
  303. * system, for example, when joining the same table more than once.
  304. * @param $arguments
  305. * An array of arguments to replace into the $condition of this join.
  306. * @return
  307. * The unique alias that was assigned for this table.
  308. */
  309. public function rightJoin($table, $alias = NULL, $condition = NULL, $arguments = array());
  310. /**
  311. * Join against another table in the database.
  312. *
  313. * This method does the "hard" work of queuing up a table to be joined against.
  314. * In some cases, that may include dipping into the Schema API to find the necessary
  315. * fields on which to join.
  316. *
  317. * @param $type
  318. * The type of join. Typically one one of INNER, LEFT OUTER, and RIGHT OUTER.
  319. * @param $table
  320. * The table against which to join. May be a string or another SelectQuery
  321. * object. If a query object is passed, it will be used as a subselect.
  322. * @param $alias
  323. * The alias for the table. In most cases this should be the first letter
  324. * of the table, or the first letter of each "word" in the table. If omitted,
  325. * one will be dynamically generated.
  326. * @param $condition
  327. * The condition on which to join this table. If the join requires values,
  328. * this clause should use a named placeholder and the value or values to
  329. * insert should be passed in the 4th parameter. For the first table joined
  330. * on a query, this value is ignored as the first table is taken as the base
  331. * table. The token %alias can be used in this string to be replaced with
  332. * the actual alias. This is useful when $alias is modified by the database
  333. * system, for example, when joining the same table more than once.
  334. * @param $arguments
  335. * An array of arguments to replace into the $condition of this join.
  336. * @return
  337. * The unique alias that was assigned for this table.
  338. */
  339. public function addJoin($type, $table, $alias = NULL, $condition = NULL, $arguments = array());
  340. /**
  341. * Orders the result set by a given field.
  342. *
  343. * If called multiple times, the query will order by each specified field in the
  344. * order this method is called.
  345. *
  346. * If the query uses DISTINCT or GROUP BY conditions, fields or expressions
  347. * that are used for the order must be selected to be compatible with some
  348. * databases like PostgreSQL. The PostgreSQL driver can handle simple cases
  349. * automatically but it is suggested to explicitly specify them. Additionally,
  350. * when ordering on an alias, the alias must be added before orderBy() is
  351. * called.
  352. *
  353. * @param $field
  354. * The field on which to order.
  355. * @param $direction
  356. * The direction to sort. Legal values are "ASC" and "DESC".
  357. * @return SelectQueryInterface
  358. * The called object.
  359. */
  360. public function orderBy($field, $direction = 'ASC');
  361. /**
  362. * Orders the result set by a random value.
  363. *
  364. * This may be stacked with other orderBy() calls. If so, the query will order
  365. * by each specified field, including this one, in the order called. Although
  366. * this method may be called multiple times on the same query, doing so
  367. * is not particularly useful.
  368. *
  369. * Note: The method used by most drivers may not scale to very large result
  370. * sets. If you need to work with extremely large data sets, you may create
  371. * your own database driver by subclassing off of an existing driver and
  372. * implementing your own randomization mechanism. See
  373. *
  374. * http://jan.kneschke.de/projects/mysql/order-by-rand/
  375. *
  376. * for an example of such an alternate sorting mechanism.
  377. *
  378. * @return SelectQueryInterface
  379. * The called object
  380. */
  381. public function orderRandom();
  382. /**
  383. * Restricts a query to a given range in the result set.
  384. *
  385. * If this method is called with no parameters, will remove any range
  386. * directives that have been set.
  387. *
  388. * @param $start
  389. * The first record from the result set to return. If NULL, removes any
  390. * range directives that are set.
  391. * @param $length
  392. * The number of records to return from the result set.
  393. * @return SelectQueryInterface
  394. * The called object.
  395. */
  396. public function range($start = NULL, $length = NULL);
  397. /**
  398. * Add another Select query to UNION to this one.
  399. *
  400. * Union queries consist of two or more queries whose
  401. * results are effectively concatenated together. Queries
  402. * will be UNIONed in the order they are specified, with
  403. * this object's query coming first. Duplicate columns will
  404. * be discarded. All forms of UNION are supported, using
  405. * the second '$type' argument.
  406. *
  407. * Note: All queries UNIONed together must have the same
  408. * field structure, in the same order. It is up to the
  409. * caller to ensure that they match properly. If they do
  410. * not, an SQL syntax error will result.
  411. *
  412. * @param $query
  413. * The query to UNION to this query.
  414. * @param $type
  415. * The type of UNION to add to the query. Defaults to plain
  416. * UNION.
  417. * @return SelectQueryInterface
  418. * The called object.
  419. */
  420. public function union(SelectQueryInterface $query, $type = '');
  421. /**
  422. * Groups the result set by the specified field.
  423. *
  424. * @param $field
  425. * The field on which to group. This should be the field as aliased.
  426. * @return SelectQueryInterface
  427. * The called object.
  428. */
  429. public function groupBy($field);
  430. /**
  431. * Get the equivalent COUNT query of this query as a new query object.
  432. *
  433. * @return SelectQueryInterface
  434. * A new SelectQuery object with no fields or expressions besides COUNT(*).
  435. */
  436. public function countQuery();
  437. /**
  438. * Indicates if preExecute() has already been called on that object.
  439. *
  440. * @return
  441. * TRUE is this query has already been prepared, FALSE otherwise.
  442. */
  443. public function isPrepared();
  444. /**
  445. * Generic preparation and validation for a SELECT query.
  446. *
  447. * @return
  448. * TRUE if the validation was successful, FALSE if not.
  449. */
  450. public function preExecute(SelectQueryInterface $query = NULL);
  451. /**
  452. * Helper function to build most common HAVING conditional clauses.
  453. *
  454. * This method can take a variable number of parameters. If called with two
  455. * parameters, they are taken as $field and $value with $operator having a value
  456. * of IN if $value is an array and = otherwise.
  457. *
  458. * @param $field
  459. * The name of the field to check. If you would like to add a more complex
  460. * condition involving operators or functions, use having().
  461. * @param $value
  462. * The value to test the field against. In most cases, this is a scalar. For more
  463. * complex options, it is an array. The meaning of each element in the array is
  464. * dependent on the $operator.
  465. * @param $operator
  466. * The comparison operator, such as =, <, or >=. It also accepts more complex
  467. * options such as IN, LIKE, or BETWEEN. Defaults to IN if $value is an array
  468. * = otherwise.
  469. * @return QueryConditionInterface
  470. * The called object.
  471. */
  472. public function havingCondition($field, $value = NULL, $operator = NULL);
  473. /**
  474. * Clone magic method.
  475. *
  476. * Select queries have dependent objects that must be deep-cloned. The
  477. * connection object itself, however, should not be cloned as that would
  478. * duplicate the connection itself.
  479. */
  480. public function __clone();
  481. /**
  482. * Add FOR UPDATE to the query.
  483. *
  484. * FOR UPDATE prevents the rows retrieved by the SELECT statement from being
  485. * modified or deleted by other transactions until the current transaction
  486. * ends. Other transactions that attempt UPDATE, DELETE, or SELECT FOR UPDATE
  487. * of these rows will be blocked until the current transaction ends.
  488. *
  489. * @param $set
  490. * IF TRUE, FOR UPDATE will be added to the query, if FALSE then it won't.
  491. *
  492. * @return QueryConditionInterface
  493. * The called object.
  494. */
  495. public function forUpdate($set = TRUE);
  496. }
  497. /**
  498. * The base extender class for Select queries.
  499. */
  500. class SelectQueryExtender implements SelectQueryInterface {
  501. /**
  502. * The SelectQuery object we are extending/decorating.
  503. *
  504. * @var SelectQueryInterface
  505. */
  506. protected $query;
  507. /**
  508. * The connection object on which to run this query.
  509. *
  510. * @var DatabaseConnection
  511. */
  512. protected $connection;
  513. /**
  514. * A unique identifier for this query object.
  515. */
  516. protected $uniqueIdentifier;
  517. /**
  518. * The placeholder counter.
  519. */
  520. protected $placeholder = 0;
  521. public function __construct(SelectQueryInterface $query, DatabaseConnection $connection) {
  522. $this->uniqueIdentifier = uniqid('', TRUE);
  523. $this->query = $query;
  524. $this->connection = $connection;
  525. }
  526. /**
  527. * Implements QueryPlaceholderInterface::uniqueIdentifier().
  528. */
  529. public function uniqueIdentifier() {
  530. return $this->uniqueIdentifier;
  531. }
  532. /**
  533. * Implements QueryPlaceholderInterface::nextPlaceholder().
  534. */
  535. public function nextPlaceholder() {
  536. return $this->placeholder++;
  537. }
  538. /* Implementations of QueryAlterableInterface. */
  539. public function addTag($tag) {
  540. $this->query->addTag($tag);
  541. return $this;
  542. }
  543. public function hasTag($tag) {
  544. return $this->query->hasTag($tag);
  545. }
  546. public function hasAllTags() {
  547. $args = func_get_args();
  548. return call_user_func_array(array($this->query, 'hasAllTags'), $args);
  549. }
  550. public function hasAnyTag() {
  551. $args = func_get_args();
  552. return call_user_func_array(array($this->query, 'hasAnyTag'), $args);
  553. }
  554. public function addMetaData($key, $object) {
  555. $this->query->addMetaData($key, $object);
  556. return $this;
  557. }
  558. public function getMetaData($key) {
  559. return $this->query->getMetaData($key);
  560. }
  561. /* Implementations of QueryConditionInterface for the WHERE clause. */
  562. public function condition($field, $value = NULL, $operator = NULL) {
  563. $this->query->condition($field, $value, $operator);
  564. return $this;
  565. }
  566. public function &conditions() {
  567. return $this->query->conditions();
  568. }
  569. public function arguments() {
  570. return $this->query->arguments();
  571. }
  572. public function where($snippet, $args = array()) {
  573. $this->query->where($snippet, $args);
  574. return $this;
  575. }
  576. public function compile(DatabaseConnection $connection, QueryPlaceholderInterface $queryPlaceholder) {
  577. return $this->query->compile($connection, $queryPlaceholder);
  578. }
  579. public function compiled() {
  580. return $this->query->compiled();
  581. }
  582. /* Implementations of QueryConditionInterface for the HAVING clause. */
  583. public function havingCondition($field, $value = NULL, $operator = '=') {
  584. $this->query->havingCondition($field, $value, $operator);
  585. return $this;
  586. }
  587. public function &havingConditions() {
  588. return $this->query->havingConditions();
  589. }
  590. public function havingArguments() {
  591. return $this->query->havingArguments();
  592. }
  593. public function having($snippet, $args = array()) {
  594. $this->query->having($snippet, $args);
  595. return $this;
  596. }
  597. public function havingCompile(DatabaseConnection $connection) {
  598. return $this->query->havingCompile($connection);
  599. }
  600. /* Implementations of QueryExtendableInterface. */
  601. public function extend($extender_name) {
  602. // The extender can be anywhere so this needs to go to the registry, which
  603. // is surely loaded by now.
  604. $class = $this->connection->getDriverClass($extender_name, array(), TRUE);
  605. return new $class($this, $this->connection);
  606. }
  607. /* Alter accessors to expose the query data to alter hooks. */
  608. public function &getFields() {
  609. return $this->query->getFields();
  610. }
  611. public function &getExpressions() {
  612. return $this->query->getExpressions();
  613. }
  614. public function &getOrderBy() {
  615. return $this->query->getOrderBy();
  616. }
  617. public function &getGroupBy() {
  618. return $this->query->getGroupBy();
  619. }
  620. public function &getTables() {
  621. return $this->query->getTables();
  622. }
  623. public function &getUnion() {
  624. return $this->query->getUnion();
  625. }
  626. public function getArguments(QueryPlaceholderInterface $queryPlaceholder = NULL) {
  627. return $this->query->getArguments($queryPlaceholder);
  628. }
  629. public function isPrepared() {
  630. return $this->query->isPrepared();
  631. }
  632. public function preExecute(SelectQueryInterface $query = NULL) {
  633. // If no query object is passed in, use $this.
  634. if (!isset($query)) {
  635. $query = $this;
  636. }
  637. return $this->query->preExecute($query);
  638. }
  639. public function execute() {
  640. // By calling preExecute() here, we force it to preprocess the extender
  641. // object rather than just the base query object. That means
  642. // hook_query_alter() gets access to the extended object.
  643. if (!$this->preExecute($this)) {
  644. return NULL;
  645. }
  646. return $this->query->execute();
  647. }
  648. public function distinct($distinct = TRUE) {
  649. $this->query->distinct($distinct);
  650. return $this;
  651. }
  652. public function addField($table_alias, $field, $alias = NULL) {
  653. return $this->query->addField($table_alias, $field, $alias);
  654. }
  655. public function fields($table_alias, array $fields = array()) {
  656. $this->query->fields($table_alias, $fields);
  657. return $this;
  658. }
  659. public function addExpression($expression, $alias = NULL, $arguments = array()) {
  660. return $this->query->addExpression($expression, $alias, $arguments);
  661. }
  662. public function join($table, $alias = NULL, $condition = NULL, $arguments = array()) {
  663. return $this->query->join($table, $alias, $condition, $arguments);
  664. }
  665. public function innerJoin($table, $alias = NULL, $condition = NULL, $arguments = array()) {
  666. return $this->query->innerJoin($table, $alias, $condition, $arguments);
  667. }
  668. public function leftJoin($table, $alias = NULL, $condition = NULL, $arguments = array()) {
  669. return $this->query->leftJoin($table, $alias, $condition, $arguments);
  670. }
  671. public function rightJoin($table, $alias = NULL, $condition = NULL, $arguments = array()) {
  672. return $this->query->rightJoin($table, $alias, $condition, $arguments);
  673. }
  674. public function addJoin($type, $table, $alias = NULL, $condition = NULL, $arguments = array()) {
  675. return $this->query->addJoin($type, $table, $alias, $condition, $arguments);
  676. }
  677. public function orderBy($field, $direction = 'ASC') {
  678. $this->query->orderBy($field, $direction);
  679. return $this;
  680. }
  681. public function orderRandom() {
  682. $this->query->orderRandom();
  683. return $this;
  684. }
  685. public function range($start = NULL, $length = NULL) {
  686. $this->query->range($start, $length);
  687. return $this;
  688. }
  689. public function union(SelectQueryInterface $query, $type = '') {
  690. $this->query->union($query, $type);
  691. return $this;
  692. }
  693. public function groupBy($field) {
  694. $this->query->groupBy($field);
  695. return $this;
  696. }
  697. public function forUpdate($set = TRUE) {
  698. $this->query->forUpdate($set);
  699. return $this;
  700. }
  701. public function countQuery() {
  702. return $this->query->countQuery();
  703. }
  704. function isNull($field) {
  705. $this->query->isNull($field);
  706. return $this;
  707. }
  708. function isNotNull($field) {
  709. $this->query->isNotNull($field);
  710. return $this;
  711. }
  712. public function exists(SelectQueryInterface $select) {
  713. $this->query->exists($select);
  714. return $this;
  715. }
  716. public function notExists(SelectQueryInterface $select) {
  717. $this->query->notExists($select);
  718. return $this;
  719. }
  720. public function __toString() {
  721. return (string) $this->query;
  722. }
  723. public function __clone() {
  724. $this->uniqueIdentifier = uniqid('', TRUE);
  725. // We need to deep-clone the query we're wrapping, which in turn may
  726. // deep-clone other objects. Exciting!
  727. $this->query = clone($this->query);
  728. }
  729. /**
  730. * Magic override for undefined methods.
  731. *
  732. * If one extender extends another extender, then methods in the inner extender
  733. * will not be exposed on the outer extender. That's because we cannot know
  734. * in advance what those methods will be, so we cannot provide wrapping
  735. * implementations as we do above. Instead, we use this slower catch-all method
  736. * to handle any additional methods.
  737. */
  738. public function __call($method, $args) {
  739. $return = call_user_func_array(array($this->query, $method), $args);
  740. // Some methods will return the called object as part of a fluent interface.
  741. // Others will return some useful value. If it's a value, then the caller
  742. // probably wants that value. If it's the called object, then we instead
  743. // return this object. That way we don't "lose" an extender layer when
  744. // chaining methods together.
  745. if ($return instanceof SelectQueryInterface) {
  746. return $this;
  747. }
  748. else {
  749. return $return;
  750. }
  751. }
  752. }
  753. /**
  754. * Query builder for SELECT statements.
  755. */
  756. class SelectQuery extends Query implements SelectQueryInterface {
  757. /**
  758. * The fields to SELECT.
  759. *
  760. * @var array
  761. */
  762. protected $fields = array();
  763. /**
  764. * The expressions to SELECT as virtual fields.
  765. *
  766. * @var array
  767. */
  768. protected $expressions = array();
  769. /**
  770. * The tables against which to JOIN.
  771. *
  772. * This property is a nested array. Each entry is an array representing
  773. * a single table against which to join. The structure of each entry is:
  774. *
  775. * array(
  776. * 'type' => $join_type (one of INNER, LEFT OUTER, RIGHT OUTER),
  777. * 'table' => $table,
  778. * 'alias' => $alias_of_the_table,
  779. * 'condition' => $condition_clause_on_which_to_join,
  780. * 'arguments' => $array_of_arguments_for_placeholders_in_the condition.
  781. * 'all_fields' => TRUE to SELECT $alias.*, FALSE or NULL otherwise.
  782. * )
  783. *
  784. * If $table is a string, it is taken as the name of a table. If it is
  785. * a SelectQuery object, it is taken as a subquery.
  786. *
  787. * @var array
  788. */
  789. protected $tables = array();
  790. /**
  791. * The fields by which to order this query.
  792. *
  793. * This is an associative array. The keys are the fields to order, and the value
  794. * is the direction to order, either ASC or DESC.
  795. *
  796. * @var array
  797. */
  798. protected $order = array();
  799. /**
  800. * The fields by which to group.
  801. *
  802. * @var array
  803. */
  804. protected $group = array();
  805. /**
  806. * The conditional object for the WHERE clause.
  807. *
  808. * @var DatabaseCondition
  809. */
  810. protected $where;
  811. /**
  812. * The conditional object for the HAVING clause.
  813. *
  814. * @var DatabaseCondition
  815. */
  816. protected $having;
  817. /**
  818. * Whether or not this query should be DISTINCT
  819. *
  820. * @var boolean
  821. */
  822. protected $distinct = FALSE;
  823. /**
  824. * The range limiters for this query.
  825. *
  826. * @var array
  827. */
  828. protected $range;
  829. /**
  830. * An array whose elements specify a query to UNION, and the UNION type. The
  831. * 'type' key may be '', 'ALL', or 'DISTINCT' to represent a 'UNION',
  832. * 'UNION ALL', or 'UNION DISTINCT' statement, respectively.
  833. *
  834. * All entries in this array will be applied from front to back, with the
  835. * first query to union on the right of the original query, the second union
  836. * to the right of the first, etc.
  837. *
  838. * @var array
  839. */
  840. protected $union = array();
  841. /**
  842. * Indicates if preExecute() has already been called.
  843. * @var boolean
  844. */
  845. protected $prepared = FALSE;
  846. /**
  847. * The FOR UPDATE status
  848. */
  849. protected $forUpdate = FALSE;
  850. public function __construct($table, $alias = NULL, DatabaseConnection $connection, $options = array()) {
  851. $options['return'] = Database::RETURN_STATEMENT;
  852. parent::__construct($connection, $options);
  853. $this->where = new DatabaseCondition('AND');
  854. $this->having = new DatabaseCondition('AND');
  855. $this->addJoin(NULL, $table, $alias);
  856. }
  857. /* Implementations of QueryAlterableInterface. */
  858. public function addTag($tag) {
  859. $this->alterTags[$tag] = 1;
  860. return $this;
  861. }
  862. public function hasTag($tag) {
  863. return isset($this->alterTags[$tag]);
  864. }
  865. public function hasAllTags() {
  866. $args = func_get_args();
  867. return !(boolean)array_diff($args, array_keys($this->alterTags));
  868. }
  869. public function hasAnyTag() {
  870. $args = func_get_args();
  871. return (boolean)array_intersect($args, array_keys($this->alterTags));
  872. }
  873. public function addMetaData($key, $object) {
  874. $this->alterMetaData[$key] = $object;
  875. return $this;
  876. }
  877. public function getMetaData($key) {
  878. return isset($this->alterMetaData[$key]) ? $this->alterMetaData[$key] : NULL;
  879. }
  880. /* Implementations of QueryConditionInterface for the WHERE clause. */
  881. public function condition($field, $value = NULL, $operator = NULL) {
  882. $this->where->condition($field, $value, $operator);
  883. return $this;
  884. }
  885. public function &conditions() {
  886. return $this->where->conditions();
  887. }
  888. public function arguments() {
  889. if (!$this->compiled()) {
  890. return NULL;
  891. }
  892. $args = $this->where->arguments() + $this->having->arguments();
  893. foreach ($this->tables as $table) {
  894. if ($table['arguments']) {
  895. $args += $table['arguments'];
  896. }
  897. // If this table is a subquery, grab its arguments recursively.
  898. if ($table['table'] instanceof SelectQueryInterface) {
  899. $args += $table['table']->arguments();
  900. }
  901. }
  902. foreach ($this->expressions as $expression) {
  903. if ($expression['arguments']) {
  904. $args += $expression['arguments'];
  905. }
  906. }
  907. // If there are any dependent queries to UNION,
  908. // incorporate their arguments recursively.
  909. foreach ($this->union as $union) {
  910. $args += $union['query']->arguments();
  911. }
  912. return $args;
  913. }
  914. public function where($snippet, $args = array()) {
  915. $this->where->where($snippet, $args);
  916. return $this;
  917. }
  918. public function isNull($field) {
  919. $this->where->isNull($field);
  920. return $this;
  921. }
  922. public function isNotNull($field) {
  923. $this->where->isNotNull($field);
  924. return $this;
  925. }
  926. public function exists(SelectQueryInterface $select) {
  927. $this->where->exists($select);
  928. return $this;
  929. }
  930. public function notExists(SelectQueryInterface $select) {
  931. $this->where->notExists($select);
  932. return $this;
  933. }
  934. public function compile(DatabaseConnection $connection, QueryPlaceholderInterface $queryPlaceholder) {
  935. $this->where->compile($connection, $queryPlaceholder);
  936. $this->having->compile($connection, $queryPlaceholder);
  937. foreach ($this->tables as $table) {
  938. // If this table is a subquery, compile it recursively.
  939. if ($table['table'] instanceof SelectQueryInterface) {
  940. $table['table']->compile($connection, $queryPlaceholder);
  941. }
  942. }
  943. // If there are any dependent queries to UNION, compile it recursively.
  944. foreach ($this->union as $union) {
  945. $union['query']->compile($connection, $queryPlaceholder);
  946. }
  947. }
  948. public function compiled() {
  949. if (!$this->where->compiled() || !$this->having->compiled()) {
  950. return FALSE;
  951. }
  952. foreach ($this->tables as $table) {
  953. // If this table is a subquery, check its status recursively.
  954. if ($table['table'] instanceof SelectQueryInterface) {
  955. if (!$table['table']->compiled()) {
  956. return FALSE;
  957. }
  958. }
  959. }
  960. foreach ($this->union as $union) {
  961. if (!$union['query']->compiled()) {
  962. return FALSE;
  963. }
  964. }
  965. return TRUE;
  966. }
  967. /* Implementations of QueryConditionInterface for the HAVING clause. */
  968. public function havingCondition($field, $value = NULL, $operator = NULL) {
  969. $this->having->condition($field, $value, $operator);
  970. return $this;
  971. }
  972. public function &havingConditions() {
  973. return $this->having->conditions();
  974. }
  975. public function havingArguments() {
  976. return $this->having->arguments();
  977. }
  978. public function having($snippet, $args = array()) {
  979. $this->having->where($snippet, $args);
  980. return $this;
  981. }
  982. public function havingCompile(DatabaseConnection $connection) {
  983. return $this->having->compile($connection, $this);
  984. }
  985. /* Implementations of QueryExtendableInterface. */
  986. public function extend($extender_name) {
  987. $override_class = $extender_name . '_' . $this->connection->driver();
  988. if (class_exists($override_class)) {
  989. $extender_name = $override_class;
  990. }
  991. return new $extender_name($this, $this->connection);
  992. }
  993. public function havingIsNull($field) {
  994. $this->having->isNull($field);
  995. return $this;
  996. }
  997. public function havingIsNotNull($field) {
  998. $this->having->isNotNull($field);
  999. return $this;
  1000. }
  1001. public function havingExists(SelectQueryInterface $select) {
  1002. $this->having->exists($select);
  1003. return $this;
  1004. }
  1005. public function havingNotExists(SelectQueryInterface $select) {
  1006. $this->having->notExists($select);
  1007. return $this;
  1008. }
  1009. public function forUpdate($set = TRUE) {
  1010. if (isset($set)) {
  1011. $this->forUpdate = $set;
  1012. }
  1013. return $this;
  1014. }
  1015. /* Alter accessors to expose the query data to alter hooks. */
  1016. public function &getFields() {
  1017. return $this->fields;
  1018. }
  1019. public function &getExpressions() {
  1020. return $this->expressions;
  1021. }
  1022. public function &getOrderBy() {
  1023. return $this->order;
  1024. }
  1025. public function &getGroupBy() {
  1026. return $this->group;
  1027. }
  1028. public function &getTables() {
  1029. return $this->tables;
  1030. }
  1031. public function &getUnion() {
  1032. return $this->union;
  1033. }
  1034. public function getArguments(QueryPlaceholderInterface $queryPlaceholder = NULL) {
  1035. if (!isset($queryPlaceholder)) {
  1036. $queryPlaceholder = $this;
  1037. }
  1038. $this->compile($this->connection, $queryPlaceholder);
  1039. return $this->arguments();
  1040. }
  1041. /**
  1042. * Indicates if preExecute() has already been called on that object.
  1043. */
  1044. public function isPrepared() {
  1045. return $this->prepared;
  1046. }
  1047. /**
  1048. * Generic preparation and validation for a SELECT query.
  1049. *
  1050. * @return
  1051. * TRUE if the validation was successful, FALSE if not.
  1052. */
  1053. public function preExecute(SelectQueryInterface $query = NULL) {
  1054. // If no query object is passed in, use $this.
  1055. if (!isset($query)) {
  1056. $query = $this;
  1057. }
  1058. // Only execute this once.
  1059. if ($query->isPrepared()) {
  1060. return TRUE;
  1061. }
  1062. // Modules may alter all queries or only those having a particular tag.
  1063. if (isset($this->alterTags)) {
  1064. $hooks = array('query');
  1065. foreach ($this->alterTags as $tag => $value) {
  1066. $hooks[] = 'query_' . $tag;
  1067. }
  1068. drupal_alter($hooks, $query);
  1069. }
  1070. $this->prepared = TRUE;
  1071. // Now also prepare any sub-queries.
  1072. foreach ($this->tables as $table) {
  1073. if ($table['table'] instanceof SelectQueryInterface) {
  1074. $table['table']->preExecute();
  1075. }
  1076. }
  1077. foreach ($this->union as $union) {
  1078. $union['query']->preExecute();
  1079. }
  1080. return $this->prepared;
  1081. }
  1082. public function execute() {
  1083. // If validation fails, simply return NULL.
  1084. // Note that validation routines in preExecute() may throw exceptions instead.
  1085. if (!$this->preExecute()) {
  1086. return NULL;
  1087. }
  1088. $args = $this->getArguments();
  1089. return $this->connection->query((string) $this, $args, $this->queryOptions);
  1090. }
  1091. public function distinct($distinct = TRUE) {
  1092. $this->distinct = $distinct;
  1093. return $this;
  1094. }
  1095. public function addField($table_alias, $field, $alias = NULL) {
  1096. // If no alias is specified, first try the field name itself.
  1097. if (empty($alias)) {
  1098. $alias = $field;
  1099. }
  1100. // If that's already in use, try the table name and field name.
  1101. if (!empty($this->fields[$alias])) {
  1102. $alias = $table_alias . '_' . $field;
  1103. }
  1104. // If that is already used, just add a counter until we find an unused alias.
  1105. $alias_candidate = $alias;
  1106. $count = 2;
  1107. while (!empty($this->fields[$alias_candidate])) {
  1108. $alias_candidate = $alias . '_' . $count++;
  1109. }
  1110. $alias = $alias_candidate;
  1111. $this->fields[$alias] = array(
  1112. 'field' => $field,
  1113. 'table' => $table_alias,
  1114. 'alias' => $alias,
  1115. );
  1116. return $alias;
  1117. }
  1118. public function fields($table_alias, array $fields = array()) {
  1119. if ($fields) {
  1120. foreach ($fields as $field) {
  1121. // We don't care what alias was assigned.
  1122. $this->addField($table_alias, $field);
  1123. }
  1124. }
  1125. else {
  1126. // We want all fields from this table.
  1127. $this->tables[$table_alias]['all_fields'] = TRUE;
  1128. }
  1129. return $this;
  1130. }
  1131. public function addExpression($expression, $alias = NULL, $arguments = array()) {
  1132. if (empty($alias)) {
  1133. $alias = 'expression';
  1134. }
  1135. $alias_candidate = $alias;
  1136. $count = 2;
  1137. while (!empty($this->expressions[$alias_candidate])) {
  1138. $alias_candidate = $alias . '_' . $count++;
  1139. }
  1140. $alias = $alias_candidate;
  1141. $this->expressions[$alias] = array(
  1142. 'expression' => $expression,
  1143. 'alias' => $alias,
  1144. 'arguments' => $arguments,
  1145. );
  1146. return $alias;
  1147. }
  1148. public function join($table, $alias = NULL, $condition = NULL, $arguments = array()) {
  1149. return $this->addJoin('INNER', $table, $alias, $condition, $arguments);
  1150. }
  1151. public function innerJoin($table, $alias = NULL, $condition = NULL, $arguments = array()) {
  1152. return $this->addJoin('INNER', $table, $alias, $condition, $arguments);
  1153. }
  1154. public function leftJoin($table, $alias = NULL, $condition = NULL, $arguments = array()) {
  1155. return $this->addJoin('LEFT OUTER', $table, $alias, $condition, $arguments);
  1156. }
  1157. public function rightJoin($table, $alias = NULL, $condition = NULL, $arguments = array()) {
  1158. return $this->addJoin('RIGHT OUTER', $table, $alias, $condition, $arguments);
  1159. }
  1160. public function addJoin($type, $table, $alias = NULL, $condition = NULL, $arguments = array()) {
  1161. if (empty($alias)) {
  1162. if ($table instanceof SelectQueryInterface) {
  1163. $alias = 'subquery';
  1164. }
  1165. else {
  1166. $alias = $table;
  1167. }
  1168. }
  1169. $alias_candidate = $alias;
  1170. $count = 2;
  1171. while (!empty($this->tables[$alias_candidate])) {
  1172. $alias_candidate = $alias . '_' . $count++;
  1173. }
  1174. $alias = $alias_candidate;
  1175. if (is_string($condition)) {
  1176. $condition = str_replace('%alias', $alias, $condition);
  1177. }
  1178. $this->tables[$alias] = array(
  1179. 'join type' => $type,
  1180. 'table' => $table,
  1181. 'alias' => $alias,
  1182. 'condition' => $condition,
  1183. 'arguments' => $arguments,
  1184. );
  1185. return $alias;
  1186. }
  1187. public function orderBy($field, $direction = 'ASC') {
  1188. $this->order[$field] = $direction;
  1189. return $this;
  1190. }
  1191. public function orderRandom() {
  1192. $alias = $this->addExpression('RAND()', 'random_field');
  1193. $this->orderBy($alias);
  1194. return $this;
  1195. }
  1196. public function range($start = NULL, $length = NULL) {
  1197. $this->range = func_num_args() ? array('start' => $start, 'length' => $length) : array();
  1198. return $this;
  1199. }
  1200. public function union(SelectQueryInterface $query, $type = '') {
  1201. // Handle UNION aliasing.
  1202. switch ($type) {
  1203. // Fold UNION DISTINCT to UNION for better cross database support.
  1204. case 'DISTINCT':
  1205. case '':
  1206. $type = 'UNION';
  1207. break;
  1208. case 'ALL':
  1209. $type = 'UNION ALL';
  1210. default:
  1211. }
  1212. $this->union[] = array(
  1213. 'type' => $type,
  1214. 'query' => $query,
  1215. );
  1216. return $this;
  1217. }
  1218. public function groupBy($field) {
  1219. $this->group[$field] = $field;
  1220. return $this;
  1221. }
  1222. public function countQuery() {
  1223. // Create our new query object that we will mutate into a count query.
  1224. $count = clone($this);
  1225. $group_by = $count->getGroupBy();
  1226. $having = $count->havingConditions();
  1227. if (!$count->distinct && !isset($having[0])) {
  1228. // When not executing a distinct query, we can zero-out existing fields
  1229. // and expressions that are not used by a GROUP BY or HAVING. Fields
  1230. // listed in a GROUP BY or HAVING clause need to be present in the
  1231. // query.
  1232. $fields =& $count->getFields();
  1233. foreach (array_keys($fields) as $field) {
  1234. if (empty($group_by[$field])) {
  1235. unset($fields[$field]);
  1236. }
  1237. }
  1238. $expressions =& $count->getExpressions();
  1239. foreach (array_keys($expressions) as $field) {
  1240. if (empty($group_by[$field])) {
  1241. unset($expressions[$field]);
  1242. }
  1243. }
  1244. // Also remove 'all_fields' statements, which are expanded into tablename.*
  1245. // when the query is executed.
  1246. foreach ($count->tables as $alias => &$table) {
  1247. unset($table['all_fields']);
  1248. }
  1249. }
  1250. // If we've just removed all fields from the query, make sure there is at
  1251. // least one so that the query still runs.
  1252. $count->addExpression('1');
  1253. // Ordering a count query is a waste of cycles, and breaks on some
  1254. // databases anyway.
  1255. $orders = &$count->getOrderBy();
  1256. $orders = array();
  1257. if ($count->distinct && !empty($group_by)) {
  1258. // If the query is distinct and contains a GROUP BY, we need to remove the
  1259. // distinct because SQL99 does not support counting on distinct multiple fields.
  1260. $count->distinct = FALSE;
  1261. }
  1262. $query = $this->connection->select($count);
  1263. $query->addExpression('COUNT(*)');
  1264. return $query;
  1265. }
  1266. public function __toString() {
  1267. // For convenience, we compile the query ourselves if the caller forgot
  1268. // to do it. This allows constructs like "(string) $query" to work. When
  1269. // the query will be executed, it will be recompiled using the proper
  1270. // placeholder generator anyway.
  1271. if (!$this->compiled()) {
  1272. $this->compile($this->connection, $this);
  1273. }
  1274. // Create a sanitized comment string to prepend to the query.
  1275. $comments = $this->connection->makeComment($this->comments);
  1276. // SELECT
  1277. $query = $comments . 'SELECT ';
  1278. if ($this->distinct) {
  1279. $query .= 'DISTINCT ';
  1280. }
  1281. // FIELDS and EXPRESSIONS
  1282. $fields = array();
  1283. foreach ($this->tables as $alias => $table) {
  1284. if (!empty($table['all_fields'])) {
  1285. $fields[] = $this->connection->escapeTable($alias) . '.*';
  1286. }
  1287. }
  1288. foreach ($this->fields as $alias => $field) {
  1289. // Always use the AS keyword for field aliases, as some
  1290. // databases require it (e.g., PostgreSQL).
  1291. $fields[] = (isset($field['table']) ? $this->connection->escapeTable($field['table']) . '.' : '') . $this->connection->escapeField($field['field']) . ' AS ' . $this->connection->escapeAlias($field['alias']);
  1292. }
  1293. foreach ($this->expressions as $alias => $expression) {
  1294. $fields[] = $expression['expression'] . ' AS ' . $this->connection->escapeAlias($expression['alias']);
  1295. }
  1296. $query .= implode(', ', $fields);
  1297. // FROM - We presume all queries have a FROM, as any query that doesn't won't need the query builder anyway.
  1298. $query .= "\nFROM ";
  1299. foreach ($this->tables as $alias => $table) {
  1300. $query .= "\n";
  1301. if (isset($table['join type'])) {
  1302. $query .= $table['join type'] . ' JOIN ';
  1303. }
  1304. // If the table is a subquery, compile it and integrate it into this query.
  1305. if ($table['table'] instanceof SelectQueryInterface) {
  1306. // Run preparation steps on this sub-query before converting to string.
  1307. $subquery = $table['table'];
  1308. $subquery->preExecute();
  1309. $table_string = '(' . (string) $subquery . ')';
  1310. }
  1311. else {
  1312. $table_string = '{' . $this->connection->escapeTable($table['table']) . '}';
  1313. }
  1314. // Don't use the AS keyword for table aliases, as some
  1315. // databases don't support it (e.g., Oracle).
  1316. $query .= $table_string . ' ' . $this->connection->escapeTable($table['alias']);
  1317. if (!empty($table['condition'])) {
  1318. $query .= ' ON ' . $table['condition'];
  1319. }
  1320. }
  1321. // WHERE
  1322. if (count($this->where)) {
  1323. // There is an implicit string cast on $this->condition.
  1324. $query .= "\nWHERE " . $this->where;
  1325. }
  1326. // GROUP BY
  1327. if ($this->group) {
  1328. $query .= "\nGROUP BY " . implode(', ', $this->group);
  1329. }
  1330. // HAVING
  1331. if (count($this->having)) {
  1332. // There is an implicit string cast on $this->having.
  1333. $query .= "\nHAVING " . $this->having;
  1334. }
  1335. // ORDER BY
  1336. if ($this->order) {
  1337. $query .= "\nORDER BY ";
  1338. $fields = array();
  1339. foreach ($this->order as $field => $direction) {
  1340. $fields[] = $field . ' ' . $direction;
  1341. }
  1342. $query .= implode(', ', $fields);
  1343. }
  1344. // RANGE
  1345. // There is no universal SQL standard for handling range or limit clauses.
  1346. // Fortunately, all core-supported databases use the same range syntax.
  1347. // Databases that need a different syntax can override this method and
  1348. // do whatever alternate logic they need to.
  1349. if (!empty($this->range)) {
  1350. $query .= "\nLIMIT " . (int) $this->range['length'] . " OFFSET " . (int) $this->range['start'];
  1351. }
  1352. // UNION is a little odd, as the select queries to combine are passed into
  1353. // this query, but syntactically they all end up on the same level.
  1354. if ($this->union) {
  1355. foreach ($this->union as $union) {
  1356. $query .= ' ' . $union['type'] . ' ' . (string) $union['query'];
  1357. }
  1358. }
  1359. if ($this->forUpdate) {
  1360. $query .= ' FOR UPDATE';
  1361. }
  1362. return $query;
  1363. }
  1364. public function __clone() {
  1365. // On cloning, also clone the dependent objects. However, we do not
  1366. // want to clone the database connection object as that would duplicate the
  1367. // connection itself.
  1368. $this->where = clone($this->where);
  1369. $this->having = clone($this->having);
  1370. foreach ($this->union as $key => $aggregate) {
  1371. $this->union[$key]['query'] = clone($aggregate['query']);
  1372. }
  1373. }
  1374. }
  1375. /**
  1376. * @} End of "addtogroup database".
  1377. */