query.inc 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959
  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' && $condition['field'] instanceOf QueryConditionInterface) {
  1709. $this->conditions[$key]['field'] = clone($condition['field']);
  1710. }
  1711. }
  1712. }
  1713. /**
  1714. * Gets any special processing requirements for the condition operator.
  1715. *
  1716. * Some condition types require special processing, such as IN, because
  1717. * the value data they pass in is not a simple value. This is a simple
  1718. * overridable lookup function.
  1719. *
  1720. * @param $operator
  1721. * The condition operator, such as "IN", "BETWEEN", etc. Case-sensitive.
  1722. *
  1723. * @return
  1724. * The extra handling directives for the specified operator, or NULL.
  1725. */
  1726. protected function mapConditionOperator($operator) {
  1727. // $specials does not use drupal_static as its value never changes.
  1728. static $specials = array(
  1729. 'BETWEEN' => array('delimiter' => ' AND '),
  1730. 'IN' => array('delimiter' => ', ', 'prefix' => ' (', 'postfix' => ')'),
  1731. 'NOT IN' => array('delimiter' => ', ', 'prefix' => ' (', 'postfix' => ')'),
  1732. 'EXISTS' => array('prefix' => ' (', 'postfix' => ')'),
  1733. 'NOT EXISTS' => array('prefix' => ' (', 'postfix' => ')'),
  1734. 'IS NULL' => array('use_value' => FALSE),
  1735. 'IS NOT NULL' => array('use_value' => FALSE),
  1736. // Use backslash for escaping wildcard characters.
  1737. 'LIKE' => array('postfix' => " ESCAPE '\\\\'"),
  1738. 'NOT LIKE' => array('postfix' => " ESCAPE '\\\\'"),
  1739. // These ones are here for performance reasons.
  1740. '=' => array(),
  1741. '<' => array(),
  1742. '>' => array(),
  1743. '>=' => array(),
  1744. '<=' => array(),
  1745. );
  1746. if (isset($specials[$operator])) {
  1747. $return = $specials[$operator];
  1748. }
  1749. else {
  1750. // We need to upper case because PHP index matches are case sensitive but
  1751. // do not need the more expensive drupal_strtoupper because SQL statements are ASCII.
  1752. $operator = strtoupper($operator);
  1753. $return = isset($specials[$operator]) ? $specials[$operator] : array();
  1754. }
  1755. $return += array('operator' => $operator);
  1756. return $return;
  1757. }
  1758. }
  1759. /**
  1760. * @} End of "addtogroup database".
  1761. */