query.inc 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964
  1. <?php
  2. /**
  3. * @addtogroup database
  4. * @{
  5. */
  6. /**
  7. * @file
  8. * Non-specific Database query code. Used by all engines.
  9. */
  10. /**
  11. * Interface for a conditional clause in a query.
  12. */
  13. interface QueryConditionInterface {
  14. /**
  15. * Helper function: builds the most common conditional clauses.
  16. *
  17. * This method can take a variable number of parameters. If called with two
  18. * parameters, they are taken as $field and $value with $operator having a
  19. * value of IN if $value is an array and = otherwise.
  20. *
  21. * Do not use this method to test for NULL values. Instead, use
  22. * QueryConditionInterface::isNull() or QueryConditionInterface::isNotNull().
  23. *
  24. * @param $field
  25. * The name of the field to check. If you would like to add a more complex
  26. * condition involving operators or functions, use where().
  27. * @param $value
  28. * The value to test the field against. In most cases, this is a scalar.
  29. * For more complex options, it is an array. The meaning of each element in
  30. * the array is dependent on the $operator.
  31. * @param $operator
  32. * The comparison operator, such as =, <, or >=. It also accepts more
  33. * complex options such as IN, LIKE, or BETWEEN. Defaults to IN if $value is
  34. * an array, and = otherwise.
  35. *
  36. * @return QueryConditionInterface
  37. * The called object.
  38. *
  39. * @see QueryConditionInterface::isNull()
  40. * @see QueryConditionInterface::isNotNull()
  41. */
  42. public function condition($field, $value = NULL, $operator = NULL);
  43. /**
  44. * Adds an arbitrary WHERE clause to the query.
  45. *
  46. * @param $snippet
  47. * A portion of a WHERE clause as a prepared statement. It must use named
  48. * placeholders, not ? placeholders.
  49. * @param $args
  50. * An associative array of arguments.
  51. *
  52. * @return QueryConditionInterface
  53. * The called object.
  54. */
  55. public function where($snippet, $args = array());
  56. /**
  57. * Sets a condition that the specified field be NULL.
  58. *
  59. * @param $field
  60. * The name of the field to check.
  61. *
  62. * @return QueryConditionInterface
  63. * The called object.
  64. */
  65. public function isNull($field);
  66. /**
  67. * Sets a condition that the specified field be NOT NULL.
  68. *
  69. * @param $field
  70. * The name of the field to check.
  71. *
  72. * @return QueryConditionInterface
  73. * The called object.
  74. */
  75. public function isNotNull($field);
  76. /**
  77. * Sets a condition that the specified subquery returns values.
  78. *
  79. * @param SelectQueryInterface $select
  80. * The subquery that must contain results.
  81. *
  82. * @return QueryConditionInterface
  83. * The called object.
  84. */
  85. public function exists(SelectQueryInterface $select);
  86. /**
  87. * Sets a condition that the specified subquery returns no values.
  88. *
  89. * @param SelectQueryInterface $select
  90. * The subquery that must not contain results.
  91. *
  92. * @return QueryConditionInterface
  93. * The called object.
  94. */
  95. public function notExists(SelectQueryInterface $select);
  96. /**
  97. * Gets a complete list of all conditions in this conditional clause.
  98. *
  99. * This method returns by reference. That allows alter hooks to access the
  100. * data structure directly and manipulate it before it gets compiled.
  101. *
  102. * The data structure that is returned is an indexed array of entries, where
  103. * each entry looks like the following:
  104. * @code
  105. * array(
  106. * 'field' => $field,
  107. * 'value' => $value,
  108. * 'operator' => $operator,
  109. * );
  110. * @endcode
  111. *
  112. * In the special case that $operator is NULL, the $field is taken as a raw
  113. * SQL snippet (possibly containing a function) and $value is an associative
  114. * array of placeholders for the snippet.
  115. *
  116. * There will also be a single array entry of #conjunction, which is the
  117. * conjunction that will be applied to the array, such as AND.
  118. */
  119. public function &conditions();
  120. /**
  121. * Gets a complete list of all values to insert into the prepared statement.
  122. *
  123. * @return
  124. * An associative array of placeholders and values.
  125. */
  126. public function arguments();
  127. /**
  128. * Compiles the saved conditions for later retrieval.
  129. *
  130. * This method does not return anything, but simply prepares data to be
  131. * retrieved via __toString() and arguments().
  132. *
  133. * @param $connection
  134. * The database connection for which to compile the conditionals.
  135. * @param $queryPlaceholder
  136. * The query this condition belongs to. If not given, the current query is
  137. * used.
  138. */
  139. public function compile(DatabaseConnection $connection, QueryPlaceholderInterface $queryPlaceholder);
  140. /**
  141. * Check whether a condition has been previously compiled.
  142. *
  143. * @return
  144. * TRUE if the condition has been previously compiled.
  145. */
  146. public function compiled();
  147. }
  148. /**
  149. * Interface for a query that can be manipulated via an alter hook.
  150. */
  151. interface QueryAlterableInterface {
  152. /**
  153. * Adds a tag to a query.
  154. *
  155. * Tags are strings that identify a query. A query may have any number of
  156. * tags. Tags are used to mark a query so that alter hooks may decide if they
  157. * wish to take action. Tags should be all lower-case and contain only
  158. * letters, numbers, and underscore, and start with a letter. That is, they
  159. * should follow the same rules as PHP identifiers in general.
  160. *
  161. * @param $tag
  162. * The tag to add.
  163. *
  164. * @return QueryAlterableInterface
  165. * The called object.
  166. */
  167. public function addTag($tag);
  168. /**
  169. * Determines if a given query has a given tag.
  170. *
  171. * @param $tag
  172. * The tag to check.
  173. *
  174. * @return
  175. * TRUE if this query has been marked with this tag, FALSE otherwise.
  176. */
  177. public function hasTag($tag);
  178. /**
  179. * Determines if a given query has all specified tags.
  180. *
  181. * @param $tags
  182. * A variable number of arguments, one for each tag to check.
  183. *
  184. * @return
  185. * TRUE if this query has been marked with all specified tags, FALSE
  186. * otherwise.
  187. */
  188. public function hasAllTags();
  189. /**
  190. * Determines if a given query has any specified tag.
  191. *
  192. * @param $tags
  193. * A variable number of arguments, one for each tag to check.
  194. *
  195. * @return
  196. * TRUE if this query has been marked with at least one of the specified
  197. * tags, FALSE otherwise.
  198. */
  199. public function hasAnyTag();
  200. /**
  201. * Adds additional metadata to the query.
  202. *
  203. * Often, a query may need to provide additional contextual data to alter
  204. * hooks. Alter hooks may then use that information to decide if and how
  205. * to take action.
  206. *
  207. * @param $key
  208. * The unique identifier for this piece of metadata. Must be a string that
  209. * follows the same rules as any other PHP identifier.
  210. * @param $object
  211. * The additional data to add to the query. May be any valid PHP variable.
  212. *
  213. * @return QueryAlterableInterface
  214. * The called object.
  215. */
  216. public function addMetaData($key, $object);
  217. /**
  218. * Retrieves a given piece of metadata.
  219. *
  220. * @param $key
  221. * The unique identifier for the piece of metadata to retrieve.
  222. *
  223. * @return
  224. * The previously attached metadata object, or NULL if one doesn't exist.
  225. */
  226. public function getMetaData($key);
  227. }
  228. /**
  229. * Interface for a query that accepts placeholders.
  230. */
  231. interface QueryPlaceholderInterface {
  232. /**
  233. * Returns a unique identifier for this object.
  234. */
  235. public function uniqueIdentifier();
  236. /**
  237. * Returns the next placeholder ID for the query.
  238. *
  239. * @return
  240. * The next available placeholder ID as an integer.
  241. */
  242. public function nextPlaceholder();
  243. }
  244. /**
  245. * Base class for query builders.
  246. *
  247. * Note that query builders use PHP's magic __toString() method to compile the
  248. * query object into a prepared statement.
  249. */
  250. abstract class Query implements QueryPlaceholderInterface {
  251. /**
  252. * The connection object on which to run this query.
  253. *
  254. * @var DatabaseConnection
  255. */
  256. protected $connection;
  257. /**
  258. * The target of the connection object.
  259. *
  260. * @var string
  261. */
  262. protected $connectionTarget;
  263. /**
  264. * The key of the connection object.
  265. *
  266. * @var string
  267. */
  268. protected $connectionKey;
  269. /**
  270. * The query options to pass on to the connection object.
  271. *
  272. * @var array
  273. */
  274. protected $queryOptions;
  275. /**
  276. * A unique identifier for this query object.
  277. */
  278. protected $uniqueIdentifier;
  279. /**
  280. * The placeholder counter.
  281. */
  282. protected $nextPlaceholder = 0;
  283. /**
  284. * An array of comments that can be prepended to a query.
  285. *
  286. * @var array
  287. */
  288. protected $comments = array();
  289. /**
  290. * Constructs a Query object.
  291. *
  292. * @param DatabaseConnection $connection
  293. * Database connection object.
  294. * @param array $options
  295. * Array of query options.
  296. */
  297. public function __construct(DatabaseConnection $connection, $options) {
  298. $this->uniqueIdentifier = uniqid('', TRUE);
  299. $this->connection = $connection;
  300. $this->connectionKey = $this->connection->getKey();
  301. $this->connectionTarget = $this->connection->getTarget();
  302. $this->queryOptions = $options;
  303. }
  304. /**
  305. * Implements the magic __sleep function to disconnect from the database.
  306. */
  307. public function __sleep() {
  308. $keys = get_object_vars($this);
  309. unset($keys['connection']);
  310. return array_keys($keys);
  311. }
  312. /**
  313. * Implements the magic __wakeup function to reconnect to the database.
  314. */
  315. public function __wakeup() {
  316. $this->connection = Database::getConnection($this->connectionTarget, $this->connectionKey);
  317. }
  318. /**
  319. * Implements the magic __clone function.
  320. */
  321. public function __clone() {
  322. $this->uniqueIdentifier = uniqid('', TRUE);
  323. }
  324. /**
  325. * Runs the query against the database.
  326. */
  327. abstract protected function execute();
  328. /**
  329. * Implements PHP magic __toString method to convert the query to a string.
  330. *
  331. * The toString operation is how we compile a query object to a prepared
  332. * statement.
  333. *
  334. * @return
  335. * A prepared statement query string for this object.
  336. */
  337. abstract public function __toString();
  338. /**
  339. * Returns a unique identifier for this object.
  340. */
  341. public function uniqueIdentifier() {
  342. return $this->uniqueIdentifier;
  343. }
  344. /**
  345. * Gets the next placeholder value for this query object.
  346. *
  347. * @return int
  348. * Next placeholder value.
  349. */
  350. public function nextPlaceholder() {
  351. return $this->nextPlaceholder++;
  352. }
  353. /**
  354. * Adds a comment to the query.
  355. *
  356. * By adding a comment to a query, you can more easily find it in your
  357. * query log or the list of active queries on an SQL server. This allows
  358. * for easier debugging and allows you to more easily find where a query
  359. * with a performance problem is being generated.
  360. *
  361. * The comment string will be sanitized to remove * / and other characters
  362. * that may terminate the string early so as to avoid SQL injection attacks.
  363. *
  364. * @param $comment
  365. * The comment string to be inserted into the query.
  366. *
  367. * @return Query
  368. * The called object.
  369. */
  370. public function comment($comment) {
  371. $this->comments[] = $comment;
  372. return $this;
  373. }
  374. /**
  375. * Returns a reference to the comments array for the query.
  376. *
  377. * Because this method returns by reference, alter hooks may edit the comments
  378. * array directly to make their changes. If just adding comments, however, the
  379. * use of comment() is preferred.
  380. *
  381. * Note that this method must be called by reference as well:
  382. * @code
  383. * $comments =& $query->getComments();
  384. * @endcode
  385. *
  386. * @return
  387. * A reference to the comments array structure.
  388. */
  389. public function &getComments() {
  390. return $this->comments;
  391. }
  392. }
  393. /**
  394. * General class for an abstracted INSERT query.
  395. */
  396. class InsertQuery extends Query {
  397. /**
  398. * The table on which to insert.
  399. *
  400. * @var string
  401. */
  402. protected $table;
  403. /**
  404. * An array of fields on which to insert.
  405. *
  406. * @var array
  407. */
  408. protected $insertFields = array();
  409. /**
  410. * An array of fields that should be set to their database-defined defaults.
  411. *
  412. * @var array
  413. */
  414. protected $defaultFields = array();
  415. /**
  416. * A nested array of values to insert.
  417. *
  418. * $insertValues is an array of arrays. Each sub-array is either an
  419. * associative array whose keys are field names and whose values are field
  420. * values to insert, or a non-associative array of values in the same order
  421. * as $insertFields.
  422. *
  423. * Whether multiple insert sets will be run in a single query or multiple
  424. * queries is left to individual drivers to implement in whatever manner is
  425. * most appropriate. The order of values in each sub-array must match the
  426. * order of fields in $insertFields.
  427. *
  428. * @var array
  429. */
  430. protected $insertValues = array();
  431. /**
  432. * A SelectQuery object to fetch the rows that should be inserted.
  433. *
  434. * @var SelectQueryInterface
  435. */
  436. protected $fromQuery;
  437. /**
  438. * Constructs an InsertQuery object.
  439. *
  440. * @param DatabaseConnection $connection
  441. * A DatabaseConnection object.
  442. * @param string $table
  443. * Name of the table to associate with this query.
  444. * @param array $options
  445. * Array of database options.
  446. */
  447. public function __construct($connection, $table, array $options = array()) {
  448. if (!isset($options['return'])) {
  449. $options['return'] = Database::RETURN_INSERT_ID;
  450. }
  451. parent::__construct($connection, $options);
  452. $this->table = $table;
  453. }
  454. /**
  455. * Adds a set of field->value pairs to be inserted.
  456. *
  457. * This method may only be called once. Calling it a second time will be
  458. * ignored. To queue up multiple sets of values to be inserted at once,
  459. * use the values() method.
  460. *
  461. * @param $fields
  462. * An array of fields on which to insert. This array may be indexed or
  463. * associative. If indexed, the array is taken to be the list of fields.
  464. * If associative, the keys of the array are taken to be the fields and
  465. * the values are taken to be corresponding values to insert. If a
  466. * $values argument is provided, $fields must be indexed.
  467. * @param $values
  468. * An array of fields to insert into the database. The values must be
  469. * specified in the same order as the $fields array.
  470. *
  471. * @return InsertQuery
  472. * The called object.
  473. */
  474. public function fields(array $fields, array $values = array()) {
  475. if (empty($this->insertFields)) {
  476. if (empty($values)) {
  477. if (!is_numeric(key($fields))) {
  478. $values = array_values($fields);
  479. $fields = array_keys($fields);
  480. }
  481. }
  482. $this->insertFields = $fields;
  483. if (!empty($values)) {
  484. $this->insertValues[] = $values;
  485. }
  486. }
  487. return $this;
  488. }
  489. /**
  490. * Adds another set of values to the query to be inserted.
  491. *
  492. * If $values is a numeric-keyed array, it will be assumed to be in the same
  493. * order as the original fields() call. If it is associative, it may be
  494. * in any order as long as the keys of the array match the names of the
  495. * fields.
  496. *
  497. * @param $values
  498. * An array of values to add to the query.
  499. *
  500. * @return InsertQuery
  501. * The called object.
  502. */
  503. public function values(array $values) {
  504. if (is_numeric(key($values))) {
  505. $this->insertValues[] = $values;
  506. }
  507. else {
  508. // Reorder the submitted values to match the fields array.
  509. foreach ($this->insertFields as $key) {
  510. $insert_values[$key] = $values[$key];
  511. }
  512. // For consistency, the values array is always numerically indexed.
  513. $this->insertValues[] = array_values($insert_values);
  514. }
  515. return $this;
  516. }
  517. /**
  518. * Specifies fields for which the database defaults should be used.
  519. *
  520. * If you want to force a given field to use the database-defined default,
  521. * not NULL or undefined, use this method to instruct the database to use
  522. * default values explicitly. In most cases this will not be necessary
  523. * unless you are inserting a row that is all default values, as you cannot
  524. * specify no values in an INSERT query.
  525. *
  526. * Specifying a field both in fields() and in useDefaults() is an error
  527. * and will not execute.
  528. *
  529. * @param $fields
  530. * An array of values for which to use the default values
  531. * specified in the table definition.
  532. *
  533. * @return InsertQuery
  534. * The called object.
  535. */
  536. public function useDefaults(array $fields) {
  537. $this->defaultFields = $fields;
  538. return $this;
  539. }
  540. /**
  541. * Sets the fromQuery on this InsertQuery object.
  542. *
  543. * @param SelectQueryInterface $query
  544. * The query to fetch the rows that should be inserted.
  545. *
  546. * @return InsertQuery
  547. * The called object.
  548. */
  549. public function from(SelectQueryInterface $query) {
  550. $this->fromQuery = $query;
  551. return $this;
  552. }
  553. /**
  554. * Executes the insert query.
  555. *
  556. * @return
  557. * The last insert ID of the query, if one exists. If the query
  558. * was given multiple sets of values to insert, the return value is
  559. * undefined. If no fields are specified, this method will do nothing and
  560. * return NULL. That makes it safe to use in multi-insert loops.
  561. */
  562. public function execute() {
  563. // If validation fails, simply return NULL. Note that validation routines
  564. // in preExecute() may throw exceptions instead.
  565. if (!$this->preExecute()) {
  566. return NULL;
  567. }
  568. // If we're selecting from a SelectQuery, finish building the query and
  569. // pass it back, as any remaining options are irrelevant.
  570. if (!empty($this->fromQuery)) {
  571. $sql = (string) $this;
  572. // The SelectQuery may contain arguments, load and pass them through.
  573. return $this->connection->query($sql, $this->fromQuery->getArguments(), $this->queryOptions);
  574. }
  575. $last_insert_id = 0;
  576. // Each insert happens in its own query in the degenerate case. However,
  577. // we wrap it in a transaction so that it is atomic where possible. On many
  578. // databases, such as SQLite, this is also a notable performance boost.
  579. $transaction = $this->connection->startTransaction();
  580. try {
  581. $sql = (string) $this;
  582. foreach ($this->insertValues as $insert_values) {
  583. $last_insert_id = $this->connection->query($sql, $insert_values, $this->queryOptions);
  584. }
  585. }
  586. catch (Exception $e) {
  587. // One of the INSERTs failed, rollback the whole batch.
  588. $transaction->rollback();
  589. // Rethrow the exception for the calling code.
  590. throw $e;
  591. }
  592. // Re-initialize the values array so that we can re-use this query.
  593. $this->insertValues = array();
  594. // Transaction commits here where $transaction looses scope.
  595. return $last_insert_id;
  596. }
  597. /**
  598. * Implements PHP magic __toString method to convert the query to a string.
  599. *
  600. * @return string
  601. * The prepared statement.
  602. */
  603. public function __toString() {
  604. // Create a sanitized comment string to prepend to the query.
  605. $comments = $this->connection->makeComment($this->comments);
  606. // Default fields are always placed first for consistency.
  607. $insert_fields = array_merge($this->defaultFields, $this->insertFields);
  608. if (!empty($this->fromQuery)) {
  609. return $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') ' . $this->fromQuery;
  610. }
  611. // For simplicity, we will use the $placeholders array to inject
  612. // default keywords even though they are not, strictly speaking,
  613. // placeholders for prepared statements.
  614. $placeholders = array();
  615. $placeholders = array_pad($placeholders, count($this->defaultFields), 'default');
  616. $placeholders = array_pad($placeholders, count($this->insertFields), '?');
  617. return $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES (' . implode(', ', $placeholders) . ')';
  618. }
  619. /**
  620. * Preprocesses and validates the query.
  621. *
  622. * @return
  623. * TRUE if the validation was successful, FALSE if not.
  624. *
  625. * @throws FieldsOverlapException
  626. * @throws NoFieldsException
  627. */
  628. public function preExecute() {
  629. // Confirm that the user did not try to specify an identical
  630. // field and default field.
  631. if (array_intersect($this->insertFields, $this->defaultFields)) {
  632. throw new FieldsOverlapException('You may not specify the same field to have a value and a schema-default value.');
  633. }
  634. if (!empty($this->fromQuery)) {
  635. // We have to assume that the used aliases match the insert fields.
  636. // Regular fields are added to the query before expressions, maintain the
  637. // same order for the insert fields.
  638. // This behavior can be overridden by calling fields() manually as only the
  639. // first call to fields() does have an effect.
  640. $this->fields(array_merge(array_keys($this->fromQuery->getFields()), array_keys($this->fromQuery->getExpressions())));
  641. }
  642. // Don't execute query without fields.
  643. if (count($this->insertFields) + count($this->defaultFields) == 0) {
  644. throw new NoFieldsException('There are no fields available to insert with.');
  645. }
  646. // If no values have been added, silently ignore this query. This can happen
  647. // if values are added conditionally, so we don't want to throw an
  648. // exception.
  649. if (!isset($this->insertValues[0]) && count($this->insertFields) > 0 && empty($this->fromQuery)) {
  650. return FALSE;
  651. }
  652. return TRUE;
  653. }
  654. }
  655. /**
  656. * General class for an abstracted DELETE operation.
  657. */
  658. class DeleteQuery extends Query implements QueryConditionInterface {
  659. /**
  660. * The table from which to delete.
  661. *
  662. * @var string
  663. */
  664. protected $table;
  665. /**
  666. * The condition object for this query.
  667. *
  668. * Condition handling is handled via composition.
  669. *
  670. * @var DatabaseCondition
  671. */
  672. protected $condition;
  673. /**
  674. * Constructs a DeleteQuery object.
  675. *
  676. * @param DatabaseConnection $connection
  677. * A DatabaseConnection object.
  678. * @param string $table
  679. * Name of the table to associate with this query.
  680. * @param array $options
  681. * Array of database options.
  682. */
  683. public function __construct(DatabaseConnection $connection, $table, array $options = array()) {
  684. $options['return'] = Database::RETURN_AFFECTED;
  685. parent::__construct($connection, $options);
  686. $this->table = $table;
  687. $this->condition = new DatabaseCondition('AND');
  688. }
  689. /**
  690. * Implements QueryConditionInterface::condition().
  691. */
  692. public function condition($field, $value = NULL, $operator = NULL) {
  693. $this->condition->condition($field, $value, $operator);
  694. return $this;
  695. }
  696. /**
  697. * Implements QueryConditionInterface::isNull().
  698. */
  699. public function isNull($field) {
  700. $this->condition->isNull($field);
  701. return $this;
  702. }
  703. /**
  704. * Implements QueryConditionInterface::isNotNull().
  705. */
  706. public function isNotNull($field) {
  707. $this->condition->isNotNull($field);
  708. return $this;
  709. }
  710. /**
  711. * Implements QueryConditionInterface::exists().
  712. */
  713. public function exists(SelectQueryInterface $select) {
  714. $this->condition->exists($select);
  715. return $this;
  716. }
  717. /**
  718. * Implements QueryConditionInterface::notExists().
  719. */
  720. public function notExists(SelectQueryInterface $select) {
  721. $this->condition->notExists($select);
  722. return $this;
  723. }
  724. /**
  725. * Implements QueryConditionInterface::conditions().
  726. */
  727. public function &conditions() {
  728. return $this->condition->conditions();
  729. }
  730. /**
  731. * Implements QueryConditionInterface::arguments().
  732. */
  733. public function arguments() {
  734. return $this->condition->arguments();
  735. }
  736. /**
  737. * Implements QueryConditionInterface::where().
  738. */
  739. public function where($snippet, $args = array()) {
  740. $this->condition->where($snippet, $args);
  741. return $this;
  742. }
  743. /**
  744. * Implements QueryConditionInterface::compile().
  745. */
  746. public function compile(DatabaseConnection $connection, QueryPlaceholderInterface $queryPlaceholder) {
  747. return $this->condition->compile($connection, $queryPlaceholder);
  748. }
  749. /**
  750. * Implements QueryConditionInterface::compiled().
  751. */
  752. public function compiled() {
  753. return $this->condition->compiled();
  754. }
  755. /**
  756. * Executes the DELETE query.
  757. *
  758. * @return
  759. * The return value is dependent on the database connection.
  760. */
  761. public function execute() {
  762. $values = array();
  763. if (count($this->condition)) {
  764. $this->condition->compile($this->connection, $this);
  765. $values = $this->condition->arguments();
  766. }
  767. return $this->connection->query((string) $this, $values, $this->queryOptions);
  768. }
  769. /**
  770. * Implements PHP magic __toString method to convert the query to a string.
  771. *
  772. * @return string
  773. * The prepared statement.
  774. */
  775. public function __toString() {
  776. // Create a sanitized comment string to prepend to the query.
  777. $comments = $this->connection->makeComment($this->comments);
  778. $query = $comments . 'DELETE FROM {' . $this->connection->escapeTable($this->table) . '} ';
  779. if (count($this->condition)) {
  780. $this->condition->compile($this->connection, $this);
  781. $query .= "\nWHERE " . $this->condition;
  782. }
  783. return $query;
  784. }
  785. }
  786. /**
  787. * General class for an abstracted TRUNCATE operation.
  788. */
  789. class TruncateQuery extends Query {
  790. /**
  791. * The table to truncate.
  792. *
  793. * @var string
  794. */
  795. protected $table;
  796. /**
  797. * Constructs a TruncateQuery object.
  798. *
  799. * @param DatabaseConnection $connection
  800. * A DatabaseConnection object.
  801. * @param string $table
  802. * Name of the table to associate with this query.
  803. * @param array $options
  804. * Array of database options.
  805. */
  806. public function __construct(DatabaseConnection $connection, $table, array $options = array()) {
  807. $options['return'] = Database::RETURN_AFFECTED;
  808. parent::__construct($connection, $options);
  809. $this->table = $table;
  810. }
  811. /**
  812. * Implements QueryConditionInterface::compile().
  813. */
  814. public function compile(DatabaseConnection $connection, QueryPlaceholderInterface $queryPlaceholder) {
  815. return $this->condition->compile($connection, $queryPlaceholder);
  816. }
  817. /**
  818. * Implements QueryConditionInterface::compiled().
  819. */
  820. public function compiled() {
  821. return $this->condition->compiled();
  822. }
  823. /**
  824. * Executes the TRUNCATE query.
  825. *
  826. * @return
  827. * Return value is dependent on the database type.
  828. */
  829. public function execute() {
  830. return $this->connection->query((string) $this, array(), $this->queryOptions);
  831. }
  832. /**
  833. * Implements PHP magic __toString method to convert the query to a string.
  834. *
  835. * @return string
  836. * The prepared statement.
  837. */
  838. public function __toString() {
  839. // Create a sanitized comment string to prepend to the query.
  840. $comments = $this->connection->makeComment($this->comments);
  841. return $comments . 'TRUNCATE {' . $this->connection->escapeTable($this->table) . '} ';
  842. }
  843. }
  844. /**
  845. * General class for an abstracted UPDATE operation.
  846. */
  847. class UpdateQuery extends Query implements QueryConditionInterface {
  848. /**
  849. * The table to update.
  850. *
  851. * @var string
  852. */
  853. protected $table;
  854. /**
  855. * An array of fields that will be updated.
  856. *
  857. * @var array
  858. */
  859. protected $fields = array();
  860. /**
  861. * An array of values to update to.
  862. *
  863. * @var array
  864. */
  865. protected $arguments = array();
  866. /**
  867. * The condition object for this query.
  868. *
  869. * Condition handling is handled via composition.
  870. *
  871. * @var DatabaseCondition
  872. */
  873. protected $condition;
  874. /**
  875. * Array of fields to update to an expression in case of a duplicate record.
  876. *
  877. * This variable is a nested array in the following format:
  878. * @code
  879. * <some field> => array(
  880. * 'condition' => <condition to execute, as a string>,
  881. * 'arguments' => <array of arguments for condition, or NULL for none>,
  882. * );
  883. * @endcode
  884. *
  885. * @var array
  886. */
  887. protected $expressionFields = array();
  888. /**
  889. * Constructs an UpdateQuery object.
  890. *
  891. * @param DatabaseConnection $connection
  892. * A DatabaseConnection object.
  893. * @param string $table
  894. * Name of the table to associate with this query.
  895. * @param array $options
  896. * Array of database options.
  897. */
  898. public function __construct(DatabaseConnection $connection, $table, array $options = array()) {
  899. $options['return'] = Database::RETURN_AFFECTED;
  900. parent::__construct($connection, $options);
  901. $this->table = $table;
  902. $this->condition = new DatabaseCondition('AND');
  903. }
  904. /**
  905. * Implements QueryConditionInterface::condition().
  906. */
  907. public function condition($field, $value = NULL, $operator = NULL) {
  908. $this->condition->condition($field, $value, $operator);
  909. return $this;
  910. }
  911. /**
  912. * Implements QueryConditionInterface::isNull().
  913. */
  914. public function isNull($field) {
  915. $this->condition->isNull($field);
  916. return $this;
  917. }
  918. /**
  919. * Implements QueryConditionInterface::isNotNull().
  920. */
  921. public function isNotNull($field) {
  922. $this->condition->isNotNull($field);
  923. return $this;
  924. }
  925. /**
  926. * Implements QueryConditionInterface::exists().
  927. */
  928. public function exists(SelectQueryInterface $select) {
  929. $this->condition->exists($select);
  930. return $this;
  931. }
  932. /**
  933. * Implements QueryConditionInterface::notExists().
  934. */
  935. public function notExists(SelectQueryInterface $select) {
  936. $this->condition->notExists($select);
  937. return $this;
  938. }
  939. /**
  940. * Implements QueryConditionInterface::conditions().
  941. */
  942. public function &conditions() {
  943. return $this->condition->conditions();
  944. }
  945. /**
  946. * Implements QueryConditionInterface::arguments().
  947. */
  948. public function arguments() {
  949. return $this->condition->arguments();
  950. }
  951. /**
  952. * Implements QueryConditionInterface::where().
  953. */
  954. public function where($snippet, $args = array()) {
  955. $this->condition->where($snippet, $args);
  956. return $this;
  957. }
  958. /**
  959. * Implements QueryConditionInterface::compile().
  960. */
  961. public function compile(DatabaseConnection $connection, QueryPlaceholderInterface $queryPlaceholder) {
  962. return $this->condition->compile($connection, $queryPlaceholder);
  963. }
  964. /**
  965. * Implements QueryConditionInterface::compiled().
  966. */
  967. public function compiled() {
  968. return $this->condition->compiled();
  969. }
  970. /**
  971. * Adds a set of field->value pairs to be updated.
  972. *
  973. * @param $fields
  974. * An associative array of fields to write into the database. The array keys
  975. * are the field names and the values are the values to which to set them.
  976. *
  977. * @return UpdateQuery
  978. * The called object.
  979. */
  980. public function fields(array $fields) {
  981. $this->fields = $fields;
  982. return $this;
  983. }
  984. /**
  985. * Specifies fields to be updated as an expression.
  986. *
  987. * Expression fields are cases such as counter=counter+1. This method takes
  988. * precedence over fields().
  989. *
  990. * @param $field
  991. * The field to set.
  992. * @param $expression
  993. * The field will be set to the value of this expression. This parameter
  994. * may include named placeholders.
  995. * @param $arguments
  996. * If specified, this is an array of key/value pairs for named placeholders
  997. * corresponding to the expression.
  998. *
  999. * @return UpdateQuery
  1000. * The called object.
  1001. */
  1002. public function expression($field, $expression, array $arguments = NULL) {
  1003. $this->expressionFields[$field] = array(
  1004. 'expression' => $expression,
  1005. 'arguments' => $arguments,
  1006. );
  1007. return $this;
  1008. }
  1009. /**
  1010. * Executes the UPDATE query.
  1011. *
  1012. * @return
  1013. * The number of rows affected by the update.
  1014. */
  1015. public function execute() {
  1016. // Expressions take priority over literal fields, so we process those first
  1017. // and remove any literal fields that conflict.
  1018. $fields = $this->fields;
  1019. $update_values = array();
  1020. foreach ($this->expressionFields as $field => $data) {
  1021. if (!empty($data['arguments'])) {
  1022. $update_values += $data['arguments'];
  1023. }
  1024. unset($fields[$field]);
  1025. }
  1026. // Because we filter $fields the same way here and in __toString(), the
  1027. // placeholders will all match up properly.
  1028. $max_placeholder = 0;
  1029. foreach ($fields as $field => $value) {
  1030. $update_values[':db_update_placeholder_' . ($max_placeholder++)] = $value;
  1031. }
  1032. if (count($this->condition)) {
  1033. $this->condition->compile($this->connection, $this);
  1034. $update_values = array_merge($update_values, $this->condition->arguments());
  1035. }
  1036. return $this->connection->query((string) $this, $update_values, $this->queryOptions);
  1037. }
  1038. /**
  1039. * Implements PHP magic __toString method to convert the query to a string.
  1040. *
  1041. * @return string
  1042. * The prepared statement.
  1043. */
  1044. public function __toString() {
  1045. // Create a sanitized comment string to prepend to the query.
  1046. $comments = $this->connection->makeComment($this->comments);
  1047. // Expressions take priority over literal fields, so we process those first
  1048. // and remove any literal fields that conflict.
  1049. $fields = $this->fields;
  1050. $update_fields = array();
  1051. foreach ($this->expressionFields as $field => $data) {
  1052. $update_fields[] = $field . '=' . $data['expression'];
  1053. unset($fields[$field]);
  1054. }
  1055. $max_placeholder = 0;
  1056. foreach ($fields as $field => $value) {
  1057. $update_fields[] = $field . '=:db_update_placeholder_' . ($max_placeholder++);
  1058. }
  1059. $query = $comments . 'UPDATE {' . $this->connection->escapeTable($this->table) . '} SET ' . implode(', ', $update_fields);
  1060. if (count($this->condition)) {
  1061. $this->condition->compile($this->connection, $this);
  1062. // There is an implicit string cast on $this->condition.
  1063. $query .= "\nWHERE " . $this->condition;
  1064. }
  1065. return $query;
  1066. }
  1067. }
  1068. /**
  1069. * General class for an abstracted MERGE query operation.
  1070. *
  1071. * An ANSI SQL:2003 compatible database would run the following query:
  1072. *
  1073. * @code
  1074. * MERGE INTO table_name_1 USING table_name_2 ON (condition)
  1075. * WHEN MATCHED THEN
  1076. * UPDATE SET column1 = value1 [, column2 = value2 ...]
  1077. * WHEN NOT MATCHED THEN
  1078. * INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...
  1079. * @endcode
  1080. *
  1081. * Other databases (most notably MySQL, PostgreSQL and SQLite) will emulate
  1082. * this statement by running a SELECT and then INSERT or UPDATE.
  1083. *
  1084. * By default, the two table names are identical and they are passed into the
  1085. * the constructor. table_name_2 can be specified by the
  1086. * MergeQuery::conditionTable() method. It can be either a string or a
  1087. * subquery.
  1088. *
  1089. * The condition is built exactly like SelectQuery or UpdateQuery conditions,
  1090. * the UPDATE query part is built similarly like an UpdateQuery and finally the
  1091. * INSERT query part is built similarly like an InsertQuery. However, both
  1092. * UpdateQuery and InsertQuery has a fields method so
  1093. * MergeQuery::updateFields() and MergeQuery::insertFields() needs to be called
  1094. * instead. MergeQuery::fields() can also be called which calls both of these
  1095. * methods as the common case is to use the same column-value pairs for both
  1096. * INSERT and UPDATE. However, this is not mandatory. Another convinient
  1097. * wrapper is MergeQuery::key() which adds the same column-value pairs to the
  1098. * condition and the INSERT query part.
  1099. *
  1100. * Several methods (key(), fields(), insertFields()) can be called to set a
  1101. * key-value pair for the INSERT query part. Subsequent calls for the same
  1102. * fields override the earlier ones. The same is true for UPDATE and key(),
  1103. * fields() and updateFields().
  1104. */
  1105. class MergeQuery extends Query implements QueryConditionInterface {
  1106. /**
  1107. * Returned by execute() if an INSERT query has been executed.
  1108. */
  1109. const STATUS_INSERT = 1;
  1110. /**
  1111. * Returned by execute() if an UPDATE query has been executed.
  1112. */
  1113. const STATUS_UPDATE = 2;
  1114. /**
  1115. * The table to be used for INSERT and UPDATE.
  1116. *
  1117. * @var string
  1118. */
  1119. protected $table;
  1120. /**
  1121. * The table or subquery to be used for the condition.
  1122. */
  1123. protected $conditionTable;
  1124. /**
  1125. * An array of fields on which to insert.
  1126. *
  1127. * @var array
  1128. */
  1129. protected $insertFields = array();
  1130. /**
  1131. * An array of fields which should be set to their database-defined defaults.
  1132. *
  1133. * Used on INSERT.
  1134. *
  1135. * @var array
  1136. */
  1137. protected $defaultFields = array();
  1138. /**
  1139. * An array of values to be inserted.
  1140. *
  1141. * @var string
  1142. */
  1143. protected $insertValues = array();
  1144. /**
  1145. * An array of fields that will be updated.
  1146. *
  1147. * @var array
  1148. */
  1149. protected $updateFields = array();
  1150. /**
  1151. * Array of fields to update to an expression in case of a duplicate record.
  1152. *
  1153. * This variable is a nested array in the following format:
  1154. * @code
  1155. * <some field> => array(
  1156. * 'condition' => <condition to execute, as a string>,
  1157. * 'arguments' => <array of arguments for condition, or NULL for none>,
  1158. * );
  1159. * @endcode
  1160. *
  1161. * @var array
  1162. */
  1163. protected $expressionFields = array();
  1164. /**
  1165. * Flag indicating whether an UPDATE is necessary.
  1166. *
  1167. * @var boolean
  1168. */
  1169. protected $needsUpdate = FALSE;
  1170. /**
  1171. * Constructs a MergeQuery object.
  1172. *
  1173. * @param DatabaseConnection $connection
  1174. * A DatabaseConnection object.
  1175. * @param string $table
  1176. * Name of the table to associate with this query.
  1177. * @param array $options
  1178. * Array of database options.
  1179. */
  1180. public function __construct(DatabaseConnection $connection, $table, array $options = array()) {
  1181. $options['return'] = Database::RETURN_AFFECTED;
  1182. parent::__construct($connection, $options);
  1183. $this->table = $table;
  1184. $this->conditionTable = $table;
  1185. $this->condition = new DatabaseCondition('AND');
  1186. }
  1187. /**
  1188. * Sets the table or subquery to be used for the condition.
  1189. *
  1190. * @param $table
  1191. * The table name or the subquery to be used. Use a SelectQuery object to
  1192. * pass in a subquery.
  1193. *
  1194. * @return MergeQuery
  1195. * The called object.
  1196. */
  1197. protected function conditionTable($table) {
  1198. $this->conditionTable = $table;
  1199. return $this;
  1200. }
  1201. /**
  1202. * Adds a set of field->value pairs to be updated.
  1203. *
  1204. * @param $fields
  1205. * An associative array of fields to write into the database. The array keys
  1206. * are the field names and the values are the values to which to set them.
  1207. *
  1208. * @return MergeQuery
  1209. * The called object.
  1210. */
  1211. public function updateFields(array $fields) {
  1212. $this->updateFields = $fields;
  1213. $this->needsUpdate = TRUE;
  1214. return $this;
  1215. }
  1216. /**
  1217. * Specifies fields to be updated as an expression.
  1218. *
  1219. * Expression fields are cases such as counter = counter + 1. This method
  1220. * takes precedence over MergeQuery::updateFields() and it's wrappers,
  1221. * MergeQuery::key() and MergeQuery::fields().
  1222. *
  1223. * @param $field
  1224. * The field to set.
  1225. * @param $expression
  1226. * The field will be set to the value of this expression. This parameter
  1227. * may include named placeholders.
  1228. * @param $arguments
  1229. * If specified, this is an array of key/value pairs for named placeholders
  1230. * corresponding to the expression.
  1231. *
  1232. * @return MergeQuery
  1233. * The called object.
  1234. */
  1235. public function expression($field, $expression, array $arguments = NULL) {
  1236. $this->expressionFields[$field] = array(
  1237. 'expression' => $expression,
  1238. 'arguments' => $arguments,
  1239. );
  1240. $this->needsUpdate = TRUE;
  1241. return $this;
  1242. }
  1243. /**
  1244. * Adds a set of field->value pairs to be inserted.
  1245. *
  1246. * @param $fields
  1247. * An array of fields on which to insert. This array may be indexed or
  1248. * associative. If indexed, the array is taken to be the list of fields.
  1249. * If associative, the keys of the array are taken to be the fields and
  1250. * the values are taken to be corresponding values to insert. If a
  1251. * $values argument is provided, $fields must be indexed.
  1252. * @param $values
  1253. * An array of fields to insert into the database. The values must be
  1254. * specified in the same order as the $fields array.
  1255. *
  1256. * @return MergeQuery
  1257. * The called object.
  1258. */
  1259. public function insertFields(array $fields, array $values = array()) {
  1260. if ($values) {
  1261. $fields = array_combine($fields, $values);
  1262. }
  1263. $this->insertFields = $fields;
  1264. return $this;
  1265. }
  1266. /**
  1267. * Specifies fields for which the database-defaults should be used.
  1268. *
  1269. * If you want to force a given field to use the database-defined default,
  1270. * not NULL or undefined, use this method to instruct the database to use
  1271. * default values explicitly. In most cases this will not be necessary
  1272. * unless you are inserting a row that is all default values, as you cannot
  1273. * specify no values in an INSERT query.
  1274. *
  1275. * Specifying a field both in fields() and in useDefaults() is an error
  1276. * and will not execute.
  1277. *
  1278. * @param $fields
  1279. * An array of values for which to use the default values
  1280. * specified in the table definition.
  1281. *
  1282. * @return MergeQuery
  1283. * The called object.
  1284. */
  1285. public function useDefaults(array $fields) {
  1286. $this->defaultFields = $fields;
  1287. return $this;
  1288. }
  1289. /**
  1290. * Sets common field-value pairs in the INSERT and UPDATE query parts.
  1291. *
  1292. * This method should only be called once. It may be called either
  1293. * with a single associative array or two indexed arrays. If called
  1294. * with an associative array, the keys are taken to be the fields
  1295. * and the values are taken to be the corresponding values to set.
  1296. * If called with two arrays, the first array is taken as the fields
  1297. * and the second array is taken as the corresponding values.
  1298. *
  1299. * @param $fields
  1300. * An array of fields to insert, or an associative array of fields and
  1301. * values. The keys of the array are taken to be the fields and the values
  1302. * are taken to be corresponding values to insert.
  1303. * @param $values
  1304. * An array of values to set into the database. The values must be
  1305. * specified in the same order as the $fields array.
  1306. *
  1307. * @return MergeQuery
  1308. * The called object.
  1309. */
  1310. public function fields(array $fields, array $values = array()) {
  1311. if ($values) {
  1312. $fields = array_combine($fields, $values);
  1313. }
  1314. foreach ($fields as $key => $value) {
  1315. $this->insertFields[$key] = $value;
  1316. $this->updateFields[$key] = $value;
  1317. }
  1318. $this->needsUpdate = TRUE;
  1319. return $this;
  1320. }
  1321. /**
  1322. * Sets the key field(s) to be used as conditions for this query.
  1323. *
  1324. * This method should only be called once. It may be called either
  1325. * with a single associative array or two indexed arrays. If called
  1326. * with an associative array, the keys are taken to be the fields
  1327. * and the values are taken to be the corresponding values to set.
  1328. * If called with two arrays, the first array is taken as the fields
  1329. * and the second array is taken as the corresponding values.
  1330. *
  1331. * The fields are copied to the condition of the query and the INSERT part.
  1332. * If no other method is called, the UPDATE will become a no-op.
  1333. *
  1334. * @param $fields
  1335. * An array of fields to set, or an associative array of fields and values.
  1336. * @param $values
  1337. * An array of values to set into the database. The values must be
  1338. * specified in the same order as the $fields array.
  1339. *
  1340. * @return MergeQuery
  1341. * The called object.
  1342. */
  1343. public function key(array $fields, array $values = array()) {
  1344. if ($values) {
  1345. $fields = array_combine($fields, $values);
  1346. }
  1347. foreach ($fields as $key => $value) {
  1348. $this->insertFields[$key] = $value;
  1349. $this->condition($key, $value);
  1350. }
  1351. return $this;
  1352. }
  1353. /**
  1354. * Implements QueryConditionInterface::condition().
  1355. */
  1356. public function condition($field, $value = NULL, $operator = NULL) {
  1357. $this->condition->condition($field, $value, $operator);
  1358. return $this;
  1359. }
  1360. /**
  1361. * Implements QueryConditionInterface::isNull().
  1362. */
  1363. public function isNull($field) {
  1364. $this->condition->isNull($field);
  1365. return $this;
  1366. }
  1367. /**
  1368. * Implements QueryConditionInterface::isNotNull().
  1369. */
  1370. public function isNotNull($field) {
  1371. $this->condition->isNotNull($field);
  1372. return $this;
  1373. }
  1374. /**
  1375. * Implements QueryConditionInterface::exists().
  1376. */
  1377. public function exists(SelectQueryInterface $select) {
  1378. $this->condition->exists($select);
  1379. return $this;
  1380. }
  1381. /**
  1382. * Implements QueryConditionInterface::notExists().
  1383. */
  1384. public function notExists(SelectQueryInterface $select) {
  1385. $this->condition->notExists($select);
  1386. return $this;
  1387. }
  1388. /**
  1389. * Implements QueryConditionInterface::conditions().
  1390. */
  1391. public function &conditions() {
  1392. return $this->condition->conditions();
  1393. }
  1394. /**
  1395. * Implements QueryConditionInterface::arguments().
  1396. */
  1397. public function arguments() {
  1398. return $this->condition->arguments();
  1399. }
  1400. /**
  1401. * Implements QueryConditionInterface::where().
  1402. */
  1403. public function where($snippet, $args = array()) {
  1404. $this->condition->where($snippet, $args);
  1405. return $this;
  1406. }
  1407. /**
  1408. * Implements QueryConditionInterface::compile().
  1409. */
  1410. public function compile(DatabaseConnection $connection, QueryPlaceholderInterface $queryPlaceholder) {
  1411. return $this->condition->compile($connection, $queryPlaceholder);
  1412. }
  1413. /**
  1414. * Implements QueryConditionInterface::compiled().
  1415. */
  1416. public function compiled() {
  1417. return $this->condition->compiled();
  1418. }
  1419. /**
  1420. * Implements PHP magic __toString method to convert the query to a string.
  1421. *
  1422. * In the degenerate case, there is no string-able query as this operation
  1423. * is potentially two queries.
  1424. *
  1425. * @return string
  1426. * The prepared query statement.
  1427. */
  1428. public function __toString() {
  1429. }
  1430. public function execute() {
  1431. // Wrap multiple queries in a transaction, if the database supports it.
  1432. $transaction = $this->connection->startTransaction();
  1433. try {
  1434. if (!count($this->condition)) {
  1435. throw new InvalidMergeQueryException(t('Invalid merge query: no conditions'));
  1436. }
  1437. $select = $this->connection->select($this->conditionTable)
  1438. ->condition($this->condition)
  1439. ->forUpdate();
  1440. $select->addExpression('1');
  1441. if (!$select->execute()->fetchField()) {
  1442. try {
  1443. $insert = $this->connection->insert($this->table)->fields($this->insertFields);
  1444. if ($this->defaultFields) {
  1445. $insert->useDefaults($this->defaultFields);
  1446. }
  1447. $insert->execute();
  1448. return MergeQuery::STATUS_INSERT;
  1449. }
  1450. catch (Exception $e) {
  1451. // The insert query failed, maybe it's because a racing insert query
  1452. // beat us in inserting the same row. Retry the select query, if it
  1453. // returns a row, ignore the error and continue with the update
  1454. // query below.
  1455. if (!$select->execute()->fetchField()) {
  1456. throw $e;
  1457. }
  1458. }
  1459. }
  1460. if ($this->needsUpdate) {
  1461. $update = $this->connection->update($this->table)
  1462. ->fields($this->updateFields)
  1463. ->condition($this->condition);
  1464. if ($this->expressionFields) {
  1465. foreach ($this->expressionFields as $field => $data) {
  1466. $update->expression($field, $data['expression'], $data['arguments']);
  1467. }
  1468. }
  1469. $update->execute();
  1470. return MergeQuery::STATUS_UPDATE;
  1471. }
  1472. }
  1473. catch (Exception $e) {
  1474. // Something really wrong happened here, bubble up the exception to the
  1475. // caller.
  1476. $transaction->rollback();
  1477. throw $e;
  1478. }
  1479. // Transaction commits here where $transaction looses scope.
  1480. }
  1481. }
  1482. /**
  1483. * Generic class for a series of conditions in a query.
  1484. */
  1485. class DatabaseCondition implements QueryConditionInterface, Countable {
  1486. /**
  1487. * Array of conditions.
  1488. *
  1489. * @var array
  1490. */
  1491. protected $conditions = array();
  1492. /**
  1493. * Array of arguments.
  1494. *
  1495. * @var array
  1496. */
  1497. protected $arguments = array();
  1498. /**
  1499. * Whether the conditions have been changed.
  1500. *
  1501. * TRUE if the condition has been changed since the last compile.
  1502. * FALSE if the condition has been compiled and not changed.
  1503. *
  1504. * @var bool
  1505. */
  1506. protected $changed = TRUE;
  1507. /**
  1508. * The identifier of the query placeholder this condition has been compiled against.
  1509. */
  1510. protected $queryPlaceholderIdentifier;
  1511. /**
  1512. * Constructs a DataBaseCondition object.
  1513. *
  1514. * @param string $conjunction
  1515. * The operator to use to combine conditions: 'AND' or 'OR'.
  1516. */
  1517. public function __construct($conjunction) {
  1518. $this->conditions['#conjunction'] = $conjunction;
  1519. }
  1520. /**
  1521. * Implements Countable::count().
  1522. *
  1523. * Returns the size of this conditional. The size of the conditional is the
  1524. * size of its conditional array minus one, because one element is the the
  1525. * conjunction.
  1526. */
  1527. public function count() {
  1528. return count($this->conditions) - 1;
  1529. }
  1530. /**
  1531. * Implements QueryConditionInterface::condition().
  1532. */
  1533. public function condition($field, $value = NULL, $operator = NULL) {
  1534. if (!isset($operator)) {
  1535. if (is_array($value)) {
  1536. $operator = 'IN';
  1537. }
  1538. elseif (!isset($value)) {
  1539. $operator = 'IS NULL';
  1540. }
  1541. else {
  1542. $operator = '=';
  1543. }
  1544. }
  1545. $this->conditions[] = array(
  1546. 'field' => $field,
  1547. 'value' => $value,
  1548. 'operator' => $operator,
  1549. );
  1550. $this->changed = TRUE;
  1551. return $this;
  1552. }
  1553. /**
  1554. * Implements QueryConditionInterface::where().
  1555. */
  1556. public function where($snippet, $args = array()) {
  1557. $this->conditions[] = array(
  1558. 'field' => $snippet,
  1559. 'value' => $args,
  1560. 'operator' => NULL,
  1561. );
  1562. $this->changed = TRUE;
  1563. return $this;
  1564. }
  1565. /**
  1566. * Implements QueryConditionInterface::isNull().
  1567. */
  1568. public function isNull($field) {
  1569. return $this->condition($field);
  1570. }
  1571. /**
  1572. * Implements QueryConditionInterface::isNotNull().
  1573. */
  1574. public function isNotNull($field) {
  1575. return $this->condition($field, NULL, 'IS NOT NULL');
  1576. }
  1577. /**
  1578. * Implements QueryConditionInterface::exists().
  1579. */
  1580. public function exists(SelectQueryInterface $select) {
  1581. return $this->condition('', $select, 'EXISTS');
  1582. }
  1583. /**
  1584. * Implements QueryConditionInterface::notExists().
  1585. */
  1586. public function notExists(SelectQueryInterface $select) {
  1587. return $this->condition('', $select, 'NOT EXISTS');
  1588. }
  1589. /**
  1590. * Implements QueryConditionInterface::conditions().
  1591. */
  1592. public function &conditions() {
  1593. return $this->conditions;
  1594. }
  1595. /**
  1596. * Implements QueryConditionInterface::arguments().
  1597. */
  1598. public function arguments() {
  1599. // If the caller forgot to call compile() first, refuse to run.
  1600. if ($this->changed) {
  1601. return NULL;
  1602. }
  1603. return $this->arguments;
  1604. }
  1605. /**
  1606. * Implements QueryConditionInterface::compile().
  1607. */
  1608. public function compile(DatabaseConnection $connection, QueryPlaceholderInterface $queryPlaceholder) {
  1609. // Re-compile if this condition changed or if we are compiled against a
  1610. // different query placeholder object.
  1611. if ($this->changed || isset($this->queryPlaceholderIdentifier) && ($this->queryPlaceholderIdentifier != $queryPlaceholder->uniqueIdentifier())) {
  1612. $this->queryPlaceholderIdentifier = $queryPlaceholder->uniqueIdentifier();
  1613. $condition_fragments = array();
  1614. $arguments = array();
  1615. $conditions = $this->conditions;
  1616. $conjunction = $conditions['#conjunction'];
  1617. unset($conditions['#conjunction']);
  1618. foreach ($conditions as $condition) {
  1619. if (empty($condition['operator'])) {
  1620. // This condition is a literal string, so let it through as is.
  1621. $condition_fragments[] = ' (' . $condition['field'] . ') ';
  1622. $arguments += $condition['value'];
  1623. }
  1624. else {
  1625. // It's a structured condition, so parse it out accordingly.
  1626. // Note that $condition['field'] will only be an object for a dependent
  1627. // DatabaseCondition object, not for a dependent subquery.
  1628. if ($condition['field'] instanceof QueryConditionInterface) {
  1629. // Compile the sub-condition recursively and add it to the list.
  1630. $condition['field']->compile($connection, $queryPlaceholder);
  1631. $condition_fragments[] = '(' . (string) $condition['field'] . ')';
  1632. $arguments += $condition['field']->arguments();
  1633. }
  1634. else {
  1635. // For simplicity, we treat all operators as the same data structure.
  1636. // In the typical degenerate case, this won't get changed.
  1637. $operator_defaults = array(
  1638. 'prefix' => '',
  1639. 'postfix' => '',
  1640. 'delimiter' => '',
  1641. 'operator' => $condition['operator'],
  1642. 'use_value' => TRUE,
  1643. );
  1644. $operator = $connection->mapConditionOperator($condition['operator']);
  1645. if (!isset($operator)) {
  1646. $operator = $this->mapConditionOperator($condition['operator']);
  1647. }
  1648. $operator += $operator_defaults;
  1649. $placeholders = array();
  1650. if ($condition['value'] instanceof SelectQueryInterface) {
  1651. $condition['value']->compile($connection, $queryPlaceholder);
  1652. $placeholders[] = (string) $condition['value'];
  1653. $arguments += $condition['value']->arguments();
  1654. // Subqueries are the actual value of the operator, we don't
  1655. // need to add another below.
  1656. $operator['use_value'] = FALSE;
  1657. }
  1658. // We assume that if there is a delimiter, then the value is an
  1659. // array. If not, it is a scalar. For simplicity, we first convert
  1660. // up to an array so that we can build the placeholders in the same way.
  1661. elseif (!$operator['delimiter']) {
  1662. $condition['value'] = array($condition['value']);
  1663. }
  1664. if ($operator['use_value']) {
  1665. foreach ($condition['value'] as $value) {
  1666. $placeholder = ':db_condition_placeholder_' . $queryPlaceholder->nextPlaceholder();
  1667. $arguments[$placeholder] = $value;
  1668. $placeholders[] = $placeholder;
  1669. }
  1670. }
  1671. $condition_fragments[] = ' (' . $connection->escapeField($condition['field']) . ' ' . $operator['operator'] . ' ' . $operator['prefix'] . implode($operator['delimiter'], $placeholders) . $operator['postfix'] . ') ';
  1672. }
  1673. }
  1674. }
  1675. $this->changed = FALSE;
  1676. $this->stringVersion = implode($conjunction, $condition_fragments);
  1677. $this->arguments = $arguments;
  1678. }
  1679. }
  1680. /**
  1681. * Implements QueryConditionInterface::compiled().
  1682. */
  1683. public function compiled() {
  1684. return !$this->changed;
  1685. }
  1686. /**
  1687. * Implements PHP magic __toString method to convert the conditions to string.
  1688. *
  1689. * @return string
  1690. * A string version of the conditions.
  1691. */
  1692. public function __toString() {
  1693. // If the caller forgot to call compile() first, refuse to run.
  1694. if ($this->changed) {
  1695. return NULL;
  1696. }
  1697. return $this->stringVersion;
  1698. }
  1699. /**
  1700. * PHP magic __clone() method.
  1701. *
  1702. * Only copies fields that implement QueryConditionInterface. Also sets
  1703. * $this->changed to TRUE.
  1704. */
  1705. function __clone() {
  1706. $this->changed = TRUE;
  1707. foreach ($this->conditions as $key => $condition) {
  1708. if ($key !== '#conjunction') {
  1709. if ($condition['field'] instanceOf QueryConditionInterface) {
  1710. $this->conditions[$key]['field'] = clone($condition['field']);
  1711. }
  1712. if ($condition['value'] instanceOf SelectQueryInterface) {
  1713. $this->conditions[$key]['value'] = clone($condition['value']);
  1714. }
  1715. }
  1716. }
  1717. }
  1718. /**
  1719. * Gets any special processing requirements for the condition operator.
  1720. *
  1721. * Some condition types require special processing, such as IN, because
  1722. * the value data they pass in is not a simple value. This is a simple
  1723. * overridable lookup function.
  1724. *
  1725. * @param $operator
  1726. * The condition operator, such as "IN", "BETWEEN", etc. Case-sensitive.
  1727. *
  1728. * @return
  1729. * The extra handling directives for the specified operator, or NULL.
  1730. */
  1731. protected function mapConditionOperator($operator) {
  1732. // $specials does not use drupal_static as its value never changes.
  1733. static $specials = array(
  1734. 'BETWEEN' => array('delimiter' => ' AND '),
  1735. 'IN' => array('delimiter' => ', ', 'prefix' => ' (', 'postfix' => ')'),
  1736. 'NOT IN' => array('delimiter' => ', ', 'prefix' => ' (', 'postfix' => ')'),
  1737. 'EXISTS' => array('prefix' => ' (', 'postfix' => ')'),
  1738. 'NOT EXISTS' => array('prefix' => ' (', 'postfix' => ')'),
  1739. 'IS NULL' => array('use_value' => FALSE),
  1740. 'IS NOT NULL' => array('use_value' => FALSE),
  1741. // Use backslash for escaping wildcard characters.
  1742. 'LIKE' => array('postfix' => " ESCAPE '\\\\'"),
  1743. 'NOT LIKE' => array('postfix' => " ESCAPE '\\\\'"),
  1744. // These ones are here for performance reasons.
  1745. '=' => array(),
  1746. '<' => array(),
  1747. '>' => array(),
  1748. '>=' => array(),
  1749. '<=' => array(),
  1750. );
  1751. if (isset($specials[$operator])) {
  1752. $return = $specials[$operator];
  1753. }
  1754. else {
  1755. // We need to upper case because PHP index matches are case sensitive but
  1756. // do not need the more expensive drupal_strtoupper because SQL statements are ASCII.
  1757. $operator = strtoupper($operator);
  1758. $return = isset($specials[$operator]) ? $specials[$operator] : array();
  1759. }
  1760. $return += array('operator' => $operator);
  1761. return $return;
  1762. }
  1763. }
  1764. /**
  1765. * @} End of "addtogroup database".
  1766. */