query.inc 57 KB

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