query.inc 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974
  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. // In most cases, TRUNCATE is not a transaction safe statement as it is a
  842. // DDL statement which results in an implicit COMMIT. When we are in a
  843. // transaction, fallback to the slower, but transactional, DELETE.
  844. // PostgreSQL also locks the entire table for a TRUNCATE strongly reducing
  845. // the concurrency with other transactions.
  846. if ($this->connection->inTransaction()) {
  847. return $comments . 'DELETE FROM {' . $this->connection->escapeTable($this->table) . '}';
  848. }
  849. else {
  850. return $comments . 'TRUNCATE {' . $this->connection->escapeTable($this->table) . '} ';
  851. }
  852. }
  853. }
  854. /**
  855. * General class for an abstracted UPDATE operation.
  856. */
  857. class UpdateQuery extends Query implements QueryConditionInterface {
  858. /**
  859. * The table to update.
  860. *
  861. * @var string
  862. */
  863. protected $table;
  864. /**
  865. * An array of fields that will be updated.
  866. *
  867. * @var array
  868. */
  869. protected $fields = array();
  870. /**
  871. * An array of values to update to.
  872. *
  873. * @var array
  874. */
  875. protected $arguments = array();
  876. /**
  877. * The condition object for this query.
  878. *
  879. * Condition handling is handled via composition.
  880. *
  881. * @var DatabaseCondition
  882. */
  883. protected $condition;
  884. /**
  885. * Array of fields to update to an expression in case of a duplicate record.
  886. *
  887. * This variable is a nested array in the following format:
  888. * @code
  889. * <some field> => array(
  890. * 'condition' => <condition to execute, as a string>,
  891. * 'arguments' => <array of arguments for condition, or NULL for none>,
  892. * );
  893. * @endcode
  894. *
  895. * @var array
  896. */
  897. protected $expressionFields = array();
  898. /**
  899. * Constructs an UpdateQuery object.
  900. *
  901. * @param DatabaseConnection $connection
  902. * A DatabaseConnection object.
  903. * @param string $table
  904. * Name of the table to associate with this query.
  905. * @param array $options
  906. * Array of database options.
  907. */
  908. public function __construct(DatabaseConnection $connection, $table, array $options = array()) {
  909. $options['return'] = Database::RETURN_AFFECTED;
  910. parent::__construct($connection, $options);
  911. $this->table = $table;
  912. $this->condition = new DatabaseCondition('AND');
  913. }
  914. /**
  915. * Implements QueryConditionInterface::condition().
  916. */
  917. public function condition($field, $value = NULL, $operator = NULL) {
  918. $this->condition->condition($field, $value, $operator);
  919. return $this;
  920. }
  921. /**
  922. * Implements QueryConditionInterface::isNull().
  923. */
  924. public function isNull($field) {
  925. $this->condition->isNull($field);
  926. return $this;
  927. }
  928. /**
  929. * Implements QueryConditionInterface::isNotNull().
  930. */
  931. public function isNotNull($field) {
  932. $this->condition->isNotNull($field);
  933. return $this;
  934. }
  935. /**
  936. * Implements QueryConditionInterface::exists().
  937. */
  938. public function exists(SelectQueryInterface $select) {
  939. $this->condition->exists($select);
  940. return $this;
  941. }
  942. /**
  943. * Implements QueryConditionInterface::notExists().
  944. */
  945. public function notExists(SelectQueryInterface $select) {
  946. $this->condition->notExists($select);
  947. return $this;
  948. }
  949. /**
  950. * Implements QueryConditionInterface::conditions().
  951. */
  952. public function &conditions() {
  953. return $this->condition->conditions();
  954. }
  955. /**
  956. * Implements QueryConditionInterface::arguments().
  957. */
  958. public function arguments() {
  959. return $this->condition->arguments();
  960. }
  961. /**
  962. * Implements QueryConditionInterface::where().
  963. */
  964. public function where($snippet, $args = array()) {
  965. $this->condition->where($snippet, $args);
  966. return $this;
  967. }
  968. /**
  969. * Implements QueryConditionInterface::compile().
  970. */
  971. public function compile(DatabaseConnection $connection, QueryPlaceholderInterface $queryPlaceholder) {
  972. return $this->condition->compile($connection, $queryPlaceholder);
  973. }
  974. /**
  975. * Implements QueryConditionInterface::compiled().
  976. */
  977. public function compiled() {
  978. return $this->condition->compiled();
  979. }
  980. /**
  981. * Adds a set of field->value pairs to be updated.
  982. *
  983. * @param $fields
  984. * An associative array of fields to write into the database. The array keys
  985. * are the field names and the values are the values to which to set them.
  986. *
  987. * @return UpdateQuery
  988. * The called object.
  989. */
  990. public function fields(array $fields) {
  991. $this->fields = $fields;
  992. return $this;
  993. }
  994. /**
  995. * Specifies fields to be updated as an expression.
  996. *
  997. * Expression fields are cases such as counter=counter+1. This method takes
  998. * precedence over fields().
  999. *
  1000. * @param $field
  1001. * The field to set.
  1002. * @param $expression
  1003. * The field will be set to the value of this expression. This parameter
  1004. * may include named placeholders.
  1005. * @param $arguments
  1006. * If specified, this is an array of key/value pairs for named placeholders
  1007. * corresponding to the expression.
  1008. *
  1009. * @return UpdateQuery
  1010. * The called object.
  1011. */
  1012. public function expression($field, $expression, array $arguments = NULL) {
  1013. $this->expressionFields[$field] = array(
  1014. 'expression' => $expression,
  1015. 'arguments' => $arguments,
  1016. );
  1017. return $this;
  1018. }
  1019. /**
  1020. * Executes the UPDATE query.
  1021. *
  1022. * @return
  1023. * The number of rows affected by the update.
  1024. */
  1025. public function execute() {
  1026. // Expressions take priority over literal fields, so we process those first
  1027. // and remove any literal fields that conflict.
  1028. $fields = $this->fields;
  1029. $update_values = array();
  1030. foreach ($this->expressionFields as $field => $data) {
  1031. if (!empty($data['arguments'])) {
  1032. $update_values += $data['arguments'];
  1033. }
  1034. unset($fields[$field]);
  1035. }
  1036. // Because we filter $fields the same way here and in __toString(), the
  1037. // placeholders will all match up properly.
  1038. $max_placeholder = 0;
  1039. foreach ($fields as $field => $value) {
  1040. $update_values[':db_update_placeholder_' . ($max_placeholder++)] = $value;
  1041. }
  1042. if (count($this->condition)) {
  1043. $this->condition->compile($this->connection, $this);
  1044. $update_values = array_merge($update_values, $this->condition->arguments());
  1045. }
  1046. return $this->connection->query((string) $this, $update_values, $this->queryOptions);
  1047. }
  1048. /**
  1049. * Implements PHP magic __toString method to convert the query to a string.
  1050. *
  1051. * @return string
  1052. * The prepared statement.
  1053. */
  1054. public function __toString() {
  1055. // Create a sanitized comment string to prepend to the query.
  1056. $comments = $this->connection->makeComment($this->comments);
  1057. // Expressions take priority over literal fields, so we process those first
  1058. // and remove any literal fields that conflict.
  1059. $fields = $this->fields;
  1060. $update_fields = array();
  1061. foreach ($this->expressionFields as $field => $data) {
  1062. $update_fields[] = $field . '=' . $data['expression'];
  1063. unset($fields[$field]);
  1064. }
  1065. $max_placeholder = 0;
  1066. foreach ($fields as $field => $value) {
  1067. $update_fields[] = $field . '=:db_update_placeholder_' . ($max_placeholder++);
  1068. }
  1069. $query = $comments . 'UPDATE {' . $this->connection->escapeTable($this->table) . '} SET ' . implode(', ', $update_fields);
  1070. if (count($this->condition)) {
  1071. $this->condition->compile($this->connection, $this);
  1072. // There is an implicit string cast on $this->condition.
  1073. $query .= "\nWHERE " . $this->condition;
  1074. }
  1075. return $query;
  1076. }
  1077. }
  1078. /**
  1079. * General class for an abstracted MERGE query operation.
  1080. *
  1081. * An ANSI SQL:2003 compatible database would run the following query:
  1082. *
  1083. * @code
  1084. * MERGE INTO table_name_1 USING table_name_2 ON (condition)
  1085. * WHEN MATCHED THEN
  1086. * UPDATE SET column1 = value1 [, column2 = value2 ...]
  1087. * WHEN NOT MATCHED THEN
  1088. * INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...
  1089. * @endcode
  1090. *
  1091. * Other databases (most notably MySQL, PostgreSQL and SQLite) will emulate
  1092. * this statement by running a SELECT and then INSERT or UPDATE.
  1093. *
  1094. * By default, the two table names are identical and they are passed into the
  1095. * the constructor. table_name_2 can be specified by the
  1096. * MergeQuery::conditionTable() method. It can be either a string or a
  1097. * subquery.
  1098. *
  1099. * The condition is built exactly like SelectQuery or UpdateQuery conditions,
  1100. * the UPDATE query part is built similarly like an UpdateQuery and finally the
  1101. * INSERT query part is built similarly like an InsertQuery. However, both
  1102. * UpdateQuery and InsertQuery has a fields method so
  1103. * MergeQuery::updateFields() and MergeQuery::insertFields() needs to be called
  1104. * instead. MergeQuery::fields() can also be called which calls both of these
  1105. * methods as the common case is to use the same column-value pairs for both
  1106. * INSERT and UPDATE. However, this is not mandatory. Another convinient
  1107. * wrapper is MergeQuery::key() which adds the same column-value pairs to the
  1108. * condition and the INSERT query part.
  1109. *
  1110. * Several methods (key(), fields(), insertFields()) can be called to set a
  1111. * key-value pair for the INSERT query part. Subsequent calls for the same
  1112. * fields override the earlier ones. The same is true for UPDATE and key(),
  1113. * fields() and updateFields().
  1114. */
  1115. class MergeQuery extends Query implements QueryConditionInterface {
  1116. /**
  1117. * Returned by execute() if an INSERT query has been executed.
  1118. */
  1119. const STATUS_INSERT = 1;
  1120. /**
  1121. * Returned by execute() if an UPDATE query has been executed.
  1122. */
  1123. const STATUS_UPDATE = 2;
  1124. /**
  1125. * The table to be used for INSERT and UPDATE.
  1126. *
  1127. * @var string
  1128. */
  1129. protected $table;
  1130. /**
  1131. * The table or subquery to be used for the condition.
  1132. */
  1133. protected $conditionTable;
  1134. /**
  1135. * An array of fields on which to insert.
  1136. *
  1137. * @var array
  1138. */
  1139. protected $insertFields = array();
  1140. /**
  1141. * An array of fields which should be set to their database-defined defaults.
  1142. *
  1143. * Used on INSERT.
  1144. *
  1145. * @var array
  1146. */
  1147. protected $defaultFields = array();
  1148. /**
  1149. * An array of values to be inserted.
  1150. *
  1151. * @var string
  1152. */
  1153. protected $insertValues = array();
  1154. /**
  1155. * An array of fields that will be updated.
  1156. *
  1157. * @var array
  1158. */
  1159. protected $updateFields = array();
  1160. /**
  1161. * Array of fields to update to an expression in case of a duplicate record.
  1162. *
  1163. * This variable is a nested array in the following format:
  1164. * @code
  1165. * <some field> => array(
  1166. * 'condition' => <condition to execute, as a string>,
  1167. * 'arguments' => <array of arguments for condition, or NULL for none>,
  1168. * );
  1169. * @endcode
  1170. *
  1171. * @var array
  1172. */
  1173. protected $expressionFields = array();
  1174. /**
  1175. * Flag indicating whether an UPDATE is necessary.
  1176. *
  1177. * @var boolean
  1178. */
  1179. protected $needsUpdate = FALSE;
  1180. /**
  1181. * Constructs a MergeQuery object.
  1182. *
  1183. * @param DatabaseConnection $connection
  1184. * A DatabaseConnection object.
  1185. * @param string $table
  1186. * Name of the table to associate with this query.
  1187. * @param array $options
  1188. * Array of database options.
  1189. */
  1190. public function __construct(DatabaseConnection $connection, $table, array $options = array()) {
  1191. $options['return'] = Database::RETURN_AFFECTED;
  1192. parent::__construct($connection, $options);
  1193. $this->table = $table;
  1194. $this->conditionTable = $table;
  1195. $this->condition = new DatabaseCondition('AND');
  1196. }
  1197. /**
  1198. * Sets the table or subquery to be used for the condition.
  1199. *
  1200. * @param $table
  1201. * The table name or the subquery to be used. Use a SelectQuery object to
  1202. * pass in a subquery.
  1203. *
  1204. * @return MergeQuery
  1205. * The called object.
  1206. */
  1207. protected function conditionTable($table) {
  1208. $this->conditionTable = $table;
  1209. return $this;
  1210. }
  1211. /**
  1212. * Adds a set of field->value pairs to be updated.
  1213. *
  1214. * @param $fields
  1215. * An associative array of fields to write into the database. The array keys
  1216. * are the field names and the values are the values to which to set them.
  1217. *
  1218. * @return MergeQuery
  1219. * The called object.
  1220. */
  1221. public function updateFields(array $fields) {
  1222. $this->updateFields = $fields;
  1223. $this->needsUpdate = TRUE;
  1224. return $this;
  1225. }
  1226. /**
  1227. * Specifies fields to be updated as an expression.
  1228. *
  1229. * Expression fields are cases such as counter = counter + 1. This method
  1230. * takes precedence over MergeQuery::updateFields() and it's wrappers,
  1231. * MergeQuery::key() and MergeQuery::fields().
  1232. *
  1233. * @param $field
  1234. * The field to set.
  1235. * @param $expression
  1236. * The field will be set to the value of this expression. This parameter
  1237. * may include named placeholders.
  1238. * @param $arguments
  1239. * If specified, this is an array of key/value pairs for named placeholders
  1240. * corresponding to the expression.
  1241. *
  1242. * @return MergeQuery
  1243. * The called object.
  1244. */
  1245. public function expression($field, $expression, array $arguments = NULL) {
  1246. $this->expressionFields[$field] = array(
  1247. 'expression' => $expression,
  1248. 'arguments' => $arguments,
  1249. );
  1250. $this->needsUpdate = TRUE;
  1251. return $this;
  1252. }
  1253. /**
  1254. * Adds a set of field->value pairs to be inserted.
  1255. *
  1256. * @param $fields
  1257. * An array of fields on which to insert. This array may be indexed or
  1258. * associative. If indexed, the array is taken to be the list of fields.
  1259. * If associative, the keys of the array are taken to be the fields and
  1260. * the values are taken to be corresponding values to insert. If a
  1261. * $values argument is provided, $fields must be indexed.
  1262. * @param $values
  1263. * An array of fields to insert into the database. The values must be
  1264. * specified in the same order as the $fields array.
  1265. *
  1266. * @return MergeQuery
  1267. * The called object.
  1268. */
  1269. public function insertFields(array $fields, array $values = array()) {
  1270. if ($values) {
  1271. $fields = array_combine($fields, $values);
  1272. }
  1273. $this->insertFields = $fields;
  1274. return $this;
  1275. }
  1276. /**
  1277. * Specifies fields for which the database-defaults should be used.
  1278. *
  1279. * If you want to force a given field to use the database-defined default,
  1280. * not NULL or undefined, use this method to instruct the database to use
  1281. * default values explicitly. In most cases this will not be necessary
  1282. * unless you are inserting a row that is all default values, as you cannot
  1283. * specify no values in an INSERT query.
  1284. *
  1285. * Specifying a field both in fields() and in useDefaults() is an error
  1286. * and will not execute.
  1287. *
  1288. * @param $fields
  1289. * An array of values for which to use the default values
  1290. * specified in the table definition.
  1291. *
  1292. * @return MergeQuery
  1293. * The called object.
  1294. */
  1295. public function useDefaults(array $fields) {
  1296. $this->defaultFields = $fields;
  1297. return $this;
  1298. }
  1299. /**
  1300. * Sets common field-value pairs in the INSERT and UPDATE query parts.
  1301. *
  1302. * This method should only be called once. It may be called either
  1303. * with a single associative array or two indexed arrays. If called
  1304. * with an associative array, the keys are taken to be the fields
  1305. * and the values are taken to be the corresponding values to set.
  1306. * If called with two arrays, the first array is taken as the fields
  1307. * and the second array is taken as the corresponding values.
  1308. *
  1309. * @param $fields
  1310. * An array of fields to insert, or an associative array of fields and
  1311. * values. The keys of the array are taken to be the fields and the values
  1312. * are taken to be corresponding values to insert.
  1313. * @param $values
  1314. * An array of values to set into the database. The values must be
  1315. * specified in the same order as the $fields array.
  1316. *
  1317. * @return MergeQuery
  1318. * The called object.
  1319. */
  1320. public function fields(array $fields, array $values = array()) {
  1321. if ($values) {
  1322. $fields = array_combine($fields, $values);
  1323. }
  1324. foreach ($fields as $key => $value) {
  1325. $this->insertFields[$key] = $value;
  1326. $this->updateFields[$key] = $value;
  1327. }
  1328. $this->needsUpdate = TRUE;
  1329. return $this;
  1330. }
  1331. /**
  1332. * Sets the key field(s) to be used as conditions for this query.
  1333. *
  1334. * This method should only be called once. It may be called either
  1335. * with a single associative array or two indexed arrays. If called
  1336. * with an associative array, the keys are taken to be the fields
  1337. * and the values are taken to be the corresponding values to set.
  1338. * If called with two arrays, the first array is taken as the fields
  1339. * and the second array is taken as the corresponding values.
  1340. *
  1341. * The fields are copied to the condition of the query and the INSERT part.
  1342. * If no other method is called, the UPDATE will become a no-op.
  1343. *
  1344. * @param $fields
  1345. * An array of fields to set, or an associative array of fields and values.
  1346. * @param $values
  1347. * An array of values to set into the database. The values must be
  1348. * specified in the same order as the $fields array.
  1349. *
  1350. * @return MergeQuery
  1351. * The called object.
  1352. */
  1353. public function key(array $fields, array $values = array()) {
  1354. if ($values) {
  1355. $fields = array_combine($fields, $values);
  1356. }
  1357. foreach ($fields as $key => $value) {
  1358. $this->insertFields[$key] = $value;
  1359. $this->condition($key, $value);
  1360. }
  1361. return $this;
  1362. }
  1363. /**
  1364. * Implements QueryConditionInterface::condition().
  1365. */
  1366. public function condition($field, $value = NULL, $operator = NULL) {
  1367. $this->condition->condition($field, $value, $operator);
  1368. return $this;
  1369. }
  1370. /**
  1371. * Implements QueryConditionInterface::isNull().
  1372. */
  1373. public function isNull($field) {
  1374. $this->condition->isNull($field);
  1375. return $this;
  1376. }
  1377. /**
  1378. * Implements QueryConditionInterface::isNotNull().
  1379. */
  1380. public function isNotNull($field) {
  1381. $this->condition->isNotNull($field);
  1382. return $this;
  1383. }
  1384. /**
  1385. * Implements QueryConditionInterface::exists().
  1386. */
  1387. public function exists(SelectQueryInterface $select) {
  1388. $this->condition->exists($select);
  1389. return $this;
  1390. }
  1391. /**
  1392. * Implements QueryConditionInterface::notExists().
  1393. */
  1394. public function notExists(SelectQueryInterface $select) {
  1395. $this->condition->notExists($select);
  1396. return $this;
  1397. }
  1398. /**
  1399. * Implements QueryConditionInterface::conditions().
  1400. */
  1401. public function &conditions() {
  1402. return $this->condition->conditions();
  1403. }
  1404. /**
  1405. * Implements QueryConditionInterface::arguments().
  1406. */
  1407. public function arguments() {
  1408. return $this->condition->arguments();
  1409. }
  1410. /**
  1411. * Implements QueryConditionInterface::where().
  1412. */
  1413. public function where($snippet, $args = array()) {
  1414. $this->condition->where($snippet, $args);
  1415. return $this;
  1416. }
  1417. /**
  1418. * Implements QueryConditionInterface::compile().
  1419. */
  1420. public function compile(DatabaseConnection $connection, QueryPlaceholderInterface $queryPlaceholder) {
  1421. return $this->condition->compile($connection, $queryPlaceholder);
  1422. }
  1423. /**
  1424. * Implements QueryConditionInterface::compiled().
  1425. */
  1426. public function compiled() {
  1427. return $this->condition->compiled();
  1428. }
  1429. /**
  1430. * Implements PHP magic __toString method to convert the query to a string.
  1431. *
  1432. * In the degenerate case, there is no string-able query as this operation
  1433. * is potentially two queries.
  1434. *
  1435. * @return string
  1436. * The prepared query statement.
  1437. */
  1438. public function __toString() {
  1439. }
  1440. public function execute() {
  1441. // Wrap multiple queries in a transaction, if the database supports it.
  1442. $transaction = $this->connection->startTransaction();
  1443. try {
  1444. if (!count($this->condition)) {
  1445. throw new InvalidMergeQueryException(t('Invalid merge query: no conditions'));
  1446. }
  1447. $select = $this->connection->select($this->conditionTable)
  1448. ->condition($this->condition)
  1449. ->forUpdate();
  1450. $select->addExpression('1');
  1451. if (!$select->execute()->fetchField()) {
  1452. try {
  1453. $insert = $this->connection->insert($this->table)->fields($this->insertFields);
  1454. if ($this->defaultFields) {
  1455. $insert->useDefaults($this->defaultFields);
  1456. }
  1457. $insert->execute();
  1458. return MergeQuery::STATUS_INSERT;
  1459. }
  1460. catch (Exception $e) {
  1461. // The insert query failed, maybe it's because a racing insert query
  1462. // beat us in inserting the same row. Retry the select query, if it
  1463. // returns a row, ignore the error and continue with the update
  1464. // query below.
  1465. if (!$select->execute()->fetchField()) {
  1466. throw $e;
  1467. }
  1468. }
  1469. }
  1470. if ($this->needsUpdate) {
  1471. $update = $this->connection->update($this->table)
  1472. ->fields($this->updateFields)
  1473. ->condition($this->condition);
  1474. if ($this->expressionFields) {
  1475. foreach ($this->expressionFields as $field => $data) {
  1476. $update->expression($field, $data['expression'], $data['arguments']);
  1477. }
  1478. }
  1479. $update->execute();
  1480. return MergeQuery::STATUS_UPDATE;
  1481. }
  1482. }
  1483. catch (Exception $e) {
  1484. // Something really wrong happened here, bubble up the exception to the
  1485. // caller.
  1486. $transaction->rollback();
  1487. throw $e;
  1488. }
  1489. // Transaction commits here where $transaction looses scope.
  1490. }
  1491. }
  1492. /**
  1493. * Generic class for a series of conditions in a query.
  1494. */
  1495. class DatabaseCondition implements QueryConditionInterface, Countable {
  1496. /**
  1497. * Array of conditions.
  1498. *
  1499. * @var array
  1500. */
  1501. protected $conditions = array();
  1502. /**
  1503. * Array of arguments.
  1504. *
  1505. * @var array
  1506. */
  1507. protected $arguments = array();
  1508. /**
  1509. * Whether the conditions have been changed.
  1510. *
  1511. * TRUE if the condition has been changed since the last compile.
  1512. * FALSE if the condition has been compiled and not changed.
  1513. *
  1514. * @var bool
  1515. */
  1516. protected $changed = TRUE;
  1517. /**
  1518. * The identifier of the query placeholder this condition has been compiled against.
  1519. */
  1520. protected $queryPlaceholderIdentifier;
  1521. /**
  1522. * Constructs a DataBaseCondition object.
  1523. *
  1524. * @param string $conjunction
  1525. * The operator to use to combine conditions: 'AND' or 'OR'.
  1526. */
  1527. public function __construct($conjunction) {
  1528. $this->conditions['#conjunction'] = $conjunction;
  1529. }
  1530. /**
  1531. * Implements Countable::count().
  1532. *
  1533. * Returns the size of this conditional. The size of the conditional is the
  1534. * size of its conditional array minus one, because one element is the the
  1535. * conjunction.
  1536. */
  1537. public function count() {
  1538. return count($this->conditions) - 1;
  1539. }
  1540. /**
  1541. * Implements QueryConditionInterface::condition().
  1542. */
  1543. public function condition($field, $value = NULL, $operator = NULL) {
  1544. if (!isset($operator)) {
  1545. if (is_array($value)) {
  1546. $operator = 'IN';
  1547. }
  1548. elseif (!isset($value)) {
  1549. $operator = 'IS NULL';
  1550. }
  1551. else {
  1552. $operator = '=';
  1553. }
  1554. }
  1555. $this->conditions[] = array(
  1556. 'field' => $field,
  1557. 'value' => $value,
  1558. 'operator' => $operator,
  1559. );
  1560. $this->changed = TRUE;
  1561. return $this;
  1562. }
  1563. /**
  1564. * Implements QueryConditionInterface::where().
  1565. */
  1566. public function where($snippet, $args = array()) {
  1567. $this->conditions[] = array(
  1568. 'field' => $snippet,
  1569. 'value' => $args,
  1570. 'operator' => NULL,
  1571. );
  1572. $this->changed = TRUE;
  1573. return $this;
  1574. }
  1575. /**
  1576. * Implements QueryConditionInterface::isNull().
  1577. */
  1578. public function isNull($field) {
  1579. return $this->condition($field);
  1580. }
  1581. /**
  1582. * Implements QueryConditionInterface::isNotNull().
  1583. */
  1584. public function isNotNull($field) {
  1585. return $this->condition($field, NULL, 'IS NOT NULL');
  1586. }
  1587. /**
  1588. * Implements QueryConditionInterface::exists().
  1589. */
  1590. public function exists(SelectQueryInterface $select) {
  1591. return $this->condition('', $select, 'EXISTS');
  1592. }
  1593. /**
  1594. * Implements QueryConditionInterface::notExists().
  1595. */
  1596. public function notExists(SelectQueryInterface $select) {
  1597. return $this->condition('', $select, 'NOT EXISTS');
  1598. }
  1599. /**
  1600. * Implements QueryConditionInterface::conditions().
  1601. */
  1602. public function &conditions() {
  1603. return $this->conditions;
  1604. }
  1605. /**
  1606. * Implements QueryConditionInterface::arguments().
  1607. */
  1608. public function arguments() {
  1609. // If the caller forgot to call compile() first, refuse to run.
  1610. if ($this->changed) {
  1611. return NULL;
  1612. }
  1613. return $this->arguments;
  1614. }
  1615. /**
  1616. * Implements QueryConditionInterface::compile().
  1617. */
  1618. public function compile(DatabaseConnection $connection, QueryPlaceholderInterface $queryPlaceholder) {
  1619. // Re-compile if this condition changed or if we are compiled against a
  1620. // different query placeholder object.
  1621. if ($this->changed || isset($this->queryPlaceholderIdentifier) && ($this->queryPlaceholderIdentifier != $queryPlaceholder->uniqueIdentifier())) {
  1622. $this->queryPlaceholderIdentifier = $queryPlaceholder->uniqueIdentifier();
  1623. $condition_fragments = array();
  1624. $arguments = array();
  1625. $conditions = $this->conditions;
  1626. $conjunction = $conditions['#conjunction'];
  1627. unset($conditions['#conjunction']);
  1628. foreach ($conditions as $condition) {
  1629. if (empty($condition['operator'])) {
  1630. // This condition is a literal string, so let it through as is.
  1631. $condition_fragments[] = ' (' . $condition['field'] . ') ';
  1632. $arguments += $condition['value'];
  1633. }
  1634. else {
  1635. // It's a structured condition, so parse it out accordingly.
  1636. // Note that $condition['field'] will only be an object for a dependent
  1637. // DatabaseCondition object, not for a dependent subquery.
  1638. if ($condition['field'] instanceof QueryConditionInterface) {
  1639. // Compile the sub-condition recursively and add it to the list.
  1640. $condition['field']->compile($connection, $queryPlaceholder);
  1641. $condition_fragments[] = '(' . (string) $condition['field'] . ')';
  1642. $arguments += $condition['field']->arguments();
  1643. }
  1644. else {
  1645. // For simplicity, we treat all operators as the same data structure.
  1646. // In the typical degenerate case, this won't get changed.
  1647. $operator_defaults = array(
  1648. 'prefix' => '',
  1649. 'postfix' => '',
  1650. 'delimiter' => '',
  1651. 'operator' => $condition['operator'],
  1652. 'use_value' => TRUE,
  1653. );
  1654. $operator = $connection->mapConditionOperator($condition['operator']);
  1655. if (!isset($operator)) {
  1656. $operator = $this->mapConditionOperator($condition['operator']);
  1657. }
  1658. $operator += $operator_defaults;
  1659. $placeholders = array();
  1660. if ($condition['value'] instanceof SelectQueryInterface) {
  1661. $condition['value']->compile($connection, $queryPlaceholder);
  1662. $placeholders[] = (string) $condition['value'];
  1663. $arguments += $condition['value']->arguments();
  1664. // Subqueries are the actual value of the operator, we don't
  1665. // need to add another below.
  1666. $operator['use_value'] = FALSE;
  1667. }
  1668. // We assume that if there is a delimiter, then the value is an
  1669. // array. If not, it is a scalar. For simplicity, we first convert
  1670. // up to an array so that we can build the placeholders in the same way.
  1671. elseif (!$operator['delimiter']) {
  1672. $condition['value'] = array($condition['value']);
  1673. }
  1674. if ($operator['use_value']) {
  1675. foreach ($condition['value'] as $value) {
  1676. $placeholder = ':db_condition_placeholder_' . $queryPlaceholder->nextPlaceholder();
  1677. $arguments[$placeholder] = $value;
  1678. $placeholders[] = $placeholder;
  1679. }
  1680. }
  1681. $condition_fragments[] = ' (' . $connection->escapeField($condition['field']) . ' ' . $operator['operator'] . ' ' . $operator['prefix'] . implode($operator['delimiter'], $placeholders) . $operator['postfix'] . ') ';
  1682. }
  1683. }
  1684. }
  1685. $this->changed = FALSE;
  1686. $this->stringVersion = implode($conjunction, $condition_fragments);
  1687. $this->arguments = $arguments;
  1688. }
  1689. }
  1690. /**
  1691. * Implements QueryConditionInterface::compiled().
  1692. */
  1693. public function compiled() {
  1694. return !$this->changed;
  1695. }
  1696. /**
  1697. * Implements PHP magic __toString method to convert the conditions to string.
  1698. *
  1699. * @return string
  1700. * A string version of the conditions.
  1701. */
  1702. public function __toString() {
  1703. // If the caller forgot to call compile() first, refuse to run.
  1704. if ($this->changed) {
  1705. return NULL;
  1706. }
  1707. return $this->stringVersion;
  1708. }
  1709. /**
  1710. * PHP magic __clone() method.
  1711. *
  1712. * Only copies fields that implement QueryConditionInterface. Also sets
  1713. * $this->changed to TRUE.
  1714. */
  1715. function __clone() {
  1716. $this->changed = TRUE;
  1717. foreach ($this->conditions as $key => $condition) {
  1718. if ($key !== '#conjunction') {
  1719. if ($condition['field'] instanceOf QueryConditionInterface) {
  1720. $this->conditions[$key]['field'] = clone($condition['field']);
  1721. }
  1722. if ($condition['value'] instanceOf SelectQueryInterface) {
  1723. $this->conditions[$key]['value'] = clone($condition['value']);
  1724. }
  1725. }
  1726. }
  1727. }
  1728. /**
  1729. * Gets any special processing requirements for the condition operator.
  1730. *
  1731. * Some condition types require special processing, such as IN, because
  1732. * the value data they pass in is not a simple value. This is a simple
  1733. * overridable lookup function.
  1734. *
  1735. * @param $operator
  1736. * The condition operator, such as "IN", "BETWEEN", etc. Case-sensitive.
  1737. *
  1738. * @return
  1739. * The extra handling directives for the specified operator, or NULL.
  1740. */
  1741. protected function mapConditionOperator($operator) {
  1742. // $specials does not use drupal_static as its value never changes.
  1743. static $specials = array(
  1744. 'BETWEEN' => array('delimiter' => ' AND '),
  1745. 'IN' => array('delimiter' => ', ', 'prefix' => ' (', 'postfix' => ')'),
  1746. 'NOT IN' => array('delimiter' => ', ', 'prefix' => ' (', 'postfix' => ')'),
  1747. 'EXISTS' => array('prefix' => ' (', 'postfix' => ')'),
  1748. 'NOT EXISTS' => array('prefix' => ' (', 'postfix' => ')'),
  1749. 'IS NULL' => array('use_value' => FALSE),
  1750. 'IS NOT NULL' => array('use_value' => FALSE),
  1751. // Use backslash for escaping wildcard characters.
  1752. 'LIKE' => array('postfix' => " ESCAPE '\\\\'"),
  1753. 'NOT LIKE' => array('postfix' => " ESCAPE '\\\\'"),
  1754. // These ones are here for performance reasons.
  1755. '=' => array(),
  1756. '<' => array(),
  1757. '>' => array(),
  1758. '>=' => array(),
  1759. '<=' => array(),
  1760. );
  1761. if (isset($specials[$operator])) {
  1762. $return = $specials[$operator];
  1763. }
  1764. else {
  1765. // We need to upper case because PHP index matches are case sensitive but
  1766. // do not need the more expensive drupal_strtoupper because SQL statements are ASCII.
  1767. $operator = strtoupper($operator);
  1768. $return = isset($specials[$operator]) ? $specials[$operator] : array();
  1769. }
  1770. $return += array('operator' => $operator);
  1771. return $return;
  1772. }
  1773. }
  1774. /**
  1775. * @} End of "addtogroup database".
  1776. */